import type { CascaderOption, Dictionaries, Fields, RegisterModel } from '@/request/model';
import { cacheFor } from '@/request/api/index';
import { fromRegisterFields } from '@/request/model';
import { getRoutePath } from '@/router';
import { useVisitor } from '@/stores';
import { getClientURL } from '@/tools';

import HTTP from '../alova';


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

export function registerFieldsMethod(dictionaries?: Dictionaries) {
  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, dictionaries);
    },
  });
}

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

export function registerAccountMethod(params: Partial<RegisterModel>) {
  if (Array.isArray(params.address) && params.address.length > 0) {
    const key = ['province', 'city', 'area'];
    params.address.forEach(({ label, value }, index) => {
      (params as Record<string, string>)[`${key[index]}Name`] = label;
      (params as Record<string, string>)[`${key[index]}Code`] = value.padEnd(6, '0').slice(0, 6);
    });
  }
  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) {
      if (data) data.address = [];
      const address = ['province', 'city', 'area'];
      for (const key of address) {
        const code = data?.[`${key}Code`];
        const name = data?.[`${key}Name`];
        Reflect.deleteProperty(data, `${key}Code`);
        Reflect.deleteProperty(data, `${key}Name`);
        if (name && code) data.address.push({ label: name, value: key === 'province' ? code.slice(0, 2) : code.padEnd(12, '0') });
        else {
          Reflect.deleteProperty(data, 'address');
          break;
        }
      }
      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: getRoutePath(processModule),
        model: Object.fromEntries(Object.entries(_data).filter(([ item, value ]) => !!value)) as Partial<RegisterModel>,
      };
    },
  });
}

export function dictionariesMethod() {
  return HTTP.Get<Dictionaries | void, any>(`/fdhb-tablet/dict/getDicts`, {
    cacheFor, name: `variate:dict`,
    transform(data) {
      if (!Array.isArray(data)) return void 0;
      const dictionaries: Dictionaries = new Map();
      for (const { dictType, items } of data) dictionaries.set(dictType, items.map((item: any) => ({label: item.dictLabel, value: item.dictValue })));
      return dictionaries.size ? dictionaries : void 0;
    },
  });
}

export function regionsMethod() {
  return HTTP.Get<CascaderOption[]>(getClientURL('/database/regions.json'), {
    cacheFor: {
      mode: 'restore',
      expire: Infinity,
      tag: __APP_VERSION__,
    }
  })
}