// module/chats/components/guide/guide.ts
import { getPatients } from "../../../../pages/home/request";
import { toCertificationPage } from "../../../../pages/home/router";
import { Post } from "../../../../lib/request/method";
import I18nBehavior from "../../../../i18n/behavior";

let next: "handleA" | "handleB" | "handleC";

Component({
  behaviors: [I18nBehavior],
  lifetimes: {
    attached(this: any) {
      const showGuideActive = wx.getStorageSync("showGuideActive");
      //  从主页点击健康评估进来的
      if (showGuideActive) {
        this.handleA();
        wx.removeStorageSync("showGuideActive");
      }
      // 首次挂载时也拉取一次，避免初次渲染为 0
      this.setAnalysisCount();
    },
  },
  pageLifetimes: {
    show(this: any) {
      // 获取评估剩余次数
      this.setAnalysisCount().then(() => {
        if (next) {
          const patientId = wx.getStorageSync("patientId");
          if (patientId) this[next]();
          else wx.showToast({ title: "请先完善信息！", icon: "none" });
          next = undefined;
        }
      });
    },
  },
  properties: {
    id: { type: String, value: "" },
    active: { type: Boolean, value: false },
  },
  data: {
    i18n: {
      chats: { 
        analysis: '测评',
        healthData: '个人信息管理',
        healthIndex: '数据信息管理',
        consult: '',
      },
    },
    analysisCount: 0,
    result: [] as string[],
    result2: false,
    patient: {} as any,
  },
  methods: {
    // 获取评估剩余次数
    async setAnalysisCount(this: any) {
      try {
        // 获取剩余次数
        const residuedCount = await Post(
          `/patientInfoManage/rechargeUseDetail`,
          {},
          {
            transform({ data }: any) {
              if (data?.usedCou === 0 && data.residuedCou === 0)
                data.residuedCou = 3;
              return data?.residuedCou;
            },
          }
        );
        this.setData({ analysisCount: residuedCount });
      } catch (error) {
        console.error("获取剩余次数失败:", error);
      }
    },
    async handleA() {
      const { patient } = await getPatients(/*this.data.patientId*/);
      if (!patient) {
        await toCertificationPage();
        next = "handleA";
      } else {
        if (this.data.active) {
          // 设置 isAnalysis 为 3（健康分析/对话管家）
          wx.setStorageSync("isAnalysis", 3);
          // 先触发 nextType 更新 messageType，然后触发 next 切换组件
          this.triggerEvent("nextType", { MessageType: 2 });
          setTimeout(() => {
            this.triggerEvent("next", {
              component: "questionnaire",
              scroll: true,
            });
          }, 100);
        }
      }
    },
    async handleB() {
      const { patient } = await getPatients(/*this.data.patientId*/);
      if (!patient) {
        await toCertificationPage();
        next = "handleB";
      } else {
        if (this.data.active)
          wx.navigateTo({
            url: "/module/health/pages/status/status",
            events: { update: this._update.bind(this) },
          });
      }
    },
    async handleC() {
      const { patient } = await getPatients(/*this.data.patientId*/);
      if (!patient) {
        await toCertificationPage();
        next = "handleC";
      } else {
        if (this.data.active)
          wx.navigateTo({
            url: "/module/user/pages/user-edit/user-edit",
            events: {
              update2: () => {
                this.setData({ result2: true });
                this.triggerEvent("next", { component: "guide", scroll: true });
              },
            },
          });
      }
    },
    handleD() {
      // if (this.data.active) wx.navigateBack();
      if (this.data.active) {
        wx.redirectTo({ url: "/pages/home/home" });
      }
    },
    // 在线咨询
    async handleE() {
      const { patient } = await getPatients(/*this.data.patientId*/);
      if (!patient) await toCertificationPage();
      else {
        if (this.data.active) {
          // 清除之前的咨询结束状态，开始新咨询
          wx.setStorageSync("consultEnded", false);
          wx.setStorageSync("lastConsultTime", Date.now());

          wx.setStorageSync("isAnalysis", 5);
          // 先触发 nextType 更新 messageType，然后立即触发 next 切换组件
          // 由于 nextType 事件处理是同步的，所以可以立即触发 next
          this.triggerEvent("nextType", { MessageType: 3 });
          setTimeout(() => {
            this.triggerEvent("next", {
              component: "questionnaire",
              scroll: true,
            });
          }, 100);
        }
      }
    },
    _update(result: string[]) {
      if (result.length) {
        this.setData({ result });
        this.triggerEvent("next", { component: "guide", scroll: true });
      } else {
        setTimeout(
          () => wx.showToast({ title: `没有更改项`, icon: "none" }),
          300
        );
      }
    },
  },
});
