<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Alert, message } from 'ant-design-vue';

import {
  getSpecialPrescriptionInfo,
  updateSpecialPrescription,
} from '../api';
import { buildSpecialPrescriptionPayload } from '../utils/buildPayload';
import ChineseDrugEditor from './ChineseDrugEditor.vue';

const gridApi = ref<any>();
const detailRes = ref<Record<string, any> | null>(null);
const prescriptionType = ref<'chinese' | 'west' | 'granular'>('chinese');
const chineseDrugEditorRef = ref<InstanceType<typeof ChineseDrugEditor>>();
const dosage = ref(7);
const dayDosage = ref(2);
const clinicalDiagnose = ref('');
const doctorOrder = ref('');

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!detailRes.value) {
      return;
    }
    if (prescriptionType.value !== 'chinese') {
      message.warning('当前仅支持编辑中药类型药方');
      return;
    }
    const drugs = chineseDrugEditorRef.value?.getDrugsPayload() || [];
    if (drugs.length === 0) {
      message.warning('请至少添加一种中药');
      return;
    }
    const diagnosisOrder =
      chineseDrugEditorRef.value?.getDiagnosisOrderPayload?.() ?? {
        clinical_diagnose: clinicalDiagnose.value,
        doctor_order: doctorOrder.value,
      };
    const payload = buildSpecialPrescriptionPayload(detailRes.value, {
      drugs,
      dosage: dosage.value,
      day_dosage: dayDosage.value,
      rule_type: 1,
      package_method_id: 2,
      clinical_diagnose: diagnosisOrder.clinical_diagnose ?? '',
      doctor_order: diagnosisOrder.doctor_order ?? '',
    });
    modalApi.setState({ loading: true, confirmLoading: true });
    updateSpecialPrescription(payload)
      .then(() => {
        message.success('药方保存成功');
        gridApi.value?.reload();
        modalApi.close();
      })
      .finally(() => {
        modalApi.setState({ loading: false, confirmLoading: false });
      });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, gridApi: grid } = modalApi.getData<Record<string, any>>();
      gridApi.value = grid;
      detailRes.value = null;
      getSpecialPrescriptionInfo(values.id).then((res: any) => {
        if (!res) return;
        detailRes.value = res;
        prescriptionType.value = res.prescription_type || 'chinese';
        clinicalDiagnose.value = res.clinical_diagnose || '';
        doctorOrder.value = res.doctor_order || '';
        if (res.prescription_type === 'chinese' && res.prescription_detail?.length) {
          const first = res.prescription_detail[0];
          chineseDrugEditorRef.value?.loadDrugs(
            res.prescription_detail,
            first?.dosage ?? 7,
            first?.consumption ?? 2,
            res.drug_prices || [],
          );
          dosage.value = first?.dosage ?? 7;
          dayDosage.value = first?.consumption ?? 2;
        } else {
          chineseDrugEditorRef.value?.loadDrugs([], 7, 2);
        }
      });
    } else {
      detailRes.value = null;
      clinicalDiagnose.value = '';
      doctorOrder.value = '';
    }
  },
});
</script>

<template>
  <Modal title="编辑药方" class="w-[80%]">
    <div v-if="prescriptionType === 'chinese'">
      <ChineseDrugEditor
        ref="chineseDrugEditorRef"
        v-model:clinical-diagnose="clinicalDiagnose"
        v-model:doctor-order="doctorOrder"
        v-model:dosage="dosage"
        v-model:day-dosage="dayDosage"
      />
    </div>
    <Alert
      v-else
      type="info"
      show-icon
      message="当前特色方为西药/颗粒药类型，后台暂不支持单独编辑药方。"
    />
  </Modal>
</template>
