// pages/orders/order-detail.ts
import { api_executeOrder, api_executePayment, api_queryByParamName, api_userPaymentOrderUnpaid } from "../../api/login";

// 获取应用实例
const app = getApp<IAppOption>()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    serviceShow: true,
    status: 'ing',
    statusList: {
      ing: {
        logo: './images/ing.png',
        title: '确认订单',
        content: '请尽快完成支付,以便我们为您处理订单'
      },
    },
    goodsInfo: {} as any,
    paymentType: null as any, // 支付类型
    paymentChannel: null as any,
    showService: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    this.queryPayType()
    if (options.orderInfo) {
      const goods = JSON.parse(decodeURIComponent(options.orderInfo));
      console.log(goods, 'goods')
      this.setData({
        goodsInfo: goods,
        status: goods.status
      });
    }
  },
  onShow() {
    this.setData({
      serviceShow: true
    })
  },
  onHide() {
    this.setData({
      serviceShow: false
    })
  },
  // 获取后台配置的支付方式
  async queryPayType() {
    try {
      // wxlite_payment_service_provider
      const { data } = await api_queryByParamName({
        paramName: app.globalData.appId
      });
      if (data.code == 200) {
        const paramValue = data.data.paramValue ? JSON.parse(data.data.paramValue) : {}
        this.setData({
          paymentType: paramValue.vendor,
          paymentChannel: paramValue.channel
        });
      }
    } catch (error) {
      console.log(error, "error");
    }
  },
  onPayError(message?: string) {
    wx.hideLoading()
    wx.showToast({
      title: message || '支付取消',
      icon: 'none'
    })
  },
  // 购买
  async onSubmit() {
    wx.showLoading({
      mask: true,
      title: "订单提交中...",
    });
    try {
      const { salePrice, shopId, name, id, orderNo } = this.data.goodsInfo
      if(orderNo) {
        const {data} = await api_userPaymentOrderUnpaid({
          orderNo: orderNo,
          paymentType: 'WECHAT_MINI'
        })
        if (data.code === 200) {
          const { paymentConfig, paymentType, orderNo } = data.data.paymentConfig
          this.onExecutePay(paymentConfig, paymentType, orderNo)
        } else {
          this.onPayError()
        }
      } else {
        const { data } = await api_executeOrder({
          "orderType": "WECHAT_MINI",
          "paymentType": this.data.paymentType,
          "paymentCashAmount": salePrice,
          "paymentCouponAmount": 0,
          "shopId": shopId,
          "openId": app.globalData.userInfo?.liteOpenid,
          "goodsInfos": [{
            "goodsId": id,
            "goodsNum": 1,
            "goodsType": "ACTIVATION_CODE",
            "paymentCashAmount": salePrice,
            "paymentCouponAmount": 0
          }],
          "orderName": name,
          "orderDesc": name
        })
        if (data.code === 200) {
          const { paymentConfig, paymentType, orderNo } = data.data
          this.onExecutePay(paymentConfig, paymentType, orderNo)
        } else if(data.code === 5200) {
          wx.hideLoading()
          wx.showToast({
            title: data.message,
            icon: 'none'
          })
        } else {
          this.onPayError()
        }
      }
    } catch {
      wx.hideLoading()
    }
  },
  async onExecutePay( paymentConfig: any, paymentType: string, orderNo: string) {
    wx.login({
      success: async (wxres: any) => {
        const res = await api_executePayment({
          merOrderNo: paymentConfig.merOrderNo,
          paymentChannel: this.data.paymentChannel || 'wx_lite', 
          paymentType,
          userId: app.globalData.userInfo?.id,
          code: wxres.code,
          wxMiniAppId: app.globalData.appId
        })
        wx.hideLoading()
        if(res.data.code === 200) {
          this.onPay(paymentType, res.data.data.reqParams, orderNo)
        } else {
          this.onPayError(res.data.message)
        }
      },
      fail: () => {
        this.onPayError()
      }
    })
  },
  onPay(paymentType: string, paymentConfig: any, orderNo: string) {
    const isYeePay = paymentType.indexOf('yeepay') !== -1
    const prePayInfo = isYeePay ? JSON.parse(paymentConfig.prePayTn)
      : paymentConfig?.expend
        ? JSON.parse(paymentConfig?.expend?.pay_info)
        : paymentConfig
    const that = this
    wx.requestPayment({
      timeStamp: prePayInfo.timeStamp,
      nonceStr: prePayInfo.nonceStr,
      package: prePayInfo.package ? prePayInfo.package : prePayInfo.packageValue,
      paySign: prePayInfo.paySign,
      signType: prePayInfo.signType ? prePayInfo.signType : 'MD5',
      success() {
        wx.showToast({ title: '支付成功', icon: 'success' });
        wx.redirectTo({
          url: '/pages/orders/order-result?orderNo=' + orderNo
        })
      },
      fail(ressonInfo) {
        console.log('支付失败', ressonInfo)
        that.onPayError()
        const goodsInfo = that.data.goodsInfo
        goodsInfo.orderNo = orderNo
        that.setData({
          goodsInfo
        })
      }
    })
  },
  /** 客服 */
  onService() {
    console.log("showService")
    this.setData({
      showService: true
    })
  },
  changePop(event: { detail: any }) {
    this.setData({
      showService: event.detail
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})