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

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

import { Form, FormItem, message, Radio, RadioGroup, Select } from 'ant-design-vue';

import { bindOnlineConsultationApi, getDoctorOptionApi, getInternetMedicalStoreOptionApi } from '../api';

// 表单数据
const formState = ref({
  id: undefined as number | undefined,
  is_internet_medical: 0,
  delegate_store_id: undefined as number | undefined,
  online_consultation_doctor_id: undefined as number | undefined,
});

// 下拉选项
const storeOptions = ref<Array<{ id: number; name: string }>>([]);
const doctorOptions = ref<Array<{ id: number; name: string }>>([]);
const gridApiRef = ref<any>(null);
const loading = ref(false);

// 根据诊所ID获取医生列表
async function loadDoctorOptions(storeId?: number) {
  if (!storeId) {
    doctorOptions.value = [];
    return;
  }
  try {
    const doctors = await getDoctorOptionApi(storeId);
    doctorOptions.value = doctors || [];
  } catch (error) {
    console.error('获取医生列表失败:', error);
    doctorOptions.value = [];
  }
}

// 监听资质变化
watch(
  () => formState.value.is_internet_medical,
  (newVal) => {
    if (newVal === 1) {
      // 有资质时，根据当前诊所ID加载医生
      formState.value.delegate_store_id = undefined;
      if (formState.value.id) {
        loadDoctorOptions(formState.value.id);
      }
    } else {
      // 无资质时，清空医生列表，等待选择委托诊所
      formState.value.online_consultation_doctor_id = undefined;
      doctorOptions.value = [];
    }
  },
);

// 监听委托诊所变化
watch(
  () => formState.value.delegate_store_id,
  (newVal) => {
    if (newVal) {
      loadDoctorOptions(newVal);
      formState.value.online_consultation_doctor_id = undefined;
    } else {
      doctorOptions.value = [];
    }
  },
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    loading.value = true;
    modalApi.setState({ confirmLoading: true });
    try {
      await bindOnlineConsultationApi({
        id: formState.value.id!,
        is_internet_medical: formState.value.is_internet_medical,
        delegate_store_id: formState.value.delegate_store_id || null,
        online_consultation_doctor_id: formState.value.online_consultation_doctor_id || null,
      });
      message.success('绑定成功');
      gridApiRef.value?.reload();
      modalApi.close();
    } catch (error) {
      message.error('绑定失败');
    } finally {
      loading.value = false;
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, gridApi } = modalApi.getData<Record<string, any>>();
      gridApiRef.value = gridApi;

      // 重置表单
      formState.value = {
        id: values?.id,
        is_internet_medical: values?.is_internet_medical ?? 0,
        delegate_store_id: values?.delegate_store_id,
        online_consultation_doctor_id: values?.online_consultation_doctor_id,
      };

      // 加载有资质诊所列表
      try {
        const stores = await getInternetMedicalStoreOptionApi();
        storeOptions.value = stores || [];
      } catch (error) {
        console.error('获取有资质诊所列表失败:', error);
        storeOptions.value = [];
      }

      // 根据当前配置加载医生列表
      if (formState.value.is_internet_medical === 1) {
        // 有资质，根据自身ID加载医生
        loadDoctorOptions(formState.value.id);
      } else if (formState.value.delegate_store_id) {
        // 无资质但有委托诊所，根据委托诊所加载医生
        loadDoctorOptions(formState.value.delegate_store_id);
      }
    }
  },
});
</script>

<template>
  <Modal title="绑定在线复诊配置" class="w-[500px]">
    <Form :model="formState" layout="vertical">
      <FormItem label="互联网诊疗资质">
        <RadioGroup v-model:value="formState.is_internet_medical">
          <Radio :value="0">无资质</Radio>
          <Radio :value="1">有资质</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem v-if="formState.is_internet_medical === 0" label="委托在线复诊诊所">
        <Select
          v-model:value="formState.delegate_store_id"
          :options="storeOptions"
          :field-names="{ label: 'name', value: 'id' }"
          placeholder="请选择委托诊所"
          allow-clear
          show-search
          :filter-option="(input: string, option: any) => option.name.toLowerCase().includes(input.toLowerCase())"
        />
      </FormItem>

      <FormItem
        v-if="formState.is_internet_medical === 1 || formState.delegate_store_id"
        label="在线复诊负责人"
      >
        <Select
          v-model:value="formState.online_consultation_doctor_id"
          :options="doctorOptions"
          :field-names="{ label: 'name', value: 'id' }"
          placeholder="请选择在线复诊负责人"
          allow-clear
          show-search
          :filter-option="(input: string, option: any) => option.name.toLowerCase().includes(input.toLowerCase())"
        />
      </FormItem>
    </Form>
  </Modal>
</template>

