import I18nBehavior from "../../../../i18n/behavior";
import { groupBy } from "../../../../utils/util";
import { AnalysisException, AnalysisModel } from "../../model/health.model";
// module/health/components/card-analysis/card-analysis-content.ts
Component({
  behaviors: [I18nBehavior],
  lifetimes: {
    attached() {
      if (this.properties.type === 'files') {
        this.setData({ isShowType: true });
      }
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    tongue: { type: Object, value: null },
    face: { type: Object, value: null },
    simple: { type: Object, value: { tongue: false, face: false } },
    exception: { type: Object, value: { tongue: false, face: false } },
    type: { type: String, value: '' },
  },
  observers: {
    'exception.tongue, tongue'(show: boolean, tongue: AnalysisModel) {
      if (show === void 0) { show = true; }
      if (!show || !tongue) return;
      const exception = this._getException(tongue.exception, 'list');
      this.setData({ tongueException: exception });
    },
    'exception.face, face'(show: boolean, face: AnalysisModel) {
      if (show === void 0) { show = true; }
      if (!show || !face) return;
      const exception = this._getException(face.exception, 'group');
      this.setData({ faceException: exception });
    }
  },
  data: {
    tongueException: [],
    faceException: [],
    isShowType: '',
    i18n: [
      'analysis._',
      'analysis.tongue',
      'analysis.face',
      'analysis.tongue_1',
      'analysis.tongue_2',
      'analysis.face_1',
      'analysis.__show__',
      'analysis.__showContent__',
    ],
  },
  methods: {
    async preview(event: WechatMiniprogram.TouchEvent) {
      const type: 'tongue' | 'face' = event.mark?.type;
      const [operation = '', dataType] = event.mark?.operation?.split('-') ?? [];
      const data = (this.data as any)[type]?.[operation];
      if (!data) return;

      const t2 = this.data.i18n?.analysis?.[type] ?? '';
      const t3 = this.data.i18n?.analysis?.['_'] ?? '';

      const { eventChannel } = await wx.navigateTo({ url: `/module/health/pages/tongue-analysis/tongue-analysis` });
      eventChannel.emit('load', {
        dataset: this._getException(data, dataType),
        title: `异常${t2}${t3}`,
      });
    },

    _getException(data: AnalysisException[], type: 'list' | 'group') {
      switch (type) {
        case 'list':
          return data.map(({ descriptions, ...item }) => ({
            ...item,
            exception: [{ key: item.key, descriptions }]
          }));
        case 'group':
          const group = groupBy<AnalysisException>(data, (item) => item.cover ?? '');
          return Object.entries(group).map(([key, exception]) => ({ key, cover: key, exception, }));
        default:
          return [];
      }
    }
  }
})