import { api_executePayment, api_queryByParamName, api_studentOrderPage, api_userPaymentCancelRefund, api_userPaymentOrderUnpaid } from "../../api/login";
// 获取应用实例
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: [
      {
        id: 0,
        label: "全部",
      },
      {
        id: 1,
        label: "待付款",
      },
      {
        id: 2,
        label: "待使用",
      },
      {
        id: 3,
        label: "已完成",
      },
      {
        id: 4,
        label: "已取消",
      },
      {
        id: 5,
        label: "售后",
      },
      // {
      //   id: 6,
      //   label: "已退款",
      // },
    ],
    tabIdx: 0, // 当前选中的tab索引
    page: 1,
    rows: 10,
    recordList: [],
    maxPage: 1, // 总分页数
    refoundStatus: false,
    cancelRefoundStatus: false,
    goodsInfo: {}, // 选中的数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },
  onShow() {
    this.setData({
      page: 1,
      maxPage: 1,
      recordList: [],
    }, () => {
      this.getList()
    })
  },
  /** 切换分类 */
  switchTab(e: { currentTarget: { dataset: { idx: any } } }) {
    const idx = e.currentTarget.dataset.idx;
    if (idx != this.data.tabIdx) {
      this.setData(
        {
          tabIdx: idx,
          page: 1,
          maxPage: 1,
          recordList: [],
        },
        () => {
          this.getList();
        }
      );
    }
  },
  async getList() {
    wx.showLoading({
      mask: true,
      title: "加载中...",
    });
    const currentPage = this.data.page,
      currentRow = this.data.rows,
      tabIdx = this.data.tabIdx;
    try {
      // @ApiModelProperty("订单状态 WAIT_PAY:待付款,WAIT_USE:待使用,SUCCESS:已完成,CLOSE:已取消")
      const { data } = await api_studentOrderPage({
        openId: app.globalData.userInfo?.liteOpenid,
        page: currentPage,
        rows: this.data.rows,
        wechatOrderStatus: tabIdx == 0 ? "" : tabIdx == 1 ? "WAIT_PAY" : tabIdx == 2 ? "WAIT_USE" : tabIdx == 3 ? "PAID" : tabIdx == 4 ? "CLOSED" : tabIdx == 5 ? 'SALE_AFTER' : "",
      })
      if (data.code == 200) {
        const { rows, total } = data.data;
        rows.forEach((item: any) => {
          item.amount = this.formatPrice(item.paymentCashAmount, 'ALL')
          item.statusName = this.formatOrderStatus(item.wechatStatus)
          const studentPaymentOrderDetails = item.studentPaymentOrderDetails || [];
          studentPaymentOrderDetails.forEach((student: any) => {
            student.originalPrice = this.formatPrice(student.paymentCashAmount, 'ALL');
            student.typeName = this.formatPeriod(student.activationCodeInfo?.times || 1, student.activationCodeInfo?.type);
          })
          item.studentPaymentOrderDetails = studentPaymentOrderDetails
        });
        
        const newList = this.data.recordList.concat(rows);
        this.setData(
          {
            recordList: newList,
            maxPage: Math.ceil(total / currentRow),
          },
          () => wx.hideLoading()
        );
      } else {
        wx.hideLoading();
      }
    } catch(e) {
      console.log(e, 'e')
      wx.hideLoading()
    }
  },
  // 格式化中文
  formatOrderStatus(status: string) {
    // 订单状态 WAIT_PAY:待付款,  WAIT_USE:待使用, SUCCESS:已完成, CLOSE:已取消
    const template: any = {
      WAIT_PAY: '等待付款',
      WAIT_USE: '等待使用',
      PAID: '交易完成',
      CLOSED: '交易取消',
      REFUNDING: '售后中',
      REFUNDED: '售后成功'
    }
    return template[status]
  },
  // 格式化价格
  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) {
    if(!num || !type) {
      return ''
    }
    const template: any = {
      DAY: "天卡",
      MONTH: "月卡",
      YEAR: "年卡"
    }
    if(type === "YEAR" && num >= 99) {
      return '永久卡'
    }
    return num + template[type]
  },
  /** 加载更多 */
  loadMore() {
    const currentPage = this.data.page;
    if (this.data.page >= this.data.maxPage) {
      // wx.showToast({
      //   title: "没有更多数据了",
      //   icon: "none",
      //   duration: 1000,
      // });
    } else {
      this.setData(
        {
          page: currentPage + 1,
        },
        () => {
          this.getList();
        }
      );
    }
  },
  onPay(e: any) {
    const { dataset } = e.currentTarget
    const item: any = this.data.recordList.find((item: any) => item.id === dataset.id)
    if(item) {
      this.onSubmit({
        orderNo: item.orderNo
      })
    }
  },
  onOne() {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  onDetail(e: any) {
    const { dataset } = e.currentTarget
    if(dataset.wechatstatus === "WAIT_PAY") {
      this.onSubmit({orderNo: dataset.orderno})
    } else {
      wx.navigateTo({
        url: `../orders/order-result?orderNo=${dataset.orderno}&tabIdx=${this.data.tabIdx}`
      })
    }
  },
  // 购买
  async onSubmit(goodsInfo: any) {
    wx.showLoading({
      mask: true,
      title: "订单提交中...",
    });
    try {
      const { orderNo } = goodsInfo
      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()
      }
    } 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.onPaying(paymentType, res.data.data.reqParams, orderNo)
        } else {
          this.onPayError(res.data.message)
        }
      },
      fail: () => {
        this.onPayError()
      }
    })
  },
  onPaying(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' });
        // that.onRefoundComfirm()
      },
      fail(ressonInfo) {
        console.log('支付失败', ressonInfo)
        that.onPayError()
      }
    })
  },
  // 获取后台配置的支付方式
  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 onRefounded(e: any) {
    const { dataset } = e.currentTarget
    const item: any = this.data.recordList.find((item: any) => item.id === dataset.id)
    console.log(dataset, item, 'item')
    if(!item) {
      return
    }

    if(item.wechatStatus === "REFUNDING") {
      this.setData({
        cancelRefoundStatus: true
      }, async () => {
        try {
          const refundOrderId = item.refundOrderId
          const {data} = await api_userPaymentCancelRefund(refundOrderId)
          wx.hideLoading()
          if(data.code == 200) {
            wx.showToast({ title: '取消退款成功', icon: 'none' })
            this.onRefoundComfirm()
          } else {
            wx.showToast({ title: data.message, icon: 'none' })
          }
        } catch {
        }
      })
     
    } else {
      const { orderNo, studentPaymentOrderDetails } = item
      const goodsInfo: any = {
        orderNo,
        goods: []
      }
      if(Array.isArray(studentPaymentOrderDetails)) {
        studentPaymentOrderDetails.forEach((item: any) => {
          goodsInfo.goods.push({
            ...item,
            id: item.userPaymentOrderDetailId,
            currentPrice: item.paymentCashAmount
          })
        })
      }
      this.setData({
        goodsInfo,
        cancelRefoundStatus: true,
        refoundStatus: true
      })
    }
  },
  changeRefoundStatus(e: {detail: any}) {
    this.setData({
      refoundStatus: e.detail,
      cancelRefoundStatus: false,
    })
  },
  onRefoundComfirm() {
    const that = this
    this.setData({
      refoundStatus: false
    })
    setTimeout(() => {
      that.setData({
        page: 1,
        maxPage: 1,
        cancelRefoundStatus: false,
        recordList: [],
      }, () => {
        this.getList()
      })
    }, 1500);
  },
})