<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        search
        toolbar
        title="数据库目录"
        :clickRowToExpand="true"
        :treeData="treeData"
        :selectedKeys="selectedTreeKeys"
        expandOnSearch
        :fieldNames="{ key: 'id', title: 'dbName' }"
        @select="handleSelect"
      />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerCurrentTable" @expand="expandedRowsChange">
        <template #toolbar>
          <a-button @click="createApi" type="primary">生成在线接口</a-button>
          <a-button @click="createCode" type="primary" class="!mr-4">生成代码</a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '打开数据表',
                onClick: openTable.bind(null, record),
              },
            ]"
          />
        </template>
        <template #expandedRowRender="{ record }">
          <a-table
            size="middle"
            :columns="innerColumns"
            :data-source="innerDatasource(record.tableName)"
            :pagination="false"
          >
            <template #headerCell="{ column }">
              <HeaderCell :column="column" />
            </template>
            <template #bodyCell="{ column }">
              <template v-if="column.dataIndex === 'nullable' || column.dataIndex === 'primaryKey'">
                {{ record[column.dataIndex] ? '是' : '否' }}
              </template>
            </template>
          </a-table>
        </template>
      </BasicTable>
    </template>
    <TableModal @register="registerTableModal" />
    <CreateModal @register="registerCreateModal" @success="handleSuccess" />
    <CreateApiModal @register="registerApiModal" @success="reloadTable" />
    <LoadingBox v-if="isLoading" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { BasicTable, useTable, FormSchema, BasicColumn, TableAction } from '/@/components/Table';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import {
    getDatabaselinkTree,
    getDatabaselinkTable,
    getDatabaselinkMultiTableColumns,
  } from '/@/api/system/databaselink';
  import { batchGeneratorCode } from '/@/api/system/generator';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import TableModal from './components/TableModal.vue';
  import CreateModal from './components/CreateModal.vue';
  import CreateApiModal from './components/CreateApiModal.vue';
  import LoadingBox from './components/LoadingBox.vue';
  import HeaderCell from '/@/components/Table/src/components/HeaderCell.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '表名',
      dataIndex: 'tableName',
      align: 'center',
    },
    {
      title: '表备注',
      dataIndex: 'tableComment',
      align: 'center',
    },
  ];

  const innerColumns: BasicColumn[] = [
    {
      title: '字段名',
      dataIndex: 'column',
      width: 150,
      align: 'center',
    },
    {
      title: '字段类型',
      dataIndex: 'dataType',
      align: 'center',
    },
    {
      title: '默认值',
      dataIndex: 'columnDefault',
      align: 'center',
    },
    {
      title: '字段长度',
      dataIndex: 'dataLength',
      align: 'center',
    },
    {
      title: '主键',
      dataIndex: 'primaryKey',
      align: 'center',
    },
    {
      title: '允许为空',
      dataIndex: 'nullable',
      align: 'center',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'tableName',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const { notification } = useMessage();

  const treeData = ref<TreeItem[]>([]);
  const selectedTreeKeys = ref<string[]>([]);
  const innerData = ref<any[]>([]);
  const isLoading = ref(false);
  const selectDBId = ref('');

  const innerDatasource = (tableName) => {
    const data = innerData.value.filter((item) => {
      if (item && Object.keys(item)) {
        return Object.keys(item)[0] === tableName;
      }
    });
    return data?.length ? data[0][tableName] : [];
  };

  const [registerTableModal, { openModal: openTableModal }] = useModal();
  const [registerCreateModal, { openModal: openCreateModal }] = useModal();
  const [registerApiModal, { openModal: openApiModal }] = useModal();
  onMounted(async () => {
    treeData.value = (await getDatabaselinkTree()) as unknown as TreeItem[];
    if (treeData.value.length) {
      let id = treeData.value.length ? treeData.value[0].id : '';
      selectedTreeKeys.value = [id];
      handleSelect([id]);
    }
  });

  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.tableName) >= 0) {
          let index = selectedRowKeys.indexOf(record.tableName);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.tableName);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };

  const [
    registerCurrentTable,
    { reload: reloadTable, setSelectedRowKeys, getSelectRowKeys, setProps },
  ] = useTable({
    title: '数据表列表',
    rowKey: 'tableName',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      return { ...params, id: selectDBId.value };
    },
    useSearchForm: true,
    striped: false,
    showIndexColumn: false,
    isPaginateByDataSource: true,
    rowSelection: {
      type: 'checkbox',
    },
    customRow,
    actionColumn: {
      width: 86,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const handleSelect = async (id) => {
    selectDBId.value = id[0];
    setProps({
      api: getDatabaselinkTable,
    });
    reloadTable();
  };

  const checkInfo = () => {
    if (!selectDBId.value) {
      notification.warning({
        message: 'Tip',
        description: '请选择数据库表',
      });
      return false;
    }
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择数据库表',
      });
      return false;
    }
    return true;
  };

  const openTable = (record) => {
    if (!selectDBId.value) {
      notification.warning({
        message: 'Tip',
        description: '请选择数据库表',
      });
      return false;
    }
    openTableModal(true, {
      databaseId: selectDBId.value,
      tableName: record.tableName,
    });
  };

  const createCode = () => {
    const isTrue = checkInfo();
    if (!isTrue) return;
    openCreateModal(true, { databaseId: selectDBId.value, tableName: getSelectRowKeys() });
  };
  const createApi = () => {
    const isTrue = checkInfo();
    if (!isTrue) return;
    if (getSelectRowKeys().length > 1) {
      notification.warning({
        message: 'Tip',
        description: '请只选择一个数据库表',
      });
      return false;
    }
    openApiModal(true, getSelectRowKeys()[0]);
  };
  async function expandedRowsChange(isOpen, record) {
    if (!isOpen || !!innerData.value?.find((x) => x[record.tableName])) return;
    const tableInfos = await getDatabaselinkMultiTableColumns({
      id: selectDBId.value,
      tableNames: record.tableName,
    });
    innerData.value.push(tableInfos);
  }

  const handleSuccess = async (data) => {
    isLoading.value = true;
    data.map(async (item) => {
      await batchGeneratorCode(item);
    });
    isLoading.value = false;
    notification.success({
      message: t('提示'),
      description: '生成代码成功！',
    });
  };
</script>
<style lang="less" scoped>
  .left-box {
    overflow: hidden;
    background: #fff;
    height: 100%;
    border-right: 1px solid #e5e7eb;
  }

  :deep(.ant-spin-nested-loading) {
    overflow: hidden;
  }
</style>
