<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-auth="'databaselink:add'">{{
          t('新增')
        }}</a-button>
        <a-button type="primary" @click="handleImport" v-auth="'databaselink:import'">
          {{ t('导入') }}
        </a-button>
        <a-button type="primary" @click="handleExport" v-auth="'databaselink:export'">
          {{ t('导出') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              auth: 'databaselink:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'databaselink:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <DatabaseLinkModal @register="registerModal" @success="handleSuccess" :width="800" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/system/databaselink/import"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    deleteDatabaseLink,
    getDatabaselinkPage,
    exportInfo,
    downloadTemplate,
  } from '/@/api/system/databaselink';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { downloadByData } from '/@/utils/file/download';
  import { ImportModal } from '/@/components/Import';
  import DatabaseLinkModal from './components/DatabaseLinkModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  // import DeptTree from './components/DeptTree.vue';
  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { xs: 16, md: 8 },
      componentProps: {
        placeholder: t('请输入数据库名称'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('数据库名称'),
      dataIndex: 'dbName',
      width: '15%',
      //sorter: true,
      align: 'center',
      resizable: true,
    },

    {
      title: t('数据库类型'),
      dataIndex: 'dbType',
      width: '15%',
      //sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('数据库版本'),
      dataIndex: 'dbVersion',
      width: '15%',
      // sorter: true,
      align: 'center',
      resizable: true,
    },
    // {
    //   title: '驱动',
    //   dataIndex: 'driver',
    //   width: 180,
    //   sorter: true,
    // },
    {
      title: t('链接'),
      dataIndex: 'host',
      // sorter: true,
      align: 'center',
      resizable: true,
    },
  ];

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
      ondblclick: () => {
        if (hasPermission('databaselink:edit')) {
          handleEdit(record);
        }
      },
    };
  };
  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys }] = useTable({
    title: t('数据库链接'),
    api: getDatabaselinkPage,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    useSearchForm: true,
    striped: false,
    showTableSetting: true,
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    rowSelection: {
      type: 'checkbox',
    },
    customRow,
  });

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    deleteDatabaseLink([record.id]).then((_) => {
      reload();
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      }); //提示消息
    });
  }

  function handleSuccess() {
    reload();
  }

  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '数据库链接模板',
    });
  };
  const handleExport = async () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要导出的数据',
      });
      return false;
    }
    const res = await exportInfo(getSelectRowKeys());
    downloadByData(
      res.data,
      '数据库链接.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
