import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import I18nBehavior from "../../../../i18n/behavior";
import TickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";

// module/health/pages/report/report.ts
import { toSchemePage, toHomePage } from "../../router";
import { healthIndexMethod, healthReportMethod } from "../../request";
import { healthIndex2Progress } from "../../tools/health-index";

Page({
  behaviors: [I18nBehavior, PageContainerBehavior, TickleBehavior],
  data: {
    i18n: {
      common: { doctor: '', zy: '' },
      health: { statusTable: ['', '', '', '', '', '', ''] },
      scheme: { title: '方案' },
      report: {
        title: '报告',
        date: '',
        physique: '',
        physiqueTable: ['特征1', '特征2', '特征3', '特征4', '特征5', '特征6'],
      }
    },
    id: "",
    dataset: null as unknown as AnyObject,
    showScheme: false,
    schemeId: "",
    healthIndex: { data: [], loading: false, message: "" },
    tongueAnalysis: [] as AnyArray,
    switchType: "",
  },
  onLoad(query: any) {
    if (query.scene) {
      this.setData({ switchType: query.scene });
      wx.showLoading({ title: "加载中" });
    } else this._load(query);
  },
  load(event: AnyObject) { this._load(event.detail, false); },
  async _load(query: Record<"id" | "scene", string>, loading = true) {
    let id = "";
    if (loading) wx.showLoading({ title: "加载中" });
    try {
      const { __origin__, ...dataset } = await healthReportMethod(query);
      id = dataset.id;
      const showScheme = __origin__?.isHaveConditioningProgram === "Y";
      const schemeId =
        __origin__?.isConfirmConditioningProgram === "Y" ? id : "";
      this.setData({
        showScheme,
        schemeId,
        dataset: {
          ...dataset,
          factorItems: __origin__?.factorItems,
          diagnoseSyndromes: __origin__?.diagnoseSyndromes,
        },
      });
    } catch (error) {
      getTickleContext.call(this).showErrorMessage(error.errMsg, 0);
    }
    wx.hideLoading();

    if (id) this.getHealthIndex(id);
  },

  async getHealthIndex(id?: string) {
    this.setData({ "healthIndex.loading": true });
    try {
      const data = await healthIndexMethod(id);
      this.setData({
        "healthIndex.data": healthIndex2Progress(data),
        "healthIndex.loading": false,
      });
    } catch (error) {
      this.setData({
        "healthIndex.data": [],
        "healthIndex.loading": false,
        "healthIndex.message": error.errMsg,
      });
    }
  },
  toHomePage() {
    toHomePage(this.data.switchType as string);
  },
  toSchemePage() {
    toSchemePage(this.data.schemeId);
  },
  openMessage(event: any) {
    const message = event?.detail?.content;
    if (message) getTickleContext.call(this).showMessage(event.detail.type || 'info', message);
  }
});
