import {findArray, getArray, toArray, tryRun} from '@/tool';

import http from './http';
import {ReasonableSafeMedicine} from './model';
import {CC_Dosage2Basis} from '@/utils/medicine';

/**
 * 获取合理安全用药 剂量范围
 * @param medicine
 * @return {Promise<{dosageRange: string} & Object>}
 */
export async function getReasonableSafeMedicineDosageRange(medicine) {
  if (!medicine.dosageRange) {
    const data = await http.post(`/basis/knowlib/medicineInfoQuery`, null, {
      params: {matid: medicine.matid},
      meta: {share: true, key: medicine.matid},
    }).then(res => res.data || {});

    const matmindosage = tryRun(() => data['matmindosage']);
    const matmaxdosage = tryRun(() => data['matmaxdosage']);
    medicine['matmindosage'] = +matmindosage;
    medicine['matmaxdosage'] = +matmaxdosage;
    medicine['dosageRange'] = [matmindosage, matmaxdosage].filter(Boolean).join('-');
  }

  const dosage = CC_Dosage2Basis(medicine);

  medicine['rs@10.1'] = '';
  medicine['rs@10.2'] = '';
  if (dosage && medicine.matmindosage && medicine.dose < medicine.matmindosage) medicine['rs@10.1'] = `${medicine.matname || medicine.name}${dosage}g(${medicine.dosageRange})`;
  if (dosage && medicine.matmaxdosage && medicine.dose > medicine.matmaxdosage) medicine['rs@10.2'] = `${medicine.matname || medicine.name}${dosage}g(${medicine.dosageRange})`;


  return medicine;
}

/**
 * 检测合理安全用药
 * @param {object[]} medicines 药品
 * @param {object} params 参数
 * @param {object} params.patient 患者信息
 * @param {object} params.illness 疾病信息
 * @return {Promise<*>}
 */
export function checkReasonableSafeMedicinesMethod(medicines, params) {
  const find = (matid = '') => findArray(medicines, ['matid', matid.toString()]) || {};
  const append = (medicine, field, value) => { medicine[field] = medicine[field] ? `${medicine[field]}|${value}` : value; };
  return http.post(`/basis/knowlib/interactionReport`, {
    medList: medicines.filter(medicine => medicine.matid).map(medicine => {
      for (const key of Object.keys(medicine)) if (key.startsWith(`rs@`)) delete medicine[key];
      return {
        pid: medicine.pid, name: medicine.name,
        medId: medicine.matid,
        medName: medicine.matname,
        medDose: CC_Dosage2Basis(medicine) || 0,
        medUsage: medicine.usage || '',
      };
    }),
    age: tryRun(() => params.patient.age),
    gender: tryRun(() => ({'男': 'M', '女': 'F'}[params.patient.sex])),
    gravidity: tryRun(() => ({'2': 'Y', '1': 'N'}[params.patient.isGravidity])),
    disId: tryRun(() => params.illness.disease.id, ''),
    synId: tryRun(() => params.illness.symptom.code, ''),
    diseaseCode: tryRun(() => params.illness.disease.code, ''),
    symptomCode: tryRun(() => params.illness.symptom.code, ''),
  }, {meta: {share: true}}).then(res => {
    for (const {field, key} of ReasonableSafeMedicine.config) {
      if (!key) continue;
      tryRun(() => {
        getArray(res.data[key], item => {
          const value = item.medDesc;
          const medicine = find(item.medId);
          if (key !== 'lowDose' || medicine.dose) {
            append(medicine, field, value);
            toArray(item.incMeds, item => {
              const medicine = find(item.medId);
              append(medicine, field, value);
            });
          }
        });
      });
    }
    return medicines;
  });
}