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

// module/health/components/report-health-status/report-health-status.ts
import {
  healthAnalysisListMethod,
  healthAnalysisMethod,
  healthReportListMethod,
  healthReportMethod,
} from "../../request";
import { healthAnalysisModel, healthRecord } from "../../model/health.model";
import { AnalysisModel } from "../../model/health.model";
interface PanelProps {
  shade?: boolean;
  title?: string;
  data: AnyArray;
  type?: "analysis" | "report";
}

Component({
  behaviors: [
    I18nBehavior,
    PageContainerBehavior,
    DraggableSheetBehavior(".health-report-list"),
  ],
  lifetimes: {
    attached() {
      this._load();
    },
  },
  pageLifetimes: {
    hide() {
      this._hideDraggableSheet({});
    },
  },
  data: {
    i18n: {
      home: { __showRecord__: false },
      health: {
        status: '结果概况',
        statusTable: ['', '', '', '', '', '', ''],
        statusNext: '概况'
      },
      report: { title: '测评结果' },
    },
    dataset: {},
    tongue: null as unknown as AnalysisModel,
    face: null as unknown as AnalysisModel,
    analysisData: null as unknown as AnalysisModel,
    loading: false,
    message: "",
    panel: {
      shade: false,
      data: [],
    } as PanelProps,
    _healthReportList: { data: [], loaded: false },
    _healthAnalysisList: { data: [], loaded: false },
  },
  methods: {
    async showReportList() {
      if (!this.data._healthReportList.loaded) {
        wx.showLoading({ title: "加载中" });
        try {
          const data = await healthReportListMethod();
          this.setData({
            "_healthReportList.data": data,
            "_healthReportList.loaded": true,
          });
        } catch (error) {
          getTickleContext.call(this).showErrorMessage(error.errMsg);
        }
        wx.hideLoading();
      }
      this._showDraggableSheet({
        title: "健康分析报告记录",
        type: "report",
        data: this.data._healthReportList.data,
      });
    },
    async showAnalysisList() {
      if (!this.data._healthAnalysisList.loaded) {
        wx.showLoading({ title: "加载中" });
        try {
          const data = await healthAnalysisListMethod();
          this.setData({
            "_healthAnalysisList.data": data,
            "_healthAnalysisList.loaded": true,
          });
        } catch (error) {
          getTickleContext.call(this).showErrorMessage(error.errMsg);
        }
        wx.hideLoading();
      }
      this._showDraggableSheet({
        title: "舌面分析报告记录",
        type: "analysis",
        data: this.data._healthAnalysisList.data,
      });
    },
    showStatusList() {
      wx.navigateTo({
        url: `/module/health/pages/status-record/status-record`,
      });
    },
    toPreviewPage(event: WechatMiniprogram.TouchEvent) {
      const { id, type } = event.mark ?? {};
      if (!id) return;
      const route = `module/health/pages/${type}/${type}`;
      wx.navigateTo({ url: `/${route}?id=${id}` });
    },

    async _load() {
      this.setData({ loading: true });
    
      const params = { id: void 0, scene: void 0 };
      try {
        const report = await healthReportMethod(params);
        const { id: analysisId, ...analysis } = await healthAnalysisMethod(
          params
        ).catch(() => healthAnalysisModel({}));
        const data = healthRecord({ ...report, ...analysis, analysisId });
        this.setData({
          dataset: data,
          loading: false,
        });
        data.condition = data.condition.map((item:any)=>{
          item.value = item.value.split('，')
          return item
        })
        const { tongue, face, ...analysisData } = await healthAnalysisMethod(params);
        this.setData({ tongue, face, analysisData });
      } catch (error) {
        this.setData({
          dataset: null,
          loading: false,
          message: error.errMsg,
        });
      }
    },

    _showDraggableSheet(props: PanelProps) {
      if (props.data?.length) {
        getDraggableSheetContext.call(this).scrollTo({
          size: 0.5,
          pixels: 600,
          animated: true,
          duration: 300,
          easingFunction: "ease",
        });
        this.setData({ panel: { ...props, shade: true } });
      } else {
        wx.showToast({ title: "暂无更新记录" });
      }
    },
    _hideDraggableSheet(e?: any) {
      this.setData({ "panel.shade": false });
      if (!e) return;
      getDraggableSheetContext.call(this).scrollTo({
        size: 0,
        animated: true,
        duration: 300,
        easingFunction: "ease",
      });
    },
    _draggableSizeUpdate(e: any) {
      "worklet";
      if (e.pixels < 1) {
        wx.worklet.runOnJS(this._hideDraggableSheet.bind(this))();
      }
    },
  },
});
