import { api_studentOrderPage } from "../../api/login";
// 获取应用实例
const app = getApp<IAppOption>()
// pages/orders/orders.ts
Page({

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

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    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" : "",
      })
      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.goodsNum, student.activationCodeInfo?.type);
          })
          item.studentPaymentOrderDetails = studentPaymentOrderDetails
        });
        
        const newList = this.data.recordList.concat(rows);
        console.log(newList, "newList");
        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: '等待使用',
      SUCCESS: '交易完成',
      CLOSED: '交易取消',
      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)
    console.log(dataset, item, 'item')
    if(item) {
      const studentPaymentOrderDetails = item.studentPaymentOrderDetails[0]
      const prices: any = this.formatPrice(item.paymentCashAmount)
      const params = {
        // buyNum: "0",
        decimalPart: prices.decimalPart,
        // id: "1856596669912584193",
        integerPart: prices.integerPart,
        userPaymentOrderDetailId: studentPaymentOrderDetails.userPaymentOrderDetailId,
        name: studentPaymentOrderDetails.goodsName,
        num: studentPaymentOrderDetails.goodsNum,
        originalPrice: studentPaymentOrderDetails.originalPrice,
        period: studentPaymentOrderDetails.activationCodeInfo.type,
        pic: studentPaymentOrderDetails.goodsUrl,
        salePrice: item.paymentCashAmount,
        // shopId: "1815717514476302337",
        orderNo: item.orderNo,
        wechatStatus: item.wechatStatus,
        // stockNum: "10",
        typeName: studentPaymentOrderDetails.typeName
      }
      let info = JSON.stringify(params);
      console.log(params, "params")
      info = encodeURIComponent(info);
      wx.navigateTo({
        url: `../orders/order-detail?orderInfo=${info}`,
      })
    }
  },
  onOne() {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  onDetail(e: any) {
    const { dataset } = e.currentTarget
    console.log(e)
    wx.navigateTo({
      url: '../orders/order-result?orderNo=' + dataset.orderno
    })
  },
})