import I18nBehavior from "../../../../i18n/behavior";
import { getOfflineTreatmentListMethod } from "../../request";

Page({
  behaviors: [I18nBehavior],
  data: {
    i18n: {
      offlineTreatment: { title: '线下', ing: '进行中', finish: '完成' },
    },
    currentTab: "",
    treatmentList: [],
    isLoading: false,
    treatmentId: "",
  },
  async onLoad(options: any) {
    console.log(options, '传过来的参数')
    if (options.id) {
      this.setData({
        treatmentId: options.id,
      });
    }
    // await this.getOfflineTreatmentList("");
  },
  async onShow() {
    await this.getOfflineTreatmentList("");
  },
  // 跳转到核销记录
  onRecord(e: any) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      wx.navigateTo({
        url: `/module/care/pages/care/verifyRecord?id=${id}`,
      });
    }
  },
  // 去预约
  goAppointment(e: any) {

    const { item } = e.currentTarget.dataset;
    const { offlineId, conditioningProgramName, offlineDuration, itemImgSecond, estimatedStartDate } = item;
    const goodsInfo = {
      name: conditioningProgramName || '',
      duration: offlineDuration || 0,
      image: itemImgSecond || '',
      offlineId: offlineId || '',
      serviceTime: estimatedStartDate || '',
    }
    console.log(goodsInfo, "goodsInfo======去预约页面")
    if (offlineId) {
      // 去预约页面
      wx.navigateTo({
        url: `/module/order/pages/appointment/appointment?goodsInfo=${JSON.stringify(goodsInfo)}`,
      });
    } else {
      wx.showToast({
        title: "线下服务ID不能为空",
        icon: "none",
      });
    }
    // const id = e.currentTarget.dataset.id;
    // if (id) {
    //   // 跳转到预约页面，传递项目id
    //   wx.navigateTo({
    //     url: `/module/care/pages/careDetail/careDetail?id=${id}`,
    //   });
    // }
  },
  onTabChange(e: any) {
    const progress = e.detail.value;
    this.setData({
      currentTab: progress,
    });
    // 不立即清空数据，避免空状态闪烁
    this.getOfflineTreatmentList(progress);
  },
  // 获取线下非药物治疗记录列表
  async getOfflineTreatmentList(progress: string) {
    // 启用加载态，保留当前列表，避免空态闪烁
    this.setData({ isLoading: true });
    try {
      const res = await getOfflineTreatmentListMethod(progress);
      console.log(res.data, "res.data")
      // 确保 res.data 是数组，避免 undefined 或 null 导致的错误
      const list = Array.isArray(res?.data) ? res.data : [];
      // 如果传入了treatmentId，标记匹配的项目为高亮并置顶
      const treatmentId = this.data.treatmentId;
      console.log(treatmentId, "treatmentId")
      console.log(list, "list")
      if (treatmentId && list.length > 0) {
        const highlightedList = list.map((item: any) => ({
          ...item,
          isHighlighted: item.id === treatmentId || String(item.id) === String(treatmentId),
        }));
        // 将高亮的项目移到最前面
        const highlightedItem = highlightedList.find((item: any) => item.isHighlighted);
        const otherItems = highlightedList.filter((item: any) => !item.isHighlighted);
        const sortedList = highlightedItem ? [highlightedItem, ...otherItems] : highlightedList;
        console.log(sortedList, "sortedList")

        this.setData({ treatmentList: sortedList, isLoading: false });
      } else {
        // 只有在数据加载完成后才更新列表
        this.setData({ treatmentList: list, isLoading: false });
      }
    } catch (error: any) {

      console.error('获取数据失败:', error);
      // 只有在真正出错时才显示错误提示
      wx.showToast({
        title: error.errMsg || "获取数据失败",
        icon: "none",
      });
      this.setData({ treatmentList: [], isLoading: false });
    }
  },
});
