import { cacheFor }                                                     from '@/request/api/index';
import { type Fields, fromRegisterFields, getPath, type RegisterModel } from '@/request/model';
import { useVisitor } from '@/stores';

import HTTP from '../alova';


export function getCaptchaMethod(mobile: string) {
  return HTTP.Get<string>(`/fdhb-tablet/sms/sendVerCode`, {
    params: { phone: mobile },
  });
}

export function registerFieldsMethod() {
  return HTTP.Post<Fields, { tabletFileFields: string[] }>(`/fdhb-tablet/warrantManage/getPageSets`, void 0, {
    cacheFor, name: `variate:register_fields`,
    params: { k: 'register_fields' },
    transform(data, headers) {
      const options = data?.tabletFileFields ?? [];
      return fromRegisterFields(options);
    },
  });
}

export function registerVisitorMethod() {
  return HTTP.Get<string, string>(`/fdhb-tablet/patientInfoManage/createTourist`, {
    name: 'register',
    cacheFor: null,
  })
}

export function registerAccountMethod(params: Partial<RegisterModel>) {
  return HTTP.Post<string, string>(`/fdhb-tablet/patientInfoManage/savePatientInfo`, params, {
    name: 'register',
    transform(data) {
      const Visitor = useVisitor();
      Visitor.patientId = data;
      return data;
    },
  });
}

export function searchAccountMethod(params: Partial<RegisterModel>) {
  return HTTP.Get(`/fdhb-tablet/patientInfoManage/getPatientInfoDetail`, {
    hitSource: 'register',
    params,
    transform(data: Record<string, any>, headers) {
      return Object.fromEntries(Object.entries(data).filter(([ item, value ]) => !!value)) as Partial<RegisterModel>;
    },
  });
}

export function scanAccountMethod(key: string) {
  return HTTP.Get(`/fdhb-tablet/patientInfoManage/getPatInfoByScanCode`, {
    hitSource: 'register',
    params: { scanCode: key },
    transform(data: Record<string, any>, headers) {
      const { id: patientId, processModule, ..._data } = data;
      if ( patientId ) useVisitor().patientId = patientId;
      return {
        key, patientId, path: getPath(processModule),
        model: Object.fromEntries(Object.entries(_data).filter(([ item, value ]) => !!value)) as Partial<RegisterModel>,
      };
    },
  });
}
