export interface AnalysisModel {
  table: {
    columns: string[];
    data: { exception?: boolean; invalid?: boolean;  }[];
  };
  exception: AnalysisException[];
  cover: string[];
  result: string;
}

export interface AnalysisException {
  key: string;
  title: string;
  cover?: string;
  description?: string;
  descriptions: { label: string; value: string }[];
  tags: string[];
}

export function healthAnalysisModel(data: AnyObject) {
  return {
    id: data?.id ?? '',
    reportTime: data?.reportTime,
    tongue: tongueAnalysisModel(data),
    face: faceAnalysisModel(data),
  }
}

export function healthReportModel(data: AnyObject) {
  const fn = (label: string, value?: string, force = false) => value || force ? { label, value: value ?? '' } : void 0;

  return {
    id: data?.healthAnalysisReportId ?? '',
    reportTime: data?.reportTime,
    reportId: data?.healthAnalysisReportId ?? '',

    analysisId: data?.tonguefaceAnalysisReportId ?? '',
    tongue: tongueAnalysisModel(data),
    face: faceAnalysisModel(data),

    report: [
      fn('结果显示您是', data?.willillStateName, true),
      fn('程度', data?.willillDegreeName, true),
      fn('类型', data?.willillSocialName, true),
      fn('表现', data?.willillFunctionName, true),
      fn('体质', data?.constitutionGroupName, true),
      fn('证素', data?.factorItemSummary, true),
      fn('证型', data?.diagnoseSyndromeSummary, true),
    ].filter(Boolean),

    result: data?.constitutionGroupDefinition ?? '',
    physique: [
      fn('总体特征', data?.constitutionGroupGeneralCharacteristics, true),
      fn('形体特征', data?.constitutionGroupPhysicalCharacteristics, true),
      fn('精神特征', data?.constitutionGroupPsychicCharacteristics, true),
      fn('常见表现', data?.constitutionGroupCommonManifestations, true),
      fn('发病倾向', data?.constitutionGroupDiseaseTendency, true),
      fn('环境适应能力', data?.constitutionGroupAdaptability, true),
    ].filter(Boolean),

    __origin__: data ?? {},
  }
}

/**
 * 健康档案显示数据
 * @param data
 */
export function healthRecord(data: ReturnType<typeof healthReportModel>) {
  const fn = (label: string, value?: string, force = false) => value || force ? { label, value: value ?? '' } : void 0;

  const conditProgram = data?.__origin__?.conditProgram;
  if (Array.isArray(conditProgram?.types)) {
    conditProgram.types = conditProgram.types.map((item: AnyObject) => ({ type: item.type }))
  }

  return {
    reportId: data?.reportId,
    analysisId: data?.analysisId,
    condition: [fn('症状信息', data?.__origin__?.pickedSymptom)].filter(Boolean),
    report: data?.report ?? [],
    analysis: [
      data?.tongue?.result ? { value: data.tongue.result, cover: data.tongue.cover } : void 0,
    ].filter(Boolean),
    conditProgram,
  }
}

function tongueAnalysisModel(data: AnyObject): AnalysisModel {
  const exception: AnalysisException[] = [];
  const tongueException = analysisException(exception);
  const c1 = data?.upImg;
  const c2 = data?.downImg;
  return {
    table: {
      columns: ['舌象维度', '检测结果', '标准值'],
      data: [
        tongueException(data?.tongueColor, '舌色'),
        tongueException(data?.tongueCoatingColor, '苔色'),
        tongueException(data?.tongueShape, '舌形'),
        tongueException(data?.tongueCoating, '苔质'),
        tongueException(data?.bodyFluid, '津液'),
        tongueException(data?.sublingualVein, '舌下'),
      ],
    },
    exception,
    result: data?.tongueAnalysisResult ?? '',
    cover: Object.assign([c1, c2].filter(Boolean), {
      ['舌上']: c1,
      ['舌下']: c2,
    }),
  }
}

function faceAnalysisModel(data: AnyObject): AnalysisModel {
  const exception: AnalysisException[] = [];
  const faceException = analysisException(exception, (label, value) => `${label}${value}`);
  const c1 = data?.faceImg ?? data?.faceImgUrl;
  const c2 = data?.faceLeft ?? data?.faceLeftImgUrl;
  const c3 = data?.faceRight ?? data?.faceRightImgUrl;
  return {
    table: {
      columns: ['面象维度', '检测结果', '标准值'],
      data: [
        faceException(data?.faceColor, '面色'),
        faceException(data?.mainColor, '主色'),
        faceException(data?.shine, '光泽'),
        // faceException(data?.leftBlackEye, '左黑眼圈'),
        // faceException(data?.rightBlackEye, '右黑眼圈'),
        faceException(data?.blackEye, '黑眼圈'),
        faceException(data?.lipColor, '唇色'),
        faceException(data?.eyeContact, '眼神'),
        // faceException(data?.leftEyeColor, '左目色'),
        // faceException(data?.rightEyeColor, '右目色'),
        faceException(data?.eyeColor, '目色'),
        faceException(data?.hecticCheek, '两颧红'),
        faceException(data?.noseFold, '鼻褶'),
        faceException(data?.cyanGlabella, '眉间/鼻柱青色'),
        faceException(data?.faceSkinDefects, '面部皮损'),
      ],
    },
    exception,
    result: data?.faceAnalysisResult ?? data?.face ?? '',
    cover: Object.assign([c1, c2, c3].filter(Boolean), {
      ['正面']: c1,
      ['左面']: c2,
      ['右面']: c3,
    }),
  };
}

function analysisException(exception: AnalysisException[], $title = (label: string, value: string) => value,) {
  return (data: { actualList?: AnyObject[]; standardValue?: string }, label: string) => {
    let is = false;
    let invalid = false;
    const values = data?.actualList?.map((item) => {
      let title: string = item?.actualValue ?? '';
      const suffix = item?.contrast ?? 's';
      if (title.endsWith('不符合检测要求')) {
        invalid = true;
      } else if (suffix !== 's') {
        if (suffix !== 'r') title += ` (${suffix || ''}) `;
        is = true;
        exception.push({
          key: title,
          title: $title(label, title),
          cover: item.splitImage,
          descriptions: [
            item.features ? { label: '【特征】', value: item.features } : null,
            item.clinicalSignificance ? { label: '【临床意义】', value: item.clinicalSignificance } : null,
          ].filter(Boolean) as any,
          tags: item.attrs ?? [],
        });
      }
      return title;
    }) ?? [];
    return Object.assign({
      0: label,
      1: values.join('<br>'),
      2: data?.standardValue ?? ''
    }, { exception: is, invalid });
  }
}