<template>
  <BasicModal v-bind="$attrs" title="选择设备大部位" :width="960" @register="registerModal" @ok="handleOk">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

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

  const emit = defineEmits(['register', 'select']);

  const selectedRow = ref<Recordable | null>(null);
  const filterCategoryId = ref('');

  function handleSelectionChange(_keys: string[], rows: Recordable[]) {
    selectedRow.value = rows?.[0] ?? null;
  }

  function fetchPartPage(params: Recordable) {
    const p = { ...params };
    if (filterCategoryId.value) {
      p.equipmentCategoryId = filterCategoryId.value;
    }
    return list(p);
  }

  const [registerTable, { reload, setProps, getSelectRowKeys, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] =
    useTable({
      api: fetchPartPage,
      columns: [
        { title: '部位代码', dataIndex: 'partCode', width: 120 },
        { title: '部位名称', dataIndex: 'partName', width: 160 },
        { title: '类别名称', dataIndex: 'equipmentCategoryName', width: 160 },
      ],
      rowKey: 'id',
      useSearchForm: true,
      formConfig: {
        labelWidth: 90,
        schemas: [
          { label: '部位代码', field: 'partCode', component: 'Input', colProps: { span: 8 } },
          { label: '部位名称', field: 'partName', component: 'Input', colProps: { span: 8 } },
        ],
      },
      pagination: { pageSize: 10 },
      canResize: false,
      showIndexColumn: false,
      immediate: true,
      rowSelection: {
        type: 'radio',
        columnWidth: 48,
        onChange: handleSelectionChange,
      },
      clickToRowSelect: true,
    });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    filterCategoryId.value = data?.equipmentCategoryId ? String(data.equipmentCategoryId) : '';
    selectedRow.value = null;
    clearSelectedRowKeys?.();
    setProps({
      rowSelection: {
        type: 'radio',
        columnWidth: 48,
        onChange: handleSelectionChange,
      },
      clickToRowSelect: true,
    });
    setModalProps({ confirmLoading: false });
    const pid = data?.equipmentPartId as string | undefined;
    if (pid) {
      setSelectedRowKeys?.([pid]);
      try {
        const raw = await queryById({ id: pid });
        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', { equipmentPartId: '', equipmentPartName: '' });
      closeModal();
      return;
    }
    emit('select', {
      equipmentPartId: row.id,
      equipmentPartName: row.partName || '',
    });
    closeModal();
  }
</script>
