<template>
  <BasicModal v-bind="$attrs" :title="title" :width="900" @register="registerModal" @ok="handleOk">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { list, queryById } from '/@/views/xslmes/mesXslManufacturer/MesXslManufacturer.api';

  const props = defineProps<{ modalTitle?: string }>();
  const emit = defineEmits(['register', 'select']);

  const title = computed(() => props.modalTitle || '选择厂家信息');
  const selectedRow = ref<Recordable | null>(null);

  const [registerTable, { reload, getSelectRowKeys, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] = useTable({
    api: list,
    columns: [
      { title: '厂家类别', dataIndex: 'manufacturerCategory_dictText', width: 120 },
      { title: '厂家名称', dataIndex: 'manufacturerName', width: 200 },
      { title: '是否有效', dataIndex: 'validStatus_dictText', width: 90 },
    ],
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 90,
      schemas: [
        {
          label: '厂家类别',
          field: 'manufacturerCategory',
          component: 'JDictSelectTag',
          componentProps: { dictCode: 'xslmes_manufacturer_category' },
          colProps: { span: 8 },
        },
        { label: '厂家名称', field: 'manufacturerName', component: 'Input', colProps: { span: 8 } },
      ],
    },
    pagination: { pageSize: 10 },
    canResize: false,
    showIndexColumn: false,
    immediate: true,
    rowSelection: {
      type: 'radio',
      columnWidth: 48,
      onChange: (_keys, rows) => {
        selectedRow.value = rows?.[0] ?? null;
      },
    },
    clickToRowSelect: true,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    selectedRow.value = null;
    clearSelectedRowKeys?.();
    setModalProps({ confirmLoading: false });
    const mid = data?.manufacturerId as string | undefined;
    if (mid) {
      setSelectedRowKeys?.([mid]);
      try {
        const raw = await queryById({ id: mid });
        const row = (raw as any)?.id != null ? raw : (raw as any)?.result;
        if (row) selectedRow.value = row;
      } catch {
        // 忽略
      }
    }
    reload();
  });

  async function handleOk() {
    const keys = (getSelectRowKeys?.() || []) as string[];
    let row = selectedRow.value || ((getSelectRows?.() || []) as Recordable[])[0];
    if (!row && keys.length) {
      try {
        const raw = await queryById({ id: keys[0] });
        row = (raw as any)?.id != null ? raw : (raw as any)?.result;
      } catch {
        // 忽略
      }
    }
    if (!row?.id) {
      emit('select', { manufacturerId: '', manufacturerName: '' });
      closeModal();
      return;
    }
    emit('select', {
      manufacturerId: row.id,
      manufacturerName: row.manufacturerName || '',
    });
    closeModal();
  }
</script>
