<template>
  <BasicModal v-bind="$attrs" title="选择设备台账" :width="1000" @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/mesXslEquipmentLedger/MesXslEquipmentLedger.api';

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

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

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

  const [registerTable, { reload, getSelectRowKeys, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] = useTable({
    api: list,
    columns: [
      { title: '设备名称', dataIndex: 'equipmentName', width: 160 },
      { title: '设备编号', dataIndex: 'equipmentCode', width: 140 },
      { title: '设备类别', dataIndex: 'equipmentCategoryName', width: 120 },
      { title: '设备类型', dataIndex: 'equipmentTypeName', width: 120 },
    ],
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 90,
      schemas: [
        { label: '设备名称', field: 'equipmentName', component: 'Input', colProps: { span: 8 } },
        { label: '设备编号', field: 'equipmentCode', 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) => {
    selectedRow.value = null;
    clearSelectedRowKeys?.();
    setModalProps({ confirmLoading: false });
    const lid = data?.equipmentLedgerId as string | undefined;
    if (lid) {
      setSelectedRowKeys?.([lid]);
      try {
        const raw = await queryById({ id: lid });
        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', { equipmentLedgerId: '', equipmentName: '', equipmentCode: '' });
      closeModal();
      return;
    }
    emit('select', {
      equipmentLedgerId: row.id,
      equipmentName: row.equipmentName || '',
      equipmentCode: row.equipmentCode || '',
    });
    closeModal();
  }
</script>
