import DictionariesBehavior from "../../../../core/behavior/dictionaries.behavior";
import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { handleWeChatPayment } from "../../../../utils/util";
import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import { getOrderDetailMethod, orderPayMethod } from "../../request";
// module/order/pages/select-goods/select-goods.ts
Page({
  behaviors: [PageContainerBehavior, DictionariesBehavior, tickleBehavior],
  properties: {
    schemeId: { type: String, value: "" },
  },
  data: {
    title: "",
    id: "",
    totalGoodsCount: 0,
    goodsList: [] as Array<{
      category: string;
      goods: Array<{
        id: string;
        name: string;
        description?: string;
        image: string;
        price: number;
      }>;
    }>,
    selectAll: true,
    selectedCount: 0,
    totalPrice: 0,
    orderDetail: {},
    remarkLength: 0,
    showDetail: false,
    isPaymentLoading: false, // 支付加载状态
    orderStatus: "", // 订单状态：pending, paid, closed, completed
  },
  onLoad(options: any) {
    const remark = (this.data.orderDetail as any)?.remark || '';
    this.setData({
      remarkLength: remark.length
    });
    if (options.id) {
      this.setData({ id: options.id });
    }
    if (options.status) {
      this.statusType(options.status);
    }

  },
  onShow() {
    if (this.data.id) {
      this.load(this.data.id);
    }
  },
  observers: {},
  // 切换收货地址
  changeAddress(_event: any) {
    // 只有待付款状态才能切换地址
    if (this.data.orderStatus !== "pending") {
      return;
    }
    wx.navigateTo({
      url:
        "/module/article/pages/manage-address/manage-address?type=orderDetail&orderId=" +
        this.data.id,
    });
  },
  statusType(status: any) {
    const code = status == null ? "" : String(status);
    switch (code) {
      case "0":
        this.setData({ orderStatus: "pending", title: "待付款" });
        break;
      case "6":
        this.setData({ orderStatus: "received", title: "已付款" });
        break;
      case "2":
        this.setData({ orderStatus: "closed", title: "交易关闭" });
        break;
      case "345":
        this.setData({ orderStatus: "completed", title: "交易成功" });
        break;
      default:
        this.setData({ orderStatus: "", title: "" });
        break;
    }
  },
  // 订单详情
  async load(id: string) {
    wx.showLoading({ title: "加载中" });
    try {
      const res = await getOrderDetailMethod(id);
      if (res && res.data) {
        this.setData({ orderDetail: res.data });
        if (
          !res.data.liaison ||
          !res.data.phone ||
          !res.data.provinceName ||
          !res.data.cityName ||
          !res.data.areaName ||
          !res.data.detailAddress
        ) {
          this.setData({
            showDetail: true,
          });
        } else {
          this.setData({
            showDetail: false,
          });
          this.setData({
            name: res.data.liaison ? `${res.data.liaison}` : "",
            phone: res.data.phone ? `${res.data.phone}` : "",
            address: `${res.data.provinceName}${res.data.cityName ? `${res.data.cityName}` : ""
              }${res.data.areaName ? `${res.data.areaName}` : ""}${res.data.detailAddress ? `${res.data.detailAddress}` : ""
              }`,
          });
        }
        // 0：待付款
        // 2 交易关闭
        // 6 已付款
        // 345  交易成功
        this.statusType(res.data.orderStatus);
        const groupForPendingPay = res.data?.groupForPendingPay || {};
        const goodsList: any[] = [];
        let totalGoodsCount = 0;

        // 遍历 groupForPendingPay
        Object.keys(groupForPendingPay).forEach((categoryName: string) => {
          const categoryItems = groupForPendingPay[categoryName] || [];
          if (categoryItems.length > 0) {
            const goods = categoryItems.map((item: any) => {
              const pricingType = item?.conditioningProgramDetail?.pricingType; //0是一口价 1按穴位/经络次数计费
              // 合计的商品件数
              totalGoodsCount += 1;
              return {
                id: item.id || '',
                name: item.conditioningProgramName || '',
                description: (() => {
                  const dose = item?.convertDose ?? '';
                  const unit = item?.convertUnit ?? '';
                  return pricingType === '0' ? `${dose} ${unit}` : `1次`;
                })(),

                image: item.conditioningProgramPhoto || '',
                // price: item.totalPrice || 0,
                price: item?.unitPrice || 0,
                quantity: item?.totalMeasure || 0,
              };
            });

            goodsList.push({
              category: categoryName,
              goods: goods
            });
          }
        });
        this.setData({ goodsList, totalGoodsCount });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    }
    wx.hideLoading();
  },

  // 立即支付
  async onPayment() {
    if (this.data.isPaymentLoading) {
      return;
    }
    this.setData({ isPaymentLoading: true });
    try {
      // 调用支付接口
      const payResult = await orderPayMethod(this.data.id, (this.data.orderDetail as any)?.remark || '');
      if (payResult) {
        const paymentParams = payResult;
        handleWeChatPayment(paymentParams, (res: any) => {
          // 支付成功，跳转到成功页面
          wx.redirectTo({
            url: "/module/article/pages/success-page/success-page?title=订单支付成功",
          });
        }, (error: any) => {
          this.setData({ isPaymentLoading: false });
          if (error?.errMsg === 'requestPayment:fail cancel') {
          // 支付取消跳到支付订单页面
            wx.navigateBack({ delta: 1 });
          }
          console.log(error, '支付失败');
          // wx.showToast({
          //   title: error?.errMsg || error?.message || "支付失败，请重试",
          //   icon: "none",
          // });
        });
      } else {
        wx.showToast({
          title: payResult.errMsg,
          icon: "none",
        });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg,
        icon: "none",
      });
    } finally {
      this.setData({ isPaymentLoading: false });
    }
  },

  // 备注输入处理
  onRemarkInput(e: any) {
    const value = e.detail.value;
    const length = value.length;

    // 限制最大长度为200
    if (length > 200) {
      return;
    }

    this.setData({
      'orderDetail.remark': value,
      remarkLength: length
    });
  },

  // 复制订单号
  copyOrderNo(e: any) {
    const orderNo = e.currentTarget.dataset.orderno;
    if (!orderNo) {
      getTickleContext.call(this).showWarnMessage("订单号为空");
      return;
    }
    wx.setClipboardData({
      data: orderNo,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  onGoBack() {
    wx.navigateBack({
      delta: 1
    });
  },

});
