import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior from "../../../../core/behavior/tickle.behavior";
import { orderConfirmReceiptMethod } from "../../request";
// module/article/pages/confirm-receiving/confirm-receiving.ts
Page({
  behaviors: [
    PageContainerBehavior,
    tickleBehavior,
  ],
  data: {
    patientConditioningRecordId: '',
    orderId: '',
    goodsList: [] as Array<{
      id: number;
      name: string;
      description: string;
      image: string;
      checked: boolean;
    }>
  },
  async onLoad(options: any) {
    console.log("onLoad", options)
    if (options.patientConditioningRecordId) {
      this.setData({ patientConditioningRecordId: options.patientConditioningRecordId });
    }
    if (options.goodsList) {
      const goodsList = JSON.parse(decodeURIComponent(options.goodsList));
      // 为每个商品添加 checked 属性，默认全部选中
      const goodsListWithChecked = goodsList.map((item: any) => ({
        ...item,
        checked: true
      }));
      this.setData({ goodsList: goodsListWithChecked });
    }
    console.log("goodsList", this.data.goodsList)
  },
  properties: {
  },
  copyExpressNo(e: any) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.no,
      success: () => wx.showToast({ title: '已复制', icon: 'none' })
    });
  },
  onCancel() {
    // 关闭弹窗或返回
    wx.navigateBack();
  },
  // 商品复选框变化
  onGoodsCheckChange(e: any) {
    const { index } = e.currentTarget.dataset;
    const checked = e.detail.checked;
    const goodsList = this.data.goodsList;
    goodsList[index].checked = checked;
    this.setData({ goodsList });
  },
  // 确认收货逻辑
  async onConfirmReceiving() {
    // 获取选中的商品id数组
    const selectedIds = this.data.goodsList
      .filter((item: any) => item.checked)
      .map((item: any) => item.id);

    if (selectedIds.length === 0) {
      wx.showToast({ title: '请至少选择一个商品', icon: 'none' });
      return;
    }
    console.log(selectedIds, "selectedIds======选中的商品id")
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确认收货后，订单将无法修改，请确认无误后再进行操作',
      success: (res) => {
        if (res.confirm) {
          that.confirmReceiving(selectedIds);
        }
      }
    });
  },
  async confirmReceiving(selectedIds: number[]) {
    try {
      await orderConfirmReceiptMethod(this.data.patientConditioningRecordId, selectedIds);
      wx.showToast({ title: '收货成功', icon: 'success' });
      setTimeout(() => {
        wx.redirectTo({
          url: "/module/article/pages/success-page/success-page?title=收货成功",
        });
      }, 1000);

    } catch (error: any) {
      wx.showToast({ title: error.errMsg || '收货失败', icon: 'none' });
    }
  }
})