import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import { handleWeChatPayment } from "../../../../utils/util";
import {
  orderListMethod,
  orderCancelMethod,
  orderPayMethod,
} from "../../request";
import I18nBehavior from "../../../../i18n/behavior";

// module/article/pages/order-list/order-list.ts
const i18n = {
  orderText: {
    mineOrder: "我的服务",
    paying: "待确认",
    paid: "已确认",
    paySuccess: "已完成",
  },
};
Page({
  behaviors: [PageContainerBehavior, tickleBehavior,I18nBehavior],
  properties: {},
  data: {
    i18n,
    showConfirm: false,
    currentTab: "all", // 当前选中的标签
    orders: [],
    filteredOrders: [], // 用于存储过滤后的订单
    patientId: 0,
    id: "",
    statusObj: {
      0: "待付款",
      // 6: "待收货",
      6: "已付款",
      345: "交易成功",
      2: "交易关闭",
    },
    statusClassObj: {
      0: "status-pending",
      6: "status-received",
      345: "status-completed",
      2: "status-closed",
    },
    selectedAddress: null,
    paying: false,
    payingId: '',
    showAddress: false,
    // 节流控制
    throttleTimers: {} as Record<string, boolean>,
    expandedItems: {} as Record<string, boolean>,
  },
  computed: {},
  // 节流 - 防止短时间内重复点击
  throttle(func: Function, delay: number = 1000, key: string = "default") {
    return (...args: any[]) => {
      // 如果该按钮正在节流中，直接返回
      if (this.data.throttleTimers[key]) {
        return;
      }

      // 设置节流定时器
      this.setData({
        [`throttleTimers.${key}`]: true,
      });

      // 执行函数
      const result = func.apply(this, args);

      // 延迟清除节流状态
      setTimeout(() => {
        this.setData({
          [`throttleTimers.${key}`]: false,
        });
      }, delay);

      return result;
    };
  },
  onLoad(options: any) {
    // 读取 tab 参数，默认为 all
    const tab = options?.tab || "all";
    this.setData({ currentTab: tab });
  },
  onShow() {
    this.filterOrdersList(this.data.currentTab);
  },
  // 切换tab
  onTabChange(event: any) {
    const type = event.detail.value;
    this.setData({ currentTab: type });
    this.filterOrdersList(type);
  },
  //  获取列表数据
  async getOrderList(progress: string) {
    const patientId = wx.getStorageSync("patientId");
    if (!patientId) {
      getTickleContext.call(this).showWarnMessage("请先登录");
      return;
    }
    const res = await orderListMethod(patientId, progress);
    if (res && res.data) {
      res.data.forEach((item: any) => {
        item.address = `${item.provinceName}${item.cityName}${item.areaName}${item.detailAddress}`;
        item.liaison =
          item.liaison !== null && item.liaison !== undefined
            ? item.liaison
            : "";
        item.phone =
          item.phone !== null && item.phone !== undefined ? item.phone : "";
        if (
          !item.provinceName ||
          !item.cityName ||
          !item.areaName ||
          !item.detailAddress ||
          !item.liaison ||
          !item.phone
        ) {
          item.showAddress = false;
        } else {
          item.showAddress = true;
        }
        if (item.items && Array.isArray(item.items)) {
          item.items = item.items.map((subItem: any) => {
            return {
              id: subItem.id || '',
              name: subItem.conditioningProgramName || '',
              description: (() => {
                const dose = subItem?.convertDose ?? '1';
                const unit = subItem?.convertUnit ?? '次';
                return `${dose} ${unit}`;
              })(),
              photo: subItem.conditioningProgramPhoto || '',
              price: subItem.unitPrice || 0,
              quantity: subItem?.totalMeasure || 0,
            }
          });
        }
      });
      // 批量初始化展开状态为false（默认折叠）
      const expandedItems: Record<string, boolean> = {};
      res.data.forEach((item: any) => {
        if (!this.data.expandedItems[item.id]) {
          expandedItems[item.id] = false;
        }
      });
      if (Object.keys(expandedItems).length > 0) {
        this.setData({ expandedItems: { ...this.data.expandedItems, ...expandedItems } });
      }
      this.setData({ orders: res.data });
    }
  },
  // 过滤订单l列表
  filterOrdersList(type: any) {
    // 根据当前选中的标签过滤订单
    switch (type) {
      // 全部订单
      case "all":
        this.getOrderList("");
        break;
      // 待付款订单
      case "pending":
        this.getOrderList("0");
        break;
      // 已付款订单
      case "paid":
        this.getOrderList("6");
        break;
      // 交易完成订单
      case "completed":
        this.getOrderList("345");
        break;
      // 交易关闭订单
      case "closed":
        this.getOrderList("2");
        break;
      default:
        break;
    }
  },
  // 订单支付
  onPay: function (event: any) {
    return this.throttle(
      async (e: any) => {
        const orderId = e.currentTarget.dataset.id;
        if (this.data.payingId) return; // 防重复
        this.setData({ paying: true, payingId: orderId });
        try {
          // 调用支付接口
          const payResult = await orderPayMethod(orderId);
          if (payResult && payResult.data) {
            const paymentParams = payResult.data;
            handleWeChatPayment(paymentParams, (res: any) => {
              // 支付成功，跳转到成功页面
              wx.redirectTo({
                url: "/module/article/pages/success-page/success-page?title=订单支付成功",
              });
            }, (error: any) => {
              this.setData({ paying: false, payingId: '' });
              if (error.errMsg === 'requestPayment:fail cancel') {
                wx.showToast({
                  title: "支付已取消",
                  icon: "none",
                });
              } else {
                wx.showToast({
                  title: error.errMsg || "支付失败，请重试",
                  icon: "none",
                });
              }
            });
          } else {
            wx.showToast({
              title: payResult.errMsg,
              icon: "none",
            });
          }
        } catch (error: any) {
          wx.showToast({
            title: error.errMsg,
            icon: "none",
          });
        } finally {
          this.setData({ paying: false, payingId: '' });
        }
      },
      2000,
      "pay"
    )(event);
  },
  // 查看物流
  onSeeLogistics: function (e: any) {
    return this.throttle(
      (event: any) => {
        wx.showToast({
          title: "暂未开通",
          icon: "none",
        });
      },
      2000,
      "logistics"
    )(e);
  },
  // 切换地址
  changeAddress: function (e: any) {
    return this.throttle(
      (event: any) => {
        const orderStatus = event.currentTarget.dataset.status;
        const id = event.currentTarget.dataset.id;
        // 根据订单状态判断是否可以切换地址. 待付款状态下可以切换地址
        if (orderStatus === "0") {
          wx.navigateTo({
            url:
              "/module/article/pages/manage-address/manage-address?type=orderList&orderId=" +
              id,
          });
        }
      },
      2000,
      "changeAddress"
    )(e);
  },
  // 打开取消订单弹窗
  onCancel: function (event: any) {
    return this.throttle(
      (e: any) => {
        const orderId = e.currentTarget.dataset.id;
        // 处理订单取消逻辑
        this.setData({ id: orderId });
        this.setData({ showConfirm: true });
      },
      2000,
      "cancel"
    )(event);
  },
  // 取消订单
  async cancelOrder(id: string) {
    this.setData({ showConfirm: true });
    try {
      await orderCancelMethod(id);
      /* 取消订单逻辑 */
      this.setData({ showConfirm: false });
      wx.navigateTo({
        url: "/module/article/pages/success-page/success-page?title=订单取消成功",
      });
    } catch (error: any) {
      getTickleContext.call(this).showWarnMessage(error.errMsg);
    }
  },
  // 确认取消订单
  confirmCancelDialog() {
    this.cancelOrder(this.data.id);
  },
  // 关闭取消订单弹窗
  closeDialog() {
    this.setData({ showConfirm: false });
  },
  // 确认收货
  onConfirmReceiving: function (e: any) {
    return this.throttle(
      (event: any) => {
        const orderId = event.currentTarget.dataset.id;
        wx.navigateTo({
          url: `/module/article/pages/confirm-receiving/confirm-receiving?orderId=${orderId}`,
        });
      },
      2000,
      "confirmReceiving"
    )(e);
  },
  // 切换地址
  onChangeAddress(e: any) {
    const orderId = e.currentTarget.dataset.id;
    // 打开地址选择器，选择后更新对应订单的地址
    // 伪代码
    wx.chooseAddress({
      success: (res) => {
        // 假设你有 orders 数组
        const idx = this.data.orders.findIndex(
          (o: any) => o.orderId === orderId
        );
        if (idx !== -1) {
          this.setData({
            [`orders[${idx}].address`]: res.detailInfo,
          });
        }
      },
    });
  },
  // 订单详情
  onOrderDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    const status = e.currentTarget.dataset.status;
    if (status === '0') {
      wx.navigateTo({
        url: `/module/order/pages/order-detail/order-detail?id=${id}&status=${status}`,
      });
    } else {
      wx.navigateTo({
        url: `/module/order/pages/other-detail/other-detail?id=${id}&status=${status}`,
      });
    }
  },
  //回到我的页面
  goMine() {
    wx.redirectTo({
      url: "/pages/mine/mine",
    });
  },
  // 切换服务包展开/收起
  toggleServicePackages(e: any) {
    const orderId = e.currentTarget.dataset.id;
    const currentExpanded = this.data.expandedItems[orderId] || false;
    this.setData({
      [`expandedItems[${orderId}]`]: !currentExpanded,
    });
  },
});
