// pages/goods/orderDetail/orderDetail.js
import {
  get,
  post
} from '../../../utils/http'
import {
  $wuxCountDown
} from '../../../components/dist/index'
import {
  toQrcode
} from '../../../utils/util'
import {
  timestampToDate
} from '../../../utils/time'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    sum: 0, // 防止进入死循环
    detail: {},
    statusTexts: {
      // 状态，-1已取消，0待支付，1已支付，3.已结算
      s_0: '待支付',
      s_1: '待取货',
      s_2: '已完成',
      s_3: '已完成'
    },
    showTips: false, // 是否展示页面顶部提示
    tips: {
      status_0: ['待支付', '逾期未付款，订单将自动取消！'],
      status_1: ['预约成功', '您的预约单已生效，请准时到店体验！'],
      status_2: ['预约成功', '您的预约单已生效，请准时到店体验！']
    },
    pay_methon: 1,
    payNow: false,
    productNum: 0, //订单详情商品总数量
    level: '', //用户充值折扣等级 (0是未拥有等级)
    levelList: {
      1: '0.98',
      4: '0.95',
      7: '0.90',
    }, //折扣列表
    levelPrice: '', //充值等级折扣优惠价格
    toLevelPrice: '', //充值折扣扣除金额
    notSalePrice: 0, //不是秒杀产品的总价
    salePrice: 0, //秒杀产品总价
    goods_price:'' //美妆产品总价格
  },

  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },

  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },


  onClosePay() {
    this.setData({
      payNow: false
    })
  },

  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.getOrderDetail(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAmount()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.c1) this.c1.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  /**
   * 复制订单号
   */
  onCopyOrderNum(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.num || '',
      success(res) {
        console.log(res)
      }
    })
  },

  /**
   * 取消订单
   */
  onCancelOrder() {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否取消当前订单',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          get(
            'v2/api/goods_order/cancel', {
              order_id: that.data.detail.id
            },
            (res) => {
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 2000
              })
              that.getOrderDetail(that.data.detail.id)
            }
          )
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 获取用户充值折扣等级
  getLevel(sale) {
    //sale 是否秒杀价格，1是，0否
    get('/v2/api/user/discount_level', {}, (res) => {
      if (res.code == 200) {
        if (res.data == 0 || this.data.detail.meet_discount == 1 || sale == 1) {
          this.setData({
            level: 0
          })
          return
        }
        let getValue = (item, val) => {
          return item[val]
        }
        this.setData({
          // 优惠的等级
          level: Number(getValue(this.data.levelList, res.data)),
        })
        this.setData({
          // 优惠的折扣 （等级*10）
          tolevel: (this.data.level * 10).toFixed(1)
        })
      }
      // 计算充值折扣
      this.rechargeDiscount()
    })
  },
  // 判断订单里的秒杀产品统计
  salePrice(list) {
    let notSalePrice = '' //非秒杀产品总价格
    let salePrice = '' // 秒杀产品总价格
    let sale = 1
    let goods_price=0
    list.forEach(item => {
      if (item.sale == 0) {
        sale = 0
        return
      }
    })
    list.forEach(item => {
      if (item.sale == 0) {
        notSalePrice = Number(notSalePrice) + Number(item.price) * Number(item.num)
      } else {
        salePrice = Number(salePrice) + Number(item.price) * Number(item.num)
      }
    })
    // 计算美妆产品总价
    list.forEach(item=>{
      goods_price =Number(goods_price)+Number(item.price*item.num)
    })
    this.setData({
      notSalePrice: notSalePrice,
      salePrice: salePrice,
      goods_price:goods_price
    })
    // 获取用户折扣等级
    this.getLevel(sale)
  },
  // 计算充值折扣
  rechargeDiscount() {
    // 计算折扣
    this.setData({
      // 优惠完的价格
      levelPrice: (this.data.notSalePrice * this.data.level + Number(this.data.salePrice)).toFixed(2),
    })
    this.setData({
      // 优惠了多少
      toLevelPrice: (this.data.goods_price - this.data.levelPrice).toFixed(2)
    })
    console.log(this.data.levelPrice, this.data.toLevelPrice);
  },
  onPay: function (e) {
    this.setData({
      payNow: true
    })
  },

  /**
   * 去支付
   */
  payNow(e) {
    let that = this
    post(
      'v2/api/order/goods/pay', {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: that.data.detail.id
      },
      (res) => {

        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
          that.getOrderDetail(that.data.detail.id)
          return
        }

        wx.requestPayment({
          timeStamp: res.data.pay_data.timeStamp,
          nonceStr: res.data.pay_data.nonceStr,
          package: res.data.pay_data.package,
          signType: res.data.pay_data.signType,
          paySign: res.data.pay_data.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              })
              that.getOrderDetail(that.data.detail.id)
            }
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'error'
            })
          }
        })
      }
    )
  },

  /**
   * 申请退款
   */
  onRefundOrder() {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否退款当前订单',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          post(
            'api/goods/refund', {
              order_id: that.data.detail.id
            },
            (res) => {
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 2000
              })
              that.getOrderDetail(that.data.detail.id)
            }
          )
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 获取详情数据
   * /api/order/info
   */
  getOrderDetail(order_id) {
    let that = this
    get(
      'v2/api/goods_order/detail', {
        order_id
      },
      (res) => {
        console.log(res)
        // 判断订单里的秒杀产品统计
        this.salePrice(res.data.good)
        //pay_way:1.支付宝支付，2微信支付，3余额支付
        let pay_way_list = ['支付宝支付', '微信支付', '余额支付']
        res.data['status_text'] = that.data.statusTexts['s_' + res.data.status]
        res.data['pay_way'] = pay_way_list[res.data.pay_way - 1]
        res.data['_pay_time'] = timestampToDate(res.data.pay_time, 'Y-m-d H:i')
        this.setData({
          detail: res.data,
          showTips: [0].indexOf(res.data.status) > -1
        })
        console.log(res.data.good);
        // 设置订单详情商品总数量
        let num = 0
        res.data.good.map(item => {
          num += item.num
        })
        num = Number(num) + Number(res.data.plus.length)
        this.setData({
          productNum: num
        })
        if (res.data.status == 0 && this.data.sum <= 0) {
          this.data.sum++
          that.c1 = new $wuxCountDown({
            date: +new Date() + res.data.invalid_time_seconds * 1000,
            render(date) {
              const hours = this.leadingZeros(date.hours, 2)
              const min = this.leadingZeros(date.min, 2)
              const sec = this.leadingZeros(date.sec, 2)
              that.setData({
                time: `${hours}:${min}:${sec}`
              })
            },
            onEnd() {
              that.c1.stop()
              that.getOrderDetail(that.data.detail.id)
            }
          })
        }
        if (res.data.status == 1) {
          // 生成二维码和条形码。 这里可以是发起后台请求，拿到要转的字符再调用方法来转二维码和条形码
          setTimeout(function () {
            toQrcode('qrcode', res.data.coupon_code, 400, 400)
          }, 200)
        }
      }
    )
  },

  /**
   * 用户允许消息通知
   * /api/message/agree
   */
  messageAgree(ids, order_id) {
    post(
      'api/message/agree', {
        order_id,
        ids
      },
      () => {}
    )
  }
})