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

// module/health/pages/report/report.ts
import { toSchemePage } from '../../router';
import { healthIndexMethod, healthReportMethod } from "../../request";
import { healthIndex2Progress } from "../../tools/health-index";
Component({
  behaviors: [
    PageContainerBehavior,
    TickleBehavior
  ],
  lifetimes: {
    attached() {
      this.getHealthReport(this.data.id);
      this.getHealthIndex(this.data.id);
    }
  },
  properties: {
    id: { type: String, value: '' },
  },
  data: {
    dataset: null,
    schemeId: '',
    healthIndex: { data: [], loading: false, message: '' },
    tongueAnalysis: [] as AnyArray,
  },
  observers: {
    'dataset'(data) {
      const has = data?.isHaveConditioningProgram === 'Y' && data?.isConfirmConditioningProgram === 'Y';

      const keys = [
        'tongueColor', 'tongueCoatingColor',
        'tongueShape', 'tongueCoating',
        'bodyFluid', 'sublingualVein'
      ]
      const tongueAnalysis = [] as AnyObject[];
      for (const key of keys) {
        const actualList = data?.[key]?.['actualList'] ?? []
        tongueAnalysis.push(...actualList.filter((item: AnyObject) => item.contrast !== 's'))
      }

      this.setData({
        schemeId: has ? this.data.id : '',
        tongueAnalysis
      })
    }
  },
  methods: {
    async getHealthReport(id?: string) {
      wx.showLoading({ title: '加载中' });
      try {
        const dataset = await healthReportMethod(id);
        this.setData({ dataset });
      } catch (error) {
        getTickleContext.call(this).showErrorMessage(error.errMsg, 0);
      }
      wx.hideLoading();
    },
    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,
        });
      }
    },
    toSchemePage() { toSchemePage(this.data.schemeId); },
    toTongueAnalysisResult() {
      wx.navigateTo({ url: `/module/health/pages/tongue-analysis/tongue-analysis` })
        .then(res => {
          res.eventChannel.emit('load', { dataset: this.data.tongueAnalysis });
        });
    }
  }
})