<template>
  <BasicModal
    @register="registerModal"
    :title="t('选择数据库')"
    v-bind="$attrs"
    :min-height="minHeight"
    width="800px"
    @ok="handlerClick"
  >
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useTable, FormSchema, BasicColumn, BasicTable } from '/@/components/Table';
  import { getDatabaselinkTable } from '/@/api/system/databaselink';
  import { ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { TableConfig } from '/@/model/generator/tableConfig';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'tableName',
      label: t('表名'),
      component: 'Input',
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('表名'),
      dataIndex: 'tableName',
      width: 200,
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'tableComment',
      width: 200,
      resizable: true,
    },
  ];

  const databaseId = ref('');

  const minHeight = ref(700);

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

  const { createMessage } = useMessage();

  const [registerTable, { getSelectRows, setSelectedRowKeys, reload }] = useTable({
    title: t('数据表列表'),
    api: getDatabaselinkTable,
    canResize: false,
    rowKey: 'tableName',
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, id: databaseId.value };
    },
    rowSelection: {
      type: 'checkbox',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, canFullscreen: false });
    setSelectedRowKeys(data.selectTableName);
    databaseId.value = data.databaseId;
    reload({ searchInfo: { id: databaseId.value } });
  });

  const handlerClick = () => {
    const selectRows = getSelectRows() as TableConfig[];
    if (selectRows.length === 0) {
      createMessage.error(t('至少需要选择一个数据表！'));
      return;
    }
    selectRows.map((item, index) => {
      item.order = index + 1;
      if (index === 0) {
        item.isMain = true;
      } else {
        item.isMain = false;
      }
    });
    emit('success', selectRows);
    closeModal();
  };
</script>
