<template>

  <BasicModal v-bind="$attrs" :title="modalTitle" :width="1000" @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 } from '/@/views/xslmes/mesXslRubberQuickTestDataPoint/MesXslRubberQuickTestDataPoint.api';



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



  const filterQuickTestTypeId = ref('');

  const selectedRows = ref<Recordable[]>([]);



  const modalTitle = computed(() => '选择数据点（可多选）');



  function handleSelectionChange(_keys: string[], rows: Recordable[]) {

    selectedRows.value = rows || [];

  }



  function fetchPointPage(params: Recordable) {

    const p = { ...params };

    if (filterQuickTestTypeId.value) {

      p.quickTestTypeId = filterQuickTestTypeId.value;

    }

    return list(p);

  }



  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({

    api: fetchPointPage,

    columns: [

      { title: '数据点名称', dataIndex: 'pointName', width: 160 },

      { title: '实验类型', dataIndex: 'quickTestTypeName', width: 140 },

      { title: '单位类型', dataIndex: 'unitType', width: 120 },

      { title: '描述', dataIndex: 'pointDesc', width: 200, ellipsis: true },

    ],

    rowKey: 'id',

    useSearchForm: true,

    formConfig: {

      labelWidth: 90,

      schemas: [

        { label: '数据点名称', field: 'pointName', component: 'Input', colProps: { span: 8 } },

      ],

    },

    pagination: { pageSize: 10 },

    canResize: false,

    showIndexColumn: false,

    immediate: true,

    rowSelection: {

      type: 'checkbox',

      columnWidth: 48,

      onChange: handleSelectionChange,

    },

    clickToRowSelect: true,

  });



  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {

    filterQuickTestTypeId.value = data?.quickTestTypeId ? String(data.quickTestTypeId) : '';

    selectedRows.value = [];

    clearSelectedRowKeys?.();

    setModalProps({ confirmLoading: false });

    reload();

  });



  async function handleOk() {

    let rows = selectedRows.value?.length ? [...selectedRows.value] : ((getSelectRows?.() || []) as Recordable[]);

    const valid = rows.filter((r) => r?.id && r.pointName != null);

    if (!valid.length) {

      closeModal();

      return;

    }

    emit('select', valid);

    closeModal();

  }

</script>

