<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
      </template>
    </BasicTable>
    <DataBaseModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, nextTick, ref, onMounted } from 'vue';
  import DataBaseModal from './DataBaseModal.vue';
  import { BasicTable, useTable } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';
  import PermissionBtn from '@/components/PermissionBtn/index.vue';
  import { useModal } from '@/components/Modal';
  import { columns, searchFormSchema } from './index.data';
  import { getDataBasePageList, delDataBaseInfo } from '@/api/database';

  const { createConfirm, createMessage } = useMessage();
  const searchInfo = reactive<Recordable>({});
  // 列表
  const [registerTable, { reload, expandAll, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '数据库连接列表',
    api: getDataBasePageList,
    columns,
    rowKey: 'databaseLinkId',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 序号列
    showIndexColumn: true,
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    bordered: true,
    rowSelection: {
      //多选框
      type: 'radio',
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  const [registerModal, { openModal }] = useModal();
  function handleSuccess() {
    reload();
  }
  // 表单列表新增和编辑弹窗
  function handleAddForm() {
    openModal(true, {
      isUpdate: false,
    });
  }
  function handleEdit() {
    let rows = getSelectRows();
    console.log('rows', rows);
    if (rows.length == 0) {
      return createMessage.warn('请选择一条数据进行编辑');
    }
    openModal(true, {
      record: rows[0],
      isUpdate: true,
    });
  }

  // 表单-删除
  function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一条数据进行删除');
    }
    console.log('rrr', rows);
    var query = {
      id: rows[0].databaseLinkId,
    };
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除该条数据？',
      onOk: async () => {
        delDataBaseInfo(query).then((res) => {
          if (res) {
            createMessage.success('删除成功', 2);
          } else {
            createMessage.error('删除失败', 2);
          }
        });
        reload();
      },
    });
  }
  // 表单设计按钮
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        handleAddForm();
        break;
      case 'btnEdit':
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      default:
        break;
    }
  }
</script>
