import DictionariesBehavior from "../../../../core/behavior/dictionaries.behavior";
import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { handleWeChatPayment } from "../../../../utils/util";
import {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import { getOrderDetailMethod, orderPayMethod } from "../../request";
// module/order/pages/select-goods/other-detail.ts
Page({
  behaviors: [PageContainerBehavior, DictionariesBehavior],
  data: {
    title: "",
    id: "",
    totalGoodsCount: 0,
    goodsList: [] as Array<{
      category: string;
      goods: Array<{
        id: string;
        name: string;
        description?: string;
        image: string;
        price: number;
        quantity: number;
        status?: string;
        statusClass?: string;
      }>;
    }>,
    // 三个分类的商品列表
    sellTypeFirstItems: [] as Array<any>, // 实体商品（快递类型在上，线下取货类型在下）
    sellTypeSecondItems: [] as Array<any>, // 线下服务
    sellTypeThirdItems: [] as Array<any>, // 线上权益
    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: {},
  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;
    }
  },
  // 查看物流详情
  goLogistics(e: any) {
    const { id } = e.currentTarget.dataset.goods;
    const { liaison, phone, provinceName, cityName, areaName, detailAddress } = this.data.orderDetail;
    let address = `${provinceName}${cityName ? `${cityName}` : ""
      }${areaName ? `${areaName}` : ""}${detailAddress ? `${detailAddress}` : ""
      }`;
    const goods = JSON.stringify({ ...e.currentTarget.dataset.goods, liaison, phone, address });
    if (id) {
      wx.navigateTo({
        url: `/module/order/pages/logistics-detail/logistics-detail?id=${id}&goods=${goods}`,
      });
    } else {
      wx.showToast({
        title: "无参数id",
        icon: "none",
      })
    }
  },
  // 订单详情
  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 processItems = (items: any[]) => {
          if (!items || !Array.isArray(items)) {
            return [];
          }
          return items.map((item: any) => {
            // 0是一口价 1按穴位/经络次数计费
            const pricingType = item?.conditioningProgramDetail?.pricingType;
            return {
              id: item.id || '', //患者调理方案id
              patientConditioningRecordId: item?.patientConditioningRecordId || '',//调理记录id
              name: item.conditioningProgramName || '',
              description: (() => {
                const convertDose = item?.conditioningProgramDetail?.cpFixedPricingRule?.convertDose
                const dose = convertDose ?? '';
                const unit = item?.conditioningProgramDetail?.cpFixedPricingRule?.convertUnit ?? '次';
                return pricingType === '0' ? `${dose} ${unit}` : `1次`;
              })(),
              sellType: item?.sellType || '', //商品类型 1-实体商品 2-线下服务 3-线上权益
              //start实体商品所用到的字段
              receiptStatus: item?.receiptStatus || '', //收货状态 0-待发货 1-已发货 2-已收货 这个字段用于实体商品的收获状态
              receiptTime: item?.receiptTime || '', //收货时间
              receiptType: item?.receiptType || '', //收货类型 0-快递 1-线下取货
              expressType: item?.expressType || '', //快递类型 0-邮政速递 1-顺丰速运 2-京东快递 3-中通快递 4-圆通速递 5-申通快递 6-韵达快递 7-极兔速递
              expressNo: item?.expressNo || '', //快递单号
              expressTypeName: item?.expressType, //快递公司名称
              // expressTypeIcon: this.getExpressTypeIcon(item?.expressType), //快递公司图标
              //end实体商品所用到的字段
              progress: item?.progress || '', //进度 0-进行中 1-已完成 2-未开始 3-已取消 这个字段用于线下服务商品以及线上权益商品的进度状态
              image: item.conditioningProgramPhoto || '',
              price: item?.unitPrice || 0,
              quantity: item?.totalMeasure || 0,
              statusClass: this.getStatusClass(item?.sellType, item?.progress, item?.receiptStatus, item.expressStatus),
              statusText: this.getGoodsStatusText(item?.sellType, item?.progress, item?.receiptStatus, item.expressStatus),
              isCanEvaluate: item?.isCanEvaluate, //是否可以评价 false-否 true-是
              evaluateTime: item?.evaluateTime, //有评价时间就是已评价，是空就是未评价
            }
          });
        };

        // 分别处理三个数组
        let sellTypeFirstItems = processItems(res.data?.sellTypeFirstItems || []);
        const sellTypeSecondItems = processItems(res.data?.sellTypeSecondItems || []);
        const sellTypeThirdItems = processItems(res.data?.sellTypeThirdItems || []);

        // 对实体商品进行排序：快递类型（receiptType === '0'）在上，线下取货类型（receiptType === '1'）在下
        sellTypeFirstItems = sellTypeFirstItems.sort((a: any, b: any) => {
          const aType = a.receiptType || '';
          const bType = b.receiptType || '';
          if (aType === '0' && bType === '1') {
            return -1;
          }
          if (aType === '1' && bType === '0') {
            return 1;
          }
          return 0;
        });

        this.setData({
          sellTypeFirstItems,
          sellTypeSecondItems,
          sellTypeThirdItems,
        });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.errMsg || "获取订单详情失败",
        icon: "none",
      });
    }
    wx.hideLoading();
  },

  // 去预约
  goAppointment(e: any) {
    const { id } = e.currentTarget.dataset;
    // 去非药物治疗页面
    wx.navigateTo({
      url: `/module/care/pages/offlineTreatment/offlineTreatment?id=${id}`,
    });
  },
  // 立即支付
  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 && 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({ isPaymentLoading: false });
          if (error?.errMsg === 'requestPayment:fail cancel') {
            // 支付取消跳到支付订单页面
            wx.navigateBack({ delta: 1 });
          }
        });
      } 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
    });
  },

  preventTap() { },
  onApplyAfterSale(_e: any) {
    wx.showToast({ title: "申请售后", icon: "none" });
  },
  onReview(e: WechatMiniprogram.TouchEvent) {
    console.log(e.currentTarget.dataset);
    const { evaluateTime } = e.currentTarget.dataset.goods;
    if (evaluateTime) {
      // 单商品评价详情
      wx.navigateTo({
        url: `/module/order/pages/goods-evaluateDetail/goods-evaluateDetail?goodsInfo=${encodeURIComponent(JSON.stringify(e.currentTarget.dataset.goods))}`,
      });

    } else {
      // 去单商品评价页面
      wx.navigateTo({
        url: `/module/order/pages/goods-evaluate/goods-evaluate?goodsInfo=${encodeURIComponent(JSON.stringify(e.currentTarget.dataset.goods))}`,
      });
    }
  },
  // 复制订单号
  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'
        });
      }
    });
  },

  // 获取状态类名
  // sellType: 商品类型 1-实体商品 2-线下服务 3-线上权益
  // progress: 进度状态（用于线下服务和线上权益）：0-进行中 1-已完成 2-未开始
  // receiptStatus: 收货状态（用于实体商品）：0-待发货 1-已发货 2-已收货
  getStatusClass(sellType?: string | number, progress?: string | number, receiptStatus?: string | number, expressStatus?: string): string {
    const type = String(sellType || '');
    // 实体商品 (sellType === 1) 使用 receiptStatus（三种状态）实体商品增加运输中
    if (type === "1") {
      const status = String(receiptStatus || '');
      if (status === "0") {
        return "status-pending"; // 待发货
      } else if (status === "1") {
        return "status-received"; // 已发货
      } else if (status === "2") {
        return "status-completed"; // 已收货
      } else {
        return "status-received"
      }
    }
    // 线下服务 (sellType === 2) 和线上权益 (sellType === 3) 使用 progress（三种状态）
    else if (type === "2" || type === "3") {
      const status = String(progress || '');
      if (status === "0") {
        return "status-pending"; // 进行中
      } else if (status === "1") {
        return "status-completed"; // 已完成
      } else if (status === "2") {
        return "status-closed"; // 未开始
      }
    }
    return "";
  },

  // 获取商品状态文本
  getGoodsStatusText(sellType?: string | number, progress?: string | number, receiptStatus?: string | number, expressStatus?: string): string {
    const type = String(sellType || '');
    // 实体商品 (sellType === 1) 使用 receiptStatus（三种状态）新增expressStatus运输状态
    if (type === "1") {
      const status = String(receiptStatus || '');
      if (expressStatus) {
        return expressStatus
      } else {
        if (status === "0") {
          return "待发货";
        } else if (status === "1") {
          return "已发货";
        } else if (status === "2") {
          return "已收货";
        }
      }
    }
    // 线下服务 (sellType === 2) 和线上权益 (sellType === 3) 使用 progress（三种状态）
    else if (type === "2" || type === "3") {
      const status = String(progress || '');
      if (status === "0") {
        return "进行中";
      } else if (status === "1") {
        return "已完成";
      } else if (status === "2") {
        return "未开始";
      }
    }
    return "";
  },
  // 获取订单状态文本
  getStatusText(status: string | number): string {
    const statusTextMap: Record<string, string> = {
      "0": "待付款",
      "6": "已付款",
      "2": "交易关闭",
      "345": "交易成功",
    };
    return statusTextMap[String(status)] || "";
  },

  // 确认收货
  onConfirmReceipt(e: any) {
    const { patientconditioningrecordid } = e.currentTarget.dataset;
    if (patientconditioningrecordid) {
      const shippedGoods = this.data.sellTypeFirstItems.filter((item: any) => item.receiptStatus === '1');

      if (shippedGoods.length === 0) {
        wx.showToast({
          title: '没有可确认收货的商品',
          icon: 'none'
        });
        return;
      }
      //  去确认收货页面
      wx.navigateTo({
        url: `/module/article/pages/confirm-receiving/confirm-receiving?patientConditioningRecordId=${patientconditioningrecordid as string}&goodsList=${encodeURIComponent(JSON.stringify(shippedGoods))}`,
        fail: (err) => {
          wx.showToast({
            title: err.errMsg || '跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '调理记录id为空',
        icon: 'none'
      });
    }
  },

});
