import {
  type AnalysisRecordModel,
  type List,
  type PatientRecordModel,
  type ReportIndicatorModel,
  type ReportModel,
  type ReportSchemeItemModel,
  transformAnalysisRecord,
  transformIndicators,
  transformPatientRecord,
  transformReportScheme,
  transformReportSchemeItem,
} from '@/model';

import request from '@/request/alova';
import dayjs from 'dayjs';

import { fromHealthIndicator, fromHealthReport, type HealthIndicatorItemVO, type HealthIndicatorVO, type HealthReportDTO, type HealthReportVO } from '@/model/health-report.model';
import { type DiagnosisReportDTO, type DiagnosisReportVO, fromDiagnosisReport } from '@/model/diagnosis-report.model';
import { type FollowUpEvaluationReportDTO, type FollowUpEvaluationReportVO, fromFollowUpEvaluationReport } from '@/model/follow-up-report.model';


export function reportsMethod(patientId: string) {
  return request.Get<ReportModel[], any[]>(`/fdhb-pc/analysisManage/getHarsTid`, {
    name: 'list-report',
    params: { patientId },
    transform(data, headers) {
      return data?.map(item => {
        return {
          ...item,
          id: item.healthAnalysisReportId.toString(),
          time: item.time2,
        };
      }) ?? [];
    },
  });
}

export function reportMethod(id: string) {
  return request.Get<ReportModel, any>(`/fdhb-pc/analysisManage/getHealRepDetailById`, {
    hitSource: 'confirm-scheme',
    name: 'get-report',
    params: { healthAnalysisReportId: id },
    transform(data, headers) {
      return {
        ...data,
        id: data.healthAnalysisReportId,
        time: data.reportTime,
        analysable: data.reportTime === dayjs().format('YYYY年MM月DD日'),
        scheme: {
          show: data.isHaveConditioningProgram === 'Y',
          editable: data.isConfirmConditioningProgram !== 'Y',
        },
      };
    },
  });
}

export function patientHealthReportMethod(id: string) {
  return request.Get<HealthReportVO, HealthReportDTO>(`/fdhb-pc/analysisManage/getHealRepDetailById`, {
    hitSource: 'confirm-scheme',
    name: 'get-report',
    params: { healthAnalysisReportId: id },
    transform: fromHealthReport,
  });
}

export function reportSchemeMethod(reportId: string) {
  return request.Get(`/fdhb-pc/analysisManage/getCondProgDetailById`, {
    hitSource: /-scheme$/,
    name: 'report-scheme',
    params: { healthAnalysisReportId: reportId },
    transform(data: any, headers) {
      data.healthAnalysisReportId ??= reportId;
      return transformReportScheme(data);
    },
  });
}

export function searchSchemeMethod(keyword?: string, query?: Partial<ReportSchemeItemModel>) {
  return request.Get(`/fdhb-pc/analysisManage/condProgramQuery`, {
    params: { type: query?.category, name: keyword ?? query?.name ?? '' },
    transform(data: any[], headers) {
      const groups = data.map((group: any, index: number) => {
        const { id, ...scheme } = transformReportSchemeItem(query?.category!, group);
        return {
          ...scheme,
          name: scheme.name ?? `预设 ${ index + 1 }`,
          label: scheme.name ?? `预设 ${ index + 1 }`,
        };
      });
      if ( keyword && !groups.find(group => group.label === keyword) ) groups.unshift(<any>{ name: keyword, label: keyword });
      return groups;
    },
  });
}

export function editSchemeMethod(reportId: string, scheme: ReportSchemeItemModel) {
  const method = scheme.id ? `Update` : `Add`;

  const filterData = (data?: any[]) => data?.filter(t => t.name)?.map(({ id, ...t }) => Object.assign(t, { id: /^custom-/.test(id!) ? '' : id }));

  return request.Post(`/fdhb-pc/analysisManage/condProgram${ method }`, {
    healthAnalysisReportId: reportId,
    type: scheme.category,
    id: scheme.id,
    name: scheme.name ?? '',
    items: filterData(scheme.content),
    attrs: filterData(scheme.descriptions),
  }, {
    name: 'edit-scheme',
    transform(data: string, headers) {
      scheme.id ??= data;
      return scheme;
    },
  });
}

export function deleteSchemeMethod(reportId: string, scheme: ReportSchemeItemModel) {
  return request.Get(`/fdhb-pc/analysisManage/condProgramDelete`, {
    name: 'delete-scheme',
    params: { id: scheme.id },
    transform(data: any, headers) {
      return scheme;
    },
  });
}

/**
 * 确认调理方案
 * @param reportId 报告 ID
 */
export function confirmSchemeMethod(reportId: string) {
  return request.Get(`/fdhb-pc/analysisManage/condProgramConfirm`, {
    name: 'confirm-scheme',
    params: { healthAnalysisReportId: reportId },
    cacheFor: null,
  });
}

/**
 * 报告指标
 * @param reportId 报告 ID
 * @param filter 默认过滤空值
 */
export function indicatorByReportIdMethod(reportId: string, filter = true) {
  return request.Get<ReportIndicatorModel[], any[]>(`/fdhb-pc/analysisManage/getLast7Day`, {
    hitSource: 'update-indicator',
    name: 'report-indicator',
    params: { healthAnalysisReportId: reportId },
    transform(data, headers) {
      const indicators = transformIndicators(data);
      return filter ? indicators.filter(model => !!model.value) : indicators;
    },
  });
}

/**
 * 患者指标
 * @param patientId 患者ID
 * @param filter 默认过滤空值
 */
export function indicatorByPatientIdMethod(patientId: string, filter = true) {
  return request.Get<ReportIndicatorModel[], any[]>(`/fdhb-pc/patientQuota/getCurQuovalByPatId`, {
    hitSource: 'update-indicator',
    name: 'patient-indicator',
    params: { patientId },
    transform(data, headers) {
      const indicators = transformIndicators(data);
      return filter ? indicators.filter(model => !!model.value) : indicators;
    },
  });
}

/**
 * 患者指标更新记录
 * @param patientId 患者ID
 * @param filter 默认过滤空值
 */
export function indicatorUpdateRecordsMethod(patientId: string, filter = true) {
  return request.Get<ReportIndicatorModel[], any[]>(`/fdhb-pc/patientQuota/getQuovalRecord`, {
    hitSource: 'update-indicator',
    params: { patientId },
    transform(data, headers) {
      console.log(data, 'data----indicatorUpdateRecordsMethod');
      const indicators = transformIndicators(data);
      return filter ? indicators.filter(model => !!model.records?.length) : indicators;
    },
  });
}

/**
 * 更新患者指标
 * @param patientId 患者ID
 * @param model 指标数据
 */
export function updateIndicatorByPatientIdMethod(patientId: string, model: Record<string, number>) {
  const data = Object.entries(model).map(([ quotaId, quotaVal ]) => (
    {
      quotaId,
      quotaVal,
    }
  )).filter(item => !!item.quotaVal);
  return request.Post(`/fdhb-pc/patientQuota/updateQuovalByPatId`, { patientId, updatePatientQuotaVOS: data }, {
    name: 'update-indicator',
  });
}

// 患者数据更新记录
export function patientUpdateRecordsMethod(page: number, size: number, query: { patientId: string }) {
  return request.Get<List<PatientRecordModel>, List<any>>(`/fdhb-pc/patientInfoManage/pageChangeRecordById`, {
    params: { pageNum: page, pageSize: size, ...query },
    transform({ data, total }, headers) {
      return { total, data: data.map(transformPatientRecord) };
    },
  });
}

// 患者分析更新记录
export function analysisUpdateRecordsMethod(page: number, size: number, query: { patientId: string }) {
  return request.Post<List<AnalysisRecordModel>, List<any>>(`/fdhb-pc/analysisManage/pageHarStatu`, {}, {
    params: { pageNum: page, pageSize: size, ...query },
    transform({ data, total }, headers) {
      return { total, data: data.map(transformAnalysisRecord) };
    },
  });
}

/**
 * 获取患者健康分析记录列表
 * @param page
 * @param size
 * @param query
 */
export function getPatientHealthRecordsMethod(page: number, size: number, query: { patientId: string }) {
  return request.Post<{ total: number; data: HealthReportVO[] }, { total: number; data: HealthReportDTO[] }>(`/fdhb-pc/analysisManage/pageHarStatu`, query, {
    params: { pageNum: page, pageSize: size, ...query },
    transform({ data, total }) {
      return { total, data: data.map(fromHealthReport) };
    },
  });
}

export function getPatientHealthRecordMethod(id: string) {
  return request.Get<HealthReportVO, HealthReportDTO>(`/fdhb-pc/analysisManage/getHealRepDetailById`, {
    params: { healthAnalysisReportId: id },
    transform(data) {
      return fromHealthReport(data);
    },
  });
}
// 获取舌面分析报告 getTofRepDetailById
export function getTonguefaceAnalysisReportMethod(id: string) {
  return request.Get<HealthReportVO, HealthReportDTO>(`/fdhb-pc/analysisManage/getTofRepDetailById`, {
    params: { tonguefaceAnalysisReportId: id },
    transform(data) {
      return fromHealthReport(data);
    },
  });
}

export function getPatientHealthIndicatorsMethod(patientId: string) {
  return request.Get<HealthIndicatorVO[], any[]>(`/fdhb-pc/patientQuota/getQuovalRecord`, {
    hitSource: 'update-indicator',
    name: 'patient-indicator',
    params: { patientId },
    transform(data) {
      return data.map(fromHealthIndicator).filter(indicator => indicator.items.length);
    },
  });
}

/**
 * 患者生理指标（每次提交）记录
 * @param patientId
 */
export function getPatientHealthIndicatorRecordsMethod(patientId: string) {
  return request.Get<HealthIndicatorVO[], any[]>(`/fdhb-pc/patientQuota/getQuoUpdateStream`, {
    hitSource: 'update-indicator',
    name: 'patient-indicator',
    params: { patientId },
    transform(data) {
      return data.map(fromHealthIndicator).filter(indicator => indicator.items.length);
    },
  });
}

export function getPatientHealthIndicatorMethod(patientId: string) {
  return request.Get<HealthIndicatorItemVO[], any[]>(`/fdhb-pc/patientQuota/getCurQuovalByPatId`, {
    hitSource: 'update-indicator',
    name: 'patient-indicator',
    params: { patientId },
    transform(data) {
      return data.map((indicator) => {
        const { items, ...collection } = fromHealthIndicator(indicator);
        return { ...collection, ...items[0] };
      }).filter(item => !!item.value);
    },
  });
}

/**
 * 获取患者就诊记录列表
 * @param page
 * @param size
 * @param query
 */
export function getPatientDiagnosisRecordsMethod(page: number, size: number, query: { patientId: string }) {
  return request.Post<{ total: number; data: DiagnosisReportVO[] }, { total: number; data: DiagnosisReportDTO[] }>(`/fdhb-pc/patientMedicalManage/pagePatientMedical`, query, {
    params: { pageNum: page, pageSize: size, ...query },
    transform({ data, total }) {
      return { total, data: data.map(fromDiagnosisReport) };
    },
  });
}

export function getPatientDiagnosisReportMethod(id: string | number, patientId?: string) {
  if (typeof id === 'string') return request.Post<DiagnosisReportVO, any>('/');

  const size = 100;
  const page = ~~(id / size) + 1;
  const index = id % size;

  return request.Post<DiagnosisReportVO, { total: number; data: DiagnosisReportDTO[] }>(
    `/fdhb-pc/patientMedicalManage/pagePatientMedical?last`,
    { patientId },
    {
      params: { pageNum: page, pageSize: size, patientId },
      transform({ data }) {
        return fromDiagnosisReport(data[index]);
      },
    },
  );
}

/**
 * 获取患者随访评估记录列表
 * @param page
 * @param size
 * @param query
 */
export function getPatientFollowUpEvaluationRecordsMethod(page: number, size: number, query: { patientId: string }) {
  return request.Post<{ total: number; data: FollowUpEvaluationReportVO[] }, { total: number; data: FollowUpEvaluationReportDTO[] }>(`/fdhb-pc/followupTaskManage/pageFollowupTaskGroup`, query, {
    params: { pageNum: page, pageSize: size, ...query },
    transform({ data, total }) {
      return { total, data: data.map(fromFollowUpEvaluationReport) };
    },
  });
}