import { cacheFor }                                             from '@/request/api/index';
import { useVisitor }                                           from '@/stores';
import HTTP                                                     from '../alova';
import { fromAnalysisModel, fromReportData, fromSchemeRequest } from '../model';


export function getAnalysisResultsMethod() {
  const Visitor = useVisitor();
  return HTTP.Post(
    `/fdhb-tablet/dialogueManage/dialog/${ Visitor.patientId }/${ Visitor.resultId }`,
    { questions: [], asyncTongueResult: false, patientId: Visitor.patientId },
    {
      meta: { ignoreException: true },
      async transform(data: Record<string, any>, headers) {
        const id = data?.tonguefaceAnalysisReportId;
        const date = data?.tonguefaceAnalysisReportDate;
        const miniProgramURL = data?.tonguefaceAnalysisReportAppletImg;
        data = data.nextQuestions?.find((item: any) => item.classify === 'tongue_result');
        let message = '';
        if ( data ) {
          const tongue = fromAnalysisModel('tongue', data);
          const face = fromAnalysisModel('face', data);
          if (!tongue.result && !face.result) {
            message = data.content;
          } else {
            const { miniProgram, payLock } = await getReportOptionsMethod('tongueface_upload_report_page');
            return {
              id, date,
              tongue, face,
              miniProgramURL: miniProgram ? miniProgramURL : void 0, payLock,
            };
          }
        }
        throw { message: message || `[分析结果] 照片不符合检测要求，图片不是舌头（请拍摄带有舌头的、清晰的彩色照！）` };
      },
    },
  );
}

export function getReportMethod(id: string) {
  const Visitor = useVisitor();
  const params = { healthAnalysisReportId: id, patientId: Visitor.patientId?.toString() };
  return HTTP.Get(`/fdhb-tablet/analysisManage/getHealRepDetailById`, {
    params,
    async transform(data, headers) {
      const patientId = (<any>data)?.patientId?.toString()
      if (params.patientId !== patientId ) Visitor.$reset()
      const report = fromReportData(<any> data);
      Visitor.updatePulseReport(report.pulse, patientId);
      const { miniProgram, payLock, ...page } = await getReportOptionsMethod('health_analysis_report_page');
      if ( !miniProgram ) { report.miniProgramURL = void 0; }
      report.payLock = payLock;
      report.page = { jumpable: true, printable: true, ...page };
      return report;
    },
  });
}

export function getAlcoholReportMethod() {
  const Visitor = useVisitor();
  const params = { healthAnalysisReportId: Visitor.reportId, patientId: Visitor.patientId };
  return HTTP.Get(`/fdhb-tablet/analysisManage/getHealRepDetailById`, {
    params,
    transform(data: Record<string, any>) {
      return {
        date: data?.alcoholAnalysisReportDate /*?? data?.reportTime*/,
        alcohol: fromAnalysisModel('alcohol', data),
      }
    }
  });
}

export function updateReportMethod(id: string, data: Record<string, any>) {
  const Visitor = useVisitor();
  const params = {
    healthAnalysisReportId: id,
    constitutionGroupImg: data?.constitutionGroupImg,
    factorItemRadarImg: data?.factorItemRadarImg,
    patientId: Visitor.patientId
  };
  return HTTP.Post(`/fdhb-tablet/analysisManage/upConFacImgById`, params, {
    meta: { ignoreException: true },
  });
}

export function getReportSchemeMethod(id: string, standalone?: boolean) {
  const Visitor = useVisitor();
  const params = { healthAnalysisReportId: id, patientId: Visitor.patientId, standalone };
  return HTTP.Get(`/fdhb-tablet/analysisManage/getCondProgDetailById`, {
    params,
    async transform(data: any, headers) {
      const scheme = fromSchemeRequest(data);
      if (standalone) {
        const { miniProgram, payLock } = await getReportOptionsMethod('health_analysis_scheme_page');
        if ( !miniProgram ) { scheme.miniProgramURL = void 0; }
        scheme.payLock = payLock;
      } else {
        scheme.miniProgramURL = void 0;
      }
      return scheme;
    },
  });
}

export function getReportOptionsMethod(prefix: 'health_analysis_report_page' | 'health_analysis_scheme_page' | 'tongueface_upload_report_page') {
  return HTTP.Post<{ miniProgram: boolean; payLock: boolean; jumpable?: boolean; printable?: boolean }, { tabletRequiredPageOperationElements: string[] }>(
    `/fdhb-tablet/warrantManage/getPageSets?${prefix}`,
    void 0,
    {
      cacheFor,
      transform(data) {
        const cfg = Array.isArray(data.tabletRequiredPageOperationElements) ? data.tabletRequiredPageOperationElements : [];
        const miniProgram = cfg.includes(`${prefix}_appletbutton`);
        const payLock = miniProgram && cfg.includes(`${prefix}_appletscan`);
        return prefix === 'health_analysis_report_page'
          ? {
            miniProgram,
            payLock,
            jumpable: !cfg.includes(`${prefix}_notjump`),
            printable: !cfg.includes(`${prefix}_notprint`),
          }
          : { miniProgram, payLock };
      },
    }
  );
}

