<script lang="ts" setup>
/**
 * 诊所「添加医生」弹窗
 * 复用 doctor/doctor 的表单 schema 子集（infoModalFormProps），
 * 诊所字段由外部传入并锁定显示，提交时强制写入选中 store_id，
 * 成功后通过传入的 onSuccess 回调刷新父级医生列表。
 */
import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { createDoctor } from '#/views/doctor/doctor/api';
import { infoModalFormProps } from '#/views/doctor/doctor/config/form';

// 当前门店信息（外部 setData 传入）
const storeId = ref(0);
const storeName = ref('');
// 提交成功后回调（由父组件注入，用于刷新医生团队列表）
const onSuccess = ref<(() => void) | null>(null);

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

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    // 校验表单通过后再提交
    formApi.validate().then(async (e: any) => {
      if (!e.valid) return;
      const values = await formApi.getValues();
      // 强制写入当前诊所 id（数组形式，匹配后端 normalizeStoreIds）
      values.store_id = [storeId.value];
      modalApi.setState({ loading: true, confirmLoading: true });
      createDoctor(values)
        .then(() => {
          message.success('添加成功');
          // 通知父组件刷新医生团队列表
          onSuccess.value?.();
          modalApi.close();
        })
        .finally(() => {
          modalApi.setState({ loading: false, confirmLoading: false });
        });
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<{
      storeId: number;
      storeName?: string;
      onSuccess?: () => void;
    }>() || { storeId: 0 };
    storeId.value = Number(data.storeId || 0);
    storeName.value = data.storeName || '';
    onSuccess.value = typeof data.onSuccess === 'function' ? data.onSuccess : null;
    if (storeId.value) {
      // 1) 锁定诊所字段：禁用 + 默认值
      formApi.setValues({ store_id: [storeId.value] });
      formApi.updateSchema([
        {
          fieldName: 'store_id',
          componentProps: {
            disabled: true,
            placeholder: `当前诊所：${storeName.value || storeId.value}`,
          },
        },
      ]);
    }
  },
});
</script>

<template>
  <Modal class="w-[60%]" title="添加医生">
    <Form />
  </Modal>
</template>
