// pages/orders/order-detail.ts
import drawQrcode from "../../utils/weapp.qrcode.esm";
import { api_userPaymentCancelRefund, api_userPaymentOrderDetail } from "../../api/login";

// 获取应用实例
Page({
  /**
   * 页面的初始数据
   */
  data: {
    serviceShow: true,
    status: 'WAIT_PAY',
    statusList: {
      WAIT_PAY: {
        logo: './images/ing.png',
        title: '待付款',
        content: '请尽快完成支付,以便我们为您处理订单'
      },
      PAID: {
        logo: './images/success.png',
        title: '已完成',
        content: '登录「音乐数字课堂」APP使用AI学练'
      },
      CLOSED: {
        logo: './images/error.png',
        title: '已取消',
        content: '您的交易订单已关闭'
      },
      WAIT_USE: {
        logo: './images/wait.png',
        title: '待使用',
        content: '请尽快扫描下方二维码进行激活'
      },
      REFUNDING: {
        logo: './images/refounding.png',
        title: '退款中',
        content: '您的退款申请正在处理,预计7个工作日内完成审核'
      },
      REFUNDED: {
        logo: './images/refounded.png',
        title: '退款成功',
        content: '您的退款已成功处理,感谢您的理解和支持'
      }
    },
    timerCount: 0,
    timer: null as any,
    goodsInfo: {} as any,
    tabIdx: 0, // 当前是从哪个tab来的
    orderNo: "" as string,
    showCanvas: false, // 是否显示二维码
    canvasImg: "" as string,
    refoundStatus: false,
    cancelRefoundStatus: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    if (options.orderNo) {
      this.setData({
        orderNo: options.orderNo,
        tabIdx: options.tabIdx
      }, () => {
        this.getDetail(this.onTimeout)
      });
    }
  },
  onShow() {
    this.setData({
      serviceShow: true
    })
  },
  onHide() {
    this.setData({
      serviceShow: false
    })
  },
  async getDetail(callback?: any) {
    try {
      const { data } = await api_userPaymentOrderDetail(this.data.orderNo);
      if (data.code == 200) {
        const result = data.data || {}
        const goodsInfos = result.goodsInfos || []
        const tempGoods: any = []
        goodsInfos.forEach((item: any) => {
          tempGoods.push({
            ...item,
            shortUrl: item.activationCodeInfo.shortUrl,
            originalPrice: this.formatPrice(item.paymentCashAmount, 'ALL'),
            typeName: this.formatPeriod(item.activationCodeInfo?.times || 1, item.activationCodeInfo.type)
          })
        })
        let refundStyleStr = ''
        if(result.refundStyle === 'TURN_BACK') {
          refundStyleStr = '原路返回'
        } else if(result.refundStyle === 'OFFLINE') {
          refundStyleStr = '线下'
        }
        const goodsInfo = {
          orderNo: result.orderNo,
          createTime: result.createTime,
          wechatStatus: result.wechatStatus,
          goods: tempGoods,
          refundOrderId: result.refundOrderId,
          refundTime: result.refundTime,
          refundAmount: this.formatPrice(result.refundAmount || 0, 'ALL'),
          refundStyleStr
        }
        this.setData({
          goodsInfo,
          status: result.wechatStatus
        }, () => {
          callback && typeof callback === 'function' && callback()
        })
        if(result.wechatStatus != 'CLOSED' || result.wechatStatus != 'WAIT_PAY') {
          const firstGoods = tempGoods[0]
          if(firstGoods?.shortUrl) {
            this.setData({
              showCanvas: true
            }, () => {
              this.createQrCode(firstGoods?.shortUrl, 'canvasCode')
            })
          }
        }
      }
    } catch (error) {
      console.log(error, "error");
    }
  },
  // 格式化价格
  formatPrice(price: number, type?: string) {
    const amountStr = price.toFixed(2)
    const [integerPart, decimalPart] = amountStr.split('.');
    if(type === 'ALL') {
      return amountStr
    }
    return {
      integerPart,
      decimalPart
    }
  },
  // 格式化类型
  formatPeriod(num: number, type: string) {
    const template: any = {
      DAY: "天卡",
      MONTH: "月卡",
      YEAR: "年卡"
    }
    if(type === "YEAR" && num >= 99) {
      return '永久卡'
    }
    return num + template[type]
  },
  onSubmit() {
    wx.redirectTo({
      url: '../index/index'
    })
  },
  setCanvasSize: function () {
    var size = {} as any;
    try {
      const res = wx.getWindowInfo()
      var scale = 750 / 202; //不同屏幕下canvas的适配比例;设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width; //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode(content: any, canvasId: any) {
    const size = this.setCanvasSize();
    drawQrcode({
      width: size.w,
      height: size.h,
      canvasId: canvasId,
      text: content,
      callback: () => {
        // 安卓机上不准确,生成的二维码无法扫描,加延时解决
        setTimeout(() => {
          wx.canvasToTempFilePath(
            {
              canvasId: canvasId,
              success: (res) => {
                this.setData({
                  canvasImg: res.tempFilePath,
                });
                // console.log(res.tempFilePath, 'res.tempFilePath', 'https://oss.dayaedu.com/ktyq/1732174043543.png')
              },
            },
            this
          );
        }, 300);
      },
    });
  },
  onTimeout() {
    // 轮询10次查询订单状态
    const goodsInfo = this.data.goodsInfo
    const timerCount = this.data.timerCount
    const timer = this.data.timer
    if(goodsInfo.wechatStatus === 'WAIT_PAY' && timerCount <= 10) {
      let count = timerCount
      const tempT = setTimeout(async () => {
        count += 1
        await this.getDetail()
        this.setData({
          timer: tempT,
          timerCount: count
        }, () => {
          this.onTimeout()
        })
      }, 3000);
    } else {
      clearTimeout(timer)
    }
  },
  /** 申请退款 */
  async cancelRefound() {
    this.setData({
      cancelRefoundStatus: true
    }, async () => {
      try {
        const {data} = await api_userPaymentCancelRefund(this.data.goodsInfo.refundOrderId)
        // console.log(data, 'data')
        if(data.code == 200) {
          wx.showToast({ title: '取消退款成功', icon: 'none' })
          this.getDetail()
        } else {
          wx.showToast({ title: data.message, icon: 'none' })
        }
        setTimeout(() => {
          this.setData({
            cancelRefoundStatus: false
          })
        }, 500);
      } catch {}
    })
  },
  /** 申请退款 */
  useRefound() {
    this.setData({
      refoundStatus: true
    })
  },
  changeRefoundStatus(e: {detail: any}) {
    this.setData({
      refoundStatus: e.detail
    })
  },
  onRefoundComfirm() {
    this.setData({
      refoundStatus: false
    })
    // wx.navigateBack({
    //   delta: 1
    // })
    this.getDetail()
  },
  onCopy(e: { currentTarget: any }) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.orderno,
      success: () => {
        wx.showToast({title: '复制成功', icon: 'none'})
      },
      fail: () => {
        wx.showToast({title: '复制失败,请稍后再试', icon: 'none'})
      }
    })
  }
})