import { useFlowStore, useVisitor }                   from '@/stores';
import HTTP                                           from '../alova';
import type { QuestionnaireStorage }                  from '../model';
import { fromQuestionnaireData, toQuestionnaireData } from '../model';


let storage: Pick<QuestionnaireStorage, 'dialogId'> & { questions: QuestionnaireStorage['questions'][] } = { questions: [] };

function getAnalysisExtendFlowValue() {
  const Flow = useFlowStore();
  return [
    Flow.router.hasNext('/alcohol/result') ? 'alcohol' : void 0,
  ].filter(Boolean).join(',');
}

export function questionnaireMethod(data = []) {
  const Visitor = useVisitor();
  if ( !data?.length ) { storage = { questions: [] }; }
  return HTTP.Post(
    `/fdhb-tablet/dialogueManage/dialog/${ Visitor.patientId }/${ Visitor.resultId }`,
    { ...toQuestionnaireData (data, storage), asyncTongueResult: true, extendFlow: getAnalysisExtendFlowValue() },
    {
      meta: { ignoreException: true },
      transform(data: Record<string, any>, headers) {
        const { storage: _storage, model } = fromQuestionnaireData(data);
        storage = _storage as any;
        if (model.reportId) Visitor.reportId = model.reportId;
        return model;
      },
    }
  );
}
