import {
  analysisPictureStrategy,
  type HealthReportAnalysisCategory,
  HealthReportAnalysisItemConfig,
  type HealthReportAnalysisKey,
  type HealthReportAnalysisSubcategory,
  HealthReportSymptomItemConfig,
} from '@/model/health-report-analysis.config';

export interface HealthReportAnalysisItemDTO {
  standardValue: string;
  actualList: {
    splitImage: string;
    actualValue: string;
    contrast: string;
    attrs: string[];
    features: string;
    clinicalSignificance?: string;
    mechanismAnalyze?: string;
  }[];
}

export interface HealthReportDTO extends Record<HealthReportAnalysisKey, HealthReportAnalysisItemDTO>, Record<`${HealthReportAnalysisCategory}AnalysisResult`, string> {
  tonguefaceAnalysisReportId: string;

  healthAnalysisReportId: string;
  reportTime: string;
  time4: string;

  pickedSymptomList?: { id: string; name: string; value: string; score: number }[];
  pickedSymptom?: string;
  duration?: string;
  influenceDegree?: string;

  willillStateName: string;
  willillDegreeName: string;
  willillFunctionName: string;
  willillSocialName: string;

  constitutionGroupName: string;
  constitutionGroupDefinition: string;

  factorItemSummary: string;
  diagnoseSyndromeSummary: string;
}

export interface HealthReportAnalysisItemVO {
  category: HealthReportAnalysisCategory;
  subcategory: HealthReportAnalysisSubcategory;
  standardValue: string;
  resultValue: string;
  values: {
    cover?: string;
    contrast: string;
    actualValue: string;
    resultValue: string;
    tags: string[];
    /**
     * 特征
     */
    feature: string;
    /**
     * 意义
     * @description
     *  - tongue  临床意义
     *  - face    病理意义
     */
    significance: string;
    /**
     * 机理分析
     */
    analysis?: string;
  }[];
}

export interface HealthReportAnalysisVO
  extends Record<
    HealthReportAnalysisCategory,
    {
      result: string;
      analysis: HealthReportAnalysisItemVO[];
      pictures: string[];
    }
  > {
  id?: string;
}

export interface HealthReportSymptomItemVo {
  /**
   * 症状ID
   */
  id: string;
  /**
   * 症状名称
   */
  name: string;
  /**
   * 症状描述
   */
  label: string;
  /**
   * 症状得分
   */
  value: number;
}

export interface HealthReportSymptomVo {
  items: HealthReportSymptomItemVo[];
  value?: string;
  duration?: string;
  influence?: string;
}

export interface HealthReportVO {
  id: string;
  date: string;
  analysis: HealthReportAnalysisVO;
  symptom: HealthReportSymptomVo;

  result: {
    status?: string;
    level?: string;
    description?: string;
    category: string;
  };

  physique: {
    label: string;
    description: string;
  };

  syndrome: {
    label: string;
  };
  syndromeElement: {
    label: string;
  };
}

export function fromHealthReport(data: HealthReportDTO): HealthReportVO {
  return {
    id: data.healthAnalysisReportId,
    date: data.reportTime ?? data.time4,
    analysis: fromHealthReportAnalysis(data),
    symptom: fromHealthReportSymptom(data),

    result: {
      status: data.willillStateName,
      level: data.willillDegreeName,
      description: data.willillFunctionName,
      category: data.willillSocialName,
    },

    physique: {
      label: data.constitutionGroupName,
      description: data.constitutionGroupDefinition,
    },
    syndromeElement: {
      label: data.factorItemSummary,
    },
    syndrome: {
      label: data.diagnoseSyndromeSummary,
    },
  };
}

export function fromHealthReportAnalysis(data: Partial<HealthReportDTO>, config = HealthReportAnalysisItemConfig): HealthReportAnalysisVO {
  const result = { id: data.tonguefaceAnalysisReportId } as HealthReportAnalysisVO;
  for (const { key, category, subcategory } of config) {
    const { analysis } =
      result[category] ??
      (result[category] = {
        analysis: [],
        result: data[`${category}AnalysisResult`] ?? '',
        pictures: analysisPictureStrategy[category]?.(data) ?? [],
      });
    if (!data[key]) continue;
    const { standardValue, actualList } = data[key]!;
    const values: HealthReportAnalysisItemVO['values'] = [];
    for (const { actualValue, splitImage: cover, ...item } of actualList) {
      const contrast = item.contrast === 's'  ? '' : (item.contrast  ?? '');
      const [_, features = _, significance = item.clinicalSignificance] = item.features?.match?.(
        new RegExp(`【(?:${actualValue}|正常${subcategory}|正常面色)】([^<]*)<?[\\s\\S]*?【病理意义】([^<]*)`)
      ) ?? item.features?.match?.(
        new RegExp(`([^<]*)<?[\\s\\S]*?【病理意义】([^<]*)`)
      ) ??  [item.features];
      values.push({
        cover: contrast ? cover : void 0,
        actualValue,
        // resultValue: contrast && contrast !=='r' ? `${actualValue} (${contrast})` : actualValue,
        resultValue: contrast ? `${actualValue} (${contrast})` : actualValue,
        contrast,
        feature: features ?? '',
        significance: significance ?? '',
        tags: item.attrs ?? [],
        analysis: item.mechanismAnalyze ?? '',
      });
    }
    analysis.push({
      category,
      subcategory,
      standardValue,
      resultValue: values.map((item) => item.resultValue).join('、'),
      values,
    });
  }
  return result;
}

export function fromHealthReportSymptom(data: Partial<HealthReportDTO>, config = HealthReportSymptomItemConfig): HealthReportSymptomVo {
  const result: HealthReportSymptomVo = {
    value: data.pickedSymptom,
    items:
      data.pickedSymptomList?.map(({ id, name, ...item }) => ({
        id,
        name,
        label: item.value,
        value: +item.score,
      })) ?? [],
    duration: data.duration,
    influence: data.influenceDegree,
  };
  if (!result.items?.length && result.value) {
    const matches = result.value?.matchAll(/([^，（]+)（([^）]+)）/g) ?? [];
    for (const [_, name, label] of matches) {
      // @ts-ignore
      const value = config[label] ?? 0;
      result.items.push({ id: name, name, label, value });
    }
  }
  return result;
}

export interface HealthIndicatorVO {
  items: HealthIndicatorItemVO[];
  id: string;
  name: string;
}

export interface HealthIndicatorItemVO {
  id: string;
  name: string;
  value: number;
  unit: string;
  trend: 0 | -1 | 1;

  date: string;
}

export function fromHealthIndicator(data: Record<string, any>): HealthIndicatorVO {
  return {
    id: data.quotaId,
    name: data.name,
    items: data.patientQuotaRecordDTOS?.map?.((item: any) => fromHealthIndicatorItem(Object.assign(item, data))) ?? [],
  };
}

export function fromHealthIndicatorItem(data: Record<string, any>): HealthIndicatorItemVO {
  const getTrend = (value: string) => {
    if (value?.includes('高')) return 1 as const;
    if (value?.includes('低')) return -1 as const;
    return 0 as const;
  };
  return {
    id: data.quotaId,
    name: data.name,
    unit: data.unit,
    value: data.quotaVal,
    trend: data.abnormal ? getTrend(data.abnormalDesc) : 0,
    date: data.time4 || data.time2,
  };
}
