<script lang="ts" setup>
/**
 * 医生绑定诊所弹窗：使用门店多选搜索（名称/首拼），替代全量 Select
 */
import { ref } from 'vue';

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

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

import StoreMultiSearch from '#/components/form/components/store-multi-search.vue';
import { updateDoctorStoreBindApi } from '#/views/doctor/doctor/api';

const gridApi = ref();
const data = ref<{ su_id?: number; stores?: number[] }>({ stores: [] });
/** 打开时回填已绑门店名称 */
const initialItems = ref<{ id: number; name: string }[]>([]);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    updateDoctorStoreBindApi({
      doctor_id: data.value.su_id,
      store_ids: data.value.stores || [],
    }).then(() => {
      modalApi.close();
      message.success('保存成功');
      gridApi.value?.reload();
    });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      gridApi.value = modalApi.getData()?.gridApi ?? null;
      const { values } = modalApi.getData<Record<string, any>>() || {};
      if (values) {
        const copied = JSON.parse(JSON.stringify(values));
        const storesRaw = copied.stores || [];
        initialItems.value = storesRaw.map((item: any) => ({
          id: Number(item.store_id ?? item.id),
          name: String(item.store?.name || item.name || `门店${item.store_id ?? item.id}`),
        }));
        data.value = {
          su_id: copied.su_id,
          stores: storesRaw.map((item: any) => Number(item.store_id ?? item.id)),
        };
      }
    }
  },
});
</script>

<template>
  <Modal class="w-[60%] h-[80%]" title="绑定诊所">
    <div style="width: 80%; margin: 30px auto">
      <StoreMultiSearch
        v-if="data"
        v-model:value="data.stores"
        :initial-items="initialItems"
        :store-type="0"
        placeholder="输入诊所名称或拼音首拼搜索"
      />
    </div>
  </Modal>
</template>
