import { get, post } from '../../utils/http'
import { $wuxCountDown } from '../../components/dist/index'
import { toQrcode } from '../../utils/util'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    sum: 0, // 防止进入死循环
    detail: {},
    showTips: false, // 是否展示页面顶部提示
    tips: {
      status_0: ['待支付', '逾期未付款，订单将自动取消！'],
      status_1: ['预约成功', '您的预约单已生效，请准时到店体验！'],
      status_2: ['预约成功', '您的预约单已生效，请准时到店体验！']
    },
    status: {
      0: '待付款',
      1: '已预约',
      2: '进行中',
      3: '已结算',
      4: '已取消'
    },
    pay_methon: 1,
    payNow: false,
  },

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

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

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

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

  /**
   * 生命周期函数--监听页面隐藏
   */
  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('用户点击确定')
          post(
            'api/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('用户点击取消')
        }
      }
    })
  },

  onPay: function (e) {
    this.setData({
      payNow: true
    })
  },

  /**
   * 支付
   */
  payNow() {
    let that = this
    that.methonPayOrder()
  },

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

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

        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          that.getOrderDetail(that.data.detail.id)

          get('api/message/ids', {}, (res) => {
            let ids = res.data.ids
            that.onSubmitCh(ids)
          })
          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)
              get('api/message/ids', {}, (res) => {
                let ids = res.data.ids
                wx.requestSubscribeMessage({
                  tmplIds: ids,
                  success(res) {
                    console.log(res)
                    that.messageAgree(ids, that.data.detail.id)
                  },
                  fail(rej) {
                    console.log(rej)
                    that.messageAgree(ids)
                    wx.showToast({
                      title: JSON.stringify(rej),
                      icon: 'error'
                    })
                  }
                })
              })
            }
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'error'
            })
          }
        })
      }
    )
  },

  onSubmitCh(ids) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '支付成功! 是否进行消息提醒',
      success: function (res) {
        if (res.confirm) {
          that.onSubmitTrue(ids)
        } else if (res.cancel) {
          that.messageAgree(ids, that.data.detail.id)
        }
      }
    });
  },

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


  onSubmitTrue(ids) {
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ids,
      success(res) {
        console.log(res)
        that.messageAgree(ids, that.data.detail.id)
      },
      fail(rej) {
        console.log(rej)
        that.messageAgree(ids, that.data.detail.id)
        wx.showToast({
          title: JSON.stringify(rej),
          icon: 'error'
        })
      }
    })
  },

  /**
   * 去支付
   */
  // onPay(e) {
  //   let that = this
  //   post(
  //     'api/pay/project',
  //     {
  //       order_id: that.data.detail.id
  //     },
  //     (res) => {
  //       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)
  //             get('api/message/ids', {}, (res) => {
  //               let ids = res.data.ids
  //               wx.requestSubscribeMessage({
  //                 tmplIds: ids,
  //                 success(res) {
  //                   console.log(res)
  //                   that.messageAgree(ids, that.data.detail.id)
  //                 },
  //                 fail(rej) {
  //                   console.log(rej)
  //                   that.messageAgree(ids)
  //                   wx.showToast({
  //                     title: JSON.stringify(rej),
  //                     icon: 'error'
  //                   })
  //                 }
  //               })
  //             })
  //           }
  //         },
  //         fail(res) {
  //           wx.showToast({
  //             title: '支付失败',
  //             icon: 'error'
  //           })
  //         }
  //       })
  //     }
  //   )
  // },

  /**
   * 申请退款
   */
  onRefundOrder() {
    let that = this
    let showData = {
      title: '提示',
      content: '是否申请退款',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          post(
            'api/order/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('用户点击取消')
        }
      }
    }
    let hasValidProduct = that.data.detail.products.length > 0
    if (hasValidProduct) {
      hasValidProduct = false
      that.data.detail.products.map((item) => {
        hasValidProduct = item.status == 1 ? true : hasValidProduct
      })
    }
    if (hasValidProduct) {
      showData = Object.assign(showData, {
        title: '订单取消确认',
        content: '检测到该订单有升级套餐产品，将一并取消。您确认要取消吗？',
        cancelText: '再想想',
        cancelColor: '#000000',
        confirmText: '确认取消',
        confirmColor: '#FA7D22'
      })
    }
    wx.showModal(showData)
  },

  /**
   * 申请退款 -- 项目升级产品
   */
  onRefundProjectProductOrder(e) {
    let product = e.currentTarget.dataset.item
    let that = this
    wx.showModal({
      title: '订单取消确认',
      content:
        '检测到该订单为项目升级产品，取消后您将只能享受基础产品。您确认要取消吗？',
      cancelText: '再想想',
      cancelColor: '#000000',
      confirmText: '确认取消',
      confirmColor: '#FA7D22',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          post(
            'api/product/refund',
            {
              product_id: product.id,
              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(
      'api/order/info',
      {
        order_id
      },
      (res) => {
        console.log(res)
        this.setData({
          detail: res.data,
          showTips: [0, 1, 2].indexOf(res.data.status) > -1
        })
        if (res.data.status == 0 && this.data.sum <= 0) {
          this.data.sum++
          that.c1 = new $wuxCountDown({
            date: +new Date() + res.data.invalid_time * 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)
            }
          })
        }
      }
    )
  },

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