import I18nBehavior from "../../i18n/behavior";
import { getPatients, getPatientPhone } from "../home/request";
import { toCertificationPage } from "../home/router";
import { getOrderList, getRecordCountMethod } from "../home/request";

const i18n = {
  consultChat: { title: "记录" },
  offlineTreatment: { title: "线下" },
  healthTeach: { title: "分享文章" },
  health: { title: "档案" },
  home: {
    __showRecord__: false,
    tea: "茶",
    tonic: "菜谱",
  },
  orderText: {
    mineOrder: "我的服务",
    payStatusList:['待确认','已确认','已完成','全部'],
  },
};

Page({
  behaviors: [I18nBehavior],
  data: {
    i18n,
    patients: [] as (App.Patient.Model & { isDefault: "Y" | "N" })[],
    patient: null as App.Patient.Model | null,
    patientDescription: "",
    userInfo: null,
    tabbarValue: "/pages/mine/mine",
    phone: "",
    loaded: false,
    mineOrderList: [
      {
        url: "../../assets/icon/obligation@3x.png",
        // name: i18n.orderText.paying,
        count: 0,
        type: 1,
        tab: "pending",
      },
      {
        url: "../../assets/icon/delivery@3x.png",
        // name: i18n.orderText.paid,
        count: 0,
        type: 2,
        tab: "paid",
      },
      {
        url: "../../assets/icon/deal@3x.png",
        // name: i18n.orderText.paySuccess,
        count: 0,
        type: 3,
        tab: "completed",
      },
      // {
      //   url: "../../assets/icon/delivery@3x.png",
      //   name: "交易关闭",
      //   count: 0,
      //   type: 4,
      //   tab: "closed",
      // },
      {
        url: "../../assets/icon/all@3x.png",
        name: "全部",
        count: 0,
        type: 5,
        tab: "all",
      },
    ],
  },
  // 读取缓存，若存在则直接渲染并返回已读到的数据
  hydrateFromCache() {
    const cachedPatient = (wx.getStorageSync("patient") ||
      null) as App.Patient.Model | null;
    const cachedPhone = (wx.getStorageSync("patientPhone") || "") as string;
    if (cachedPatient || cachedPhone) {
      this.setData({
        patient: cachedPatient || null,
        phone: cachedPhone || "",
        loaded: true,
      });
    }
    return { cachedPatient, cachedPhone } as {
      cachedPatient: App.Patient.Model | null;
      cachedPhone: string;
    };
  },
  // 写入缓存
  syncCache(patient: App.Patient.Model | null, phone: string) {
    try {
      wx.setStorageSync("patient", patient || null);
      wx.setStorageSync("patientPhone", phone || "");
      wx.setStorageSync("patientName", patient?.name);
    } catch {}
  },
  // 轻量对比（避免 JSON 深比较）：患者用 patientId 或 name，对比手机号字符串
  isDifferent(
    cachedPatient: App.Patient.Model | null,
    newPatient: App.Patient.Model | null,
    cachedPhone: string,
    newPhone: string
  ) {
    const cachedId = cachedPatient?.patientId || "";
    const newId = newPatient?.patientId || "";
    const cachedName = cachedPatient?.name || "";
    const newName = newPatient?.name || "";
    return (
      cachedId !== newId ||
      cachedName !== newName ||
      (cachedPhone || "") !== (newPhone || "")
    );
  },
  // 获取各状态调理记录数量
  async getRecordCount() {
    try {
      const res = await getRecordCountMethod();
      if (res && res.data) {
        this.setData({
          "mineOrderList[0].count": res.data.pendingPayment,
          // "mineOrderList[1].count": res.data.pendingReceiptGoods,//已付款
          // "mineOrderList[2].count": res.data.successTrade,//交易成功
          // "mineOrderList[3].count": res.data.closeTrade,//交易关闭
          // "mineOrderList[3].count": res.data.total,//全部
        });
      }
    } catch (error: any) {
      wx.showToast({
        title: error.message,
        icon: "none",
        duration: 2000,
      });
    }
  },
  async load(retry = false) {
    if (retry) {
      await wx
        .showModal({
          title: "提示",
          content: "数据加载失败，是否重试？",
          showCancel: true,
        })
        .then((res) => {
          if (res.confirm) {
            this.load();
          }
        });
      return;
    }
    this.getRecordCount();
    try {
      // 1) 先读缓存渲染，避免初始闪烁
      const { cachedPatient, cachedPhone } = this.hydrateFromCache();

      // 2) 并行请求接口，完成后轻量对比，有变更再更新与回写缓存
      wx.showLoading({ title: "加载中" });
      const [{ patient }, phoneRes] = await Promise.all([
        getPatients(),
        getPatientPhone(),
      ]);
      const latestPhone = phoneRes?.phone || "";
      if (
        this.isDifferent(
          cachedPatient,
          patient || null,
          cachedPhone || "",
          latestPhone
        ) ||
        !this.data.loaded
      ) {
        this.setData({
          patient: patient || null,
          phone: latestPhone,
          loaded: true,
        });
        this.syncCache(patient || null, latestPhone);
      }
    } catch (error) {
      wx.showToast({
        title: "加载失败",
        icon: "none",
        duration: 2000,
      });
    } finally {
      wx.hideLoading();
      if (!this.data.loaded) {
        this.setData({ loaded: true });
      }
    }
  },

  // 健康档案
  toHealthPage() {
    if (!this.data.patient?.patientId) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      toCertificationPage();
    } else {
      wx.navigateTo({ url: `/module/health/pages/home/home` });
    }
  },

  // 药膳
  toDietTonicPage() {
    wx.navigateTo({
      url: `/module/article/pages/diet-list/diet-list?classify=tonic`,
    });
  },

  // 茶饮
  toDietTeaPage() {
    wx.navigateTo({
      url: `/module/article/pages/diet-list/diet-list?classify=tea`,
    });
  },

  // 订单列表
  toOrderListPage(e: any) {
    const tab = e.currentTarget.dataset.tab;
    wx.navigateTo({
      url: `/module/article/pages/order-list/order-list?tab=${tab}`,
    });
  },
  // 获取全部订单列表
  async getOrderList() {
    const patientId = wx.getStorageSync("patientId");
    await getOrderList(patientId, "");
  },
  onShow() {
    // 如果需要每次显示页面时刷新数据，可以在这里调用 load
    this.load();
    // 从支付成功页点「返回订单列表」时，自动打开订单列表，返回时回到本页
    const fromSuccess = wx.getStorageSync("fromSuccessToOrderList");
    if (fromSuccess) {
      wx.removeStorageSync("fromSuccessToOrderList");
      wx.navigateTo({
        url: "/module/article/pages/order-list/order-list?tab=all",
      });
    }
  },
  // 足迹
  toFootPrintPage() {
    wx.navigateTo({
      url: "/module/article/pages/foot-print/foot-print",
    });
  },
  // 宣教通知
  toHealthEducationPage() {
    
    wx.navigateTo({
      url: '/module/article/pages/education-list/education-list'
    });
  },
  onAddressTap() {
    // 跳转到收货地址页面
    wx.navigateTo({
      url: "/module/article/pages/manage-address/manage-address",
    });
  },
  onConsultationTap() {
    // 跳转到咨询记录页面
    // wx.showToast({
    //   title: "敬请期待",
    //   icon: "none",
    // });
    wx.navigateTo({
      url: '/module/chats/pages/consultation-record/consultation-record'
    });
  },
  onTreatmentTap() {
    // 跳转到线下非药物治疗页面
    wx.navigateTo({
      url: "/module/care/pages/offlineTreatment/offlineTreatment",
    });
  },
});
