<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="选择采集项"
    @ok="handleSubmit"
    @visible-change="handleVisibleChange"
    @cancel="handleCancel"
    width="800px"
    :height="600"
  >
    <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 { FormSchema } from '/@/components/Form';
  import { BasicColumn } from '/@/components/Table';
  import { getMesCollectionItemPage } from '/@/api/jcsj/cjx';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);

  const contentType = ref<string>('');

  const searchFormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '编码',
      component: 'Input',
      colProps: { span: 8 },
    },
    {
      field: 'name',
      label: '名称',
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '编码',
      dataIndex: 'code',
      width: 150,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 200,
    },
    {
      title: '采集内容',
      dataIndex: 'contentType',
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'note',
      width: 200,
    },
  ];

  const [registerTable, { getSelectRows, reload, clearSelectedRowKeys, getForm }] = useTable({
    title: '采集项列表',
    api: getMesCollectionItemPage,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 70,
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'checkbox',
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    pagination: {
      pageSize: 10,
    },
    beforeFetch: (params) => {
      // 根据选择的采集内容过滤
      if (contentType.value) {
        params.contentType = contentType.value;
      }
      return params;
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    contentType.value = data?.contentType || '';
    setModalProps({ confirmLoading: false });
    await reload();
  });

  // 清空弹窗内的操作
  function clearModalOperations() {
    // 清空表格选中项
    clearSelectedRowKeys();
    // 重置搜索表单
    const form = getForm();
    if (form) {
      form.resetFields();
    }
  }

  // 处理弹窗可见性变化
  function handleVisibleChange(visible: boolean) {
    // 当弹窗关闭时，清空操作
    if (!visible) {
      clearModalOperations();
    }
  }

  // 处理取消事件
  function handleCancel() {
    clearModalOperations();
  }

  const handleSubmit = () => {
    const selectedRows = getSelectRows();
    if (selectedRows.length === 0) {
      return;
    }
    emit('success', selectedRows);
    closeModal();
  };
</script>



