<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑处方主表' : '添加处方主表'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="处方编号" name="orderNo">
        <a-input
          allow-clear
          placeholder="请输入订单编号"
          v-model:value="form.orderNo"
        />
      </a-form-item>
      <a-form-item label="处方类型 0中药 1西药" name="prescriptionType">
        <a-select v-model:value="form.prescriptionType">
          <a-select-option :value="0">中药</a-select-option>
          <a-select-option :value="1">西药</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="诊断结果" name="diagnosis">
        <a-input
          allow-clear
          placeholder="请输入诊断结果"
          v-model:value="form.diagnosis"
        />
      </a-form-item>
      <a-form-item label="治疗方案" name="treatmentPlan">
        <a-input
          allow-clear
          placeholder="请输入治疗方案"
          v-model:value="form.treatmentPlan"
        />
      </a-form-item>
      <a-form-item label="煎药说明" name="decoctionInstructions">
        <a-input
          allow-clear
          placeholder="请输入煎药说明"
          v-model:value="form.decoctionInstructions"
        />
      </a-form-item>
      <a-form-item label="处方药品" name="items">
        <div class="medicine-list">
          <template v-if="form.items.length">
            <div
              class="medicine-row"
              v-for="item in form.items"
              :key="item._key"
            >
              <a-space :size="12" style="width: 100%" align="center">
                <a-select
                  show-search
                  allow-clear
                  placeholder="请选择药品"
                  v-model:value="item.medicineId"
                  :options="medicineSelectOptions"
                  :filter-option="filterMedicineOption"
                  :loading="medicineLoading"
                  option-filter-prop="label"
                  style="flex: 1"
                />
                <a-input-number
                  :min="1"
                  :precision="0"
                  placeholder="数量"
                  v-model:value="item.quantity"
                  style="width: 120px"
                />
                <a-button type="link" danger @click="removeMedicineItem(item._key)">
                  删除
                </a-button>
              </a-space>
            </div>
          </template>
          <div v-else class="medicine-empty">尚未选择药品，请先添加。</div>
          <a-button
            type="dashed"
            block
            @click="addMedicineItem"
            style="margin-top: 8px"
          >
            添加药品
          </a-button>
        </div>
      </a-form-item>
<!--      <a-form-item label="订单总金额" name="orderPrice">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入订单总金额"-->
<!--          v-model:value="form.orderPrice"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="单价" name="price">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入单价"-->
<!--          v-model:value="form.price"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="实付金额" name="payPrice">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入实付金额"-->
<!--          v-model:value="form.payPrice"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="订单是否失效(0未失效 1已失效)" name="isInvalid">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入订单是否失效(0未失效 1已失效)"-->
<!--          v-model:value="form.isInvalid"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="结算(0未结算 1已结算)" name="isSettled">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入结算(0未结算 1已结算)"-->
<!--          v-model:value="form.isSettled"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="结算时间" name="settleTime">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入结算时间"-->
<!--          v-model:value="form.settleTime"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="状态, 0正常, 1已完成，2已支付，3已取消" name="status">-->
<!--        <a-radio-group v-model:value="form.status">-->
<!--          <a-radio :value="0">显示</a-radio>-->
<!--          <a-radio :value="1">隐藏</a-radio>-->
<!--        </a-radio-group>-->
<!--      </a-form-item>-->
<!--      <a-form-item label="备注" name="comments">-->
<!--        <a-textarea-->
<!--          :rows="4"-->
<!--          :maxlength="200"-->
<!--          placeholder="请输入描述"-->
<!--          v-model:value="form.comments"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="修改时间" name="updateTime">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入修改时间"-->
<!--          v-model:value="form.updateTime"-->
<!--        />-->
<!--      </a-form-item>-->
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addClinicPrescription, updateClinicPrescription } from '@/api/clinic/clinicPrescription';
  import type { ClinicPrescription } from '@/api/clinic/clinicPrescription/model';
  import type { ClinicPrescriptionItem } from '@/api/clinic/clinicPrescriptionItem/model';
  import { listClinicMedicine } from '@/api/clinic/clinicMedicine';
  import type { ClinicMedicine } from '@/api/clinic/clinicMedicine/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';

  type PrescriptionMedicineFormItem = Pick<
    ClinicPrescriptionItem,
    'id' | 'medicineId' | 'quantity'
  > & {
    _key: string;
  };

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ClinicPrescription | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);

  // 用户信息
  const form = reactive<
    ClinicPrescription & {
      items: PrescriptionMedicineFormItem[];
    }
  >({
    id: undefined,
    userId: undefined,
    doctorId: undefined,
    orderNo: undefined,
    visitRecordId: undefined,
    prescriptionType: undefined,
    diagnosis: undefined,
    treatmentPlan: undefined,
    decoctionInstructions: undefined,
    orderPrice: undefined,
    price: undefined,
    payPrice: undefined,
    isInvalid: undefined,
    isSettled: undefined,
    settleTime: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    status: 0,
    comments: '',
    items: []
  });
  const medicineOptions = ref<ClinicMedicine[]>([]);
  const medicineLoading = ref(false);
  const medicineSelectOptions = computed(() =>
    medicineOptions.value
      .filter((item): item is ClinicMedicine & { id: number } => item.id !== undefined)
      .map((item) => ({
        label: item.name ?? '-',
        value: item.id as number,
        pinyin: item.pinyin ?? ''
      }))
  );
  const filterMedicineOption = (input: string, option?: Record<string, any>) => {
    if (!option) {
      return false;
    }
    const keyword = `${option.label ?? ''} ${option.pinyin ?? ''}`.toLowerCase();
    return keyword.includes(input.toLowerCase());
  };
  const createMedicineItem = (item?: ClinicPrescriptionItem): PrescriptionMedicineFormItem => ({
    _key: uuid(),
    id: item?.id,
    medicineId: item?.medicineId,
    quantity: item?.quantity ?? 1
  });
  const loadMedicineOptions = async () => {
    if (medicineLoading.value || medicineOptions.value.length) {
      return;
    }
    medicineLoading.value = true;
    try {
      medicineOptions.value = await listClinicMedicine();
    } catch (e) {
      message.error((e as Error).message);
    } finally {
      medicineLoading.value = false;
    }
  };
  const addMedicineItem = () => {
    form.items.push(createMedicineItem());
  };
  const removeMedicineItem = (key: string) => {
    const index = form.items.findIndex((item) => item._key === key);
    if (index !== -1) {
      form.items.splice(index, 1);
    }
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    clinicPrescriptionName: [
      {
        required: true,
        type: 'string',
        message: '请填写处方主表名称',
        trigger: 'blur'
      }
    ]
  });

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const itemsPayload = form.items
          .filter((item) => item.medicineId)
          .map((item) => ({
            id: item.id,
            medicineId: item.medicineId,
            quantity: item.quantity ?? 1
          }));
        const formData: ClinicPrescription = {
          ...form,
          items: itemsPayload
        };
        const saveOrUpdate = isUpdate.value ? updateClinicPrescription : addClinicPrescription;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        loadMedicineOptions();
        if (props.data) {
          assignObject(form, props.data);
          form.items = (props.data.items ?? []).map((item) => createMedicineItem(item));
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
          form.items = [];
        }
      } else {
        resetFields();
        form.items = [];
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
.medicine-list {
  width: 100%;
}

.medicine-row {
  margin-bottom: 8px;
}

.medicine-empty {
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.45);
}
</style>
