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

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

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

import { useVbenForm } from '#/adapter/form';

import {
  createSpecialPrescription,
  getSpecialPrescriptionInfo,
  updateSpecialPrescription,
} from '../api';
import ChineseDrugEditor from './ChineseDrugEditor.vue';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
const prescriptionType = ref<'chinese' | 'west' | 'granular'>('chinese');
const chineseDrugEditorRef = ref<InstanceType<typeof ChineseDrugEditor>>();
const dosage = ref(7);
const dayDosage = ref(2);
const drugsChanged = ref(false);
/** 预选诊断/医嘱（在药品列表气泡卡中编辑） */
const clinicalDiagnose = ref('');
const doctorOrder = ref('');

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const validation = await formApi.validate();
    if (!validation.valid) {
      return;
    }
    const values = await formApi.getValues();
    prescriptionType.value = values.prescription_type || 'chinese';

    let drugs: any[] = [];
    if (prescriptionType.value === 'chinese') {
      drugs = chineseDrugEditorRef.value?.getDrugsPayload() || [];
      if (!isUpdate.value && drugs.length === 0) {
        message.warning('请至少添加一种中药');
        return;
      }
      if (drugs.length > 0) {
        drugsChanged.value = true;
      }
    } else if (!isUpdate.value) {
      message.warning('当前仅支持在后台配置中药类型处方，请选择中药类型');
      return;
    }

    const payload: Record<string, any> = {
      ...values,
      tags: Array.isArray(values.tags)
        ? values.tags
        : String(values.tags || '')
            .split(',')
            .map((s: string) => s.trim())
            .filter(Boolean),
    };

    const diagnosisOrder =
      chineseDrugEditorRef.value?.getDiagnosisOrderPayload?.() ?? {
        clinical_diagnose: clinicalDiagnose.value,
        doctor_order: doctorOrder.value,
      };
    payload.clinical_diagnose = diagnosisOrder.clinical_diagnose ?? '';
    payload.doctor_order = diagnosisOrder.doctor_order ?? '';

    if (prescriptionType.value === 'chinese' && drugs.length > 0) {
      payload.drugs = drugs;
      payload.dosage = dosage.value;
      payload.day_dosage = dayDosage.value;
      payload.rule_type = 1;
      payload.package_method_id = 2;
    } else if (isUpdate.value && !drugsChanged.value) {
      delete payload.drugs;
    }

    modalApi.setState({ loading: true, confirmLoading: true });
    const submitApi = isUpdate.value ? updateSpecialPrescription : createSpecialPrescription;
    submitApi(payload)
      .then(() => {
        message.success('保存成功');
        gridApi.value?.reload();
        modalApi.close();
      })
      .finally(() => {
        modalApi.setState({ loading: false, confirmLoading: false });
      });
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      bindPrescriptionTypeChange();
      const { values, update } = modalApi.getData<Record<string, any>>();
      drugsChanged.value = false;
      if (values && update) {
        isUpdate.value = true;
        getSpecialPrescriptionInfo(values.id).then((res: any) => {
          if (!res) return;
          prescriptionType.value = res.prescription_type || 'chinese';
          formApi.setValues({
            id: res.id,
            name: res.name || '',
            category_id: res.category_id,
            cover_image: res.cover_image || '',
            tags: Array.isArray(res.tags) ? res.tags : [],
            price_per_dose: res.price_per_dose ?? 0,
            sales_count: res.sales_count ?? 0,
            status: res.status ?? 1,
            prescription_type: res.prescription_type || 'chinese',
            intro_text: res.intro_text || '',
            introduction_images: res.introduction_images || [],
          });
          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,
            );
            dosage.value = first?.dosage ?? 7;
            dayDosage.value = first?.consumption ?? 2;
          }
        });
      } else {
        isUpdate.value = false;
        prescriptionType.value = 'chinese';
        dosage.value = 7;
        dayDosage.value = 2;
        formApi.resetForm();
        formApi.setValues({
          id: '',
          name: '',
          category_id: undefined,
          cover_image: '',
          tags: [],
          price_per_dose: 0,
          sales_count: 0,
          status: 1,
          prescription_type: 'chinese',
          intro_text: '',
          introduction_images: [],
        });
        clinicalDiagnose.value = '';
        doctorOrder.value = '';
        chineseDrugEditorRef.value?.loadDrugs([], 7, 2);
      }
    } else {
      formApi.resetForm();
    }
  },
});

function bindPrescriptionTypeChange() {
  formApi.updateSchema([
    {
      fieldName: 'prescription_type',
      componentProps: {
        onChange: (val: string) => {
          prescriptionType.value = val || 'chinese';
        },
      },
    },
  ]);
}
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}特色方`" class="w-[80%]">
    <Form />
    <div v-if="prescriptionType === 'chinese'" class="mt-4 border-t pt-4">
      <ChineseDrugEditor
        ref="chineseDrugEditorRef"
        v-model:clinical-diagnose="clinicalDiagnose"
        v-model:doctor-order="doctorOrder"
        v-model:dosage="dosage"
        v-model:day-dosage="dayDosage"
        @update:model-value="drugsChanged = true"
      />
    </div>
    <Alert
      v-else
      class="mt-4"
      type="info"
      show-icon
      message="西药/颗粒药类型请切换为中药后在后台配置，或通过创建接口传入 drugs 数组保存。"
    />
  </Modal>
</template>
