import http from './http';
import {getArray, randomUUID} from '@/tool';

export function getDiseaseListMethod(page = 1, size = 10, query = {}) {
  const keyword = query.keyword;
  return http.post(`/basis/knowlib/diseaseQuery`, {
    serchtype: /* 1: 拼音码 2: 五笔码；搜索中文时可传空*/ /\w+/.test(keyword) ? '1' : '',
    pageid: page,
    pagesize: size,
    ...query, keyword,
  }, {meta: {share: true}}).then(res => {
    const data = res.data || {};
    return {
      total: data.disnum || 0,
      list: getArray(data.diseases, item => Object.assign(item, {
        $uid: randomUUID(),
        $code: item.disCode,
        $name: item.disname,
      })),
    };
  });
}

export function getSymptomListMethod(page = 1, size = 10, query = {}) {
  const keyword = query.keyword;
  return http.post(`/basis/knowlib/symptomQuery`, {
    serchtype: /* 1: 拼音码 2: 五笔码；搜索中文时可传空*/ /\w+/.test(keyword) ? '1' : '',
    pageid: page,
    pagesize: size,
    ...query, keyword,
  }, {meta: {share: true}}).then(res => {
    const data = res.data || {};
    return {
      total: data.sysnum || 0,
      list: getArray(data.sysptoms, item => Object.assign(item, {
        $uid: randomUUID(),
        $code: item.symid,
        $name: item.symname,
        therapies: getArray(item.therapys, item => Object.assign(item, {
          $uid: randomUUID(),
          $code: item.therapyCode,
          $name: item.therapyName,
        })),
      })),
    };
  });
}

export function getTherapyListMethod(page = 1, size = 10, query = {}) {
  const keyword = query.keyword;
  return http.post(`/basis/knowlib/getTherapyAll`, {
    serchtype: /* 1: 拼音码 2: 五笔码；搜索中文时可传空*/ /\w+/.test(keyword) ? '1' : '',
    pageid: page,
    pagesize: size,
    ...query, name: keyword,
  }, {meta: {share: true, ignoreError: true}}).then(res => {
    const list = getArray(res.data, item => Object.assign(item, {
      $uid: randomUUID(),
      $code: item.therapyCode,
      $name: item.therapy,
    }));
    return {total: list.length, list};
  });
}

/**
 *
 * 根据疾病信息推导业务处方
 * @param {string} business 业务类型，多个用逗号分隔
 *   - '1' 中药处方
 *   - '2' 中药制剂
 *   - '3' 适宜技术
 * @param {object} illness 疾病信息对象
 * @param {string} illness.disease.id 疾病ID
 * @param {string} illness.disease.code 疾病代码
 * @param {string} illness.disease.name 疾病名称
 * @param {string} illness.symptom.code 证型代码
 * @param {string} illness.symptom.name 证型名称
 * @param {string} illness.therapy.code 治法代码
 * @param {string} illness.therapy.name 治法名称
 * @return {Promise<*>}
 */
export function deduceIllnessPrescriptionMethod(business = '1,2,3', illness) {
  const [_, prefix = '', special, suffix = ''] = business.match(/^([^1]+)?(?:(1)(?:,|$))?([^1]*)?$/) || ['', business];

  const request = (business) => {
    if (!business) return {expList: [], schemes: []};
    return http.post(`/basis/knowlib/treatmentScheme`, {
      businesstype: business.endsWith(',') ? business.slice(0, -1) : business,
      disid: illness.disease.id,
      symid: illness.symptom.code,
      therapy: illness.therapy.name,
      therapyCode: illness.therapy.code,
      disCode: illness.disease.code,
    }).then(res => {
      const {expList, schemes} = res.data;
      return {schemes, expList: business === '1' ? {pres: expList, businesstype: business} : []};
    });
  };

  return Promise.all([
    request(special),
    request(`${prefix}${suffix}`),
  ]).then(([s, b]) => {
    return {
      expList: [s.expList, b.expList].flat(),
      schemes: [s.schemes, b.schemes].flat(),
    };
  }).then(({schemes, expList}) => {
    const categories = business.split(',');
    const results = {
      * [Symbol.iterator]() { for (const type of categories) yield this[type]; },
    };
    for (const category of categories) {
      const e = expList.find(item => item.businesstype === category) || {pres: []};
      const s = schemes.find(item => item.businesstype === category) || {pres: []};
      results[category] = [
        e.pres.map(item => Object.assign(item, {$category: category, $type: '3'})),
        s.pres.map(item => Object.assign(item, {$category: category, $type: '1'})),
      ].flat(1);
      if (results.index == null && results[category].length) results.index = categories.findIndex(t => t === category);
    }
    return results;
  });
}


/**
 * [legacy] 推导处方
 * {@link deduceIllnessPrescriptionMethod}
 */
export function legacyDeduceIllnessPrescriptionMethod(business, params = {}) {
  return deduceIllnessPrescriptionMethod(business, {
    disease: {code: params.disCode, id: params.disid},
    symptom: {code: params.symptomCode},
    therapy: {code: params.therapyCode, name: params.treatment},
  }).then(data => {
    const categories = business.split(',');
    for (const category of categories) {
      const expList = [], schemes = [];
      for (const prescription of data[category]) {
        if (prescription.$type === '3') expList.push(prescription);
        else if (prescription.$type === '1') schemes.push(prescription);
      }
      data[category] = {code: 0, data: {expList, schemes: [{businesstype: category, presnum: schemes.length, pres: schemes}]}};
    }
    return data;
  });
}