<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { fetchDelTable, fetchGenCode, fetchGetTableList, previewTable, synchDb } from '@/service/api/tool/gen';
import { useAppStore } from '@/store/modules/app';
import { useDownLoadFile } from '@/hooks/common/download';
import GenCodePreview from '@/views/tool/gen/modules/gen-code-preview.vue';
import GenSearch from './modules/gen-search.vue';
import ImportTableModal from './modules/import-table-modal.vue';
export type PreviewData = { open: boolean; data: Record<string, string> | null; activeName: string };
const { loading: exportLoading, downLoadZip } = useDownLoadFile();
const appStore = useAppStore();
const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetTableList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    tableName: null,
    tableComment: null,
  },
  columns: () => [
    {
      type: 'selection',
      width: 48,
      align: 'center'
    },
    {
      key: 'tableName',
      title: '表名称',
      align: 'center'
    },
    {
      key: 'tableComment',
      title: '表描述',
      align: 'center'
    },
    {
      key: 'className',
      title: '实体',
      align: 'center'
    },
    {
      key: 'createTime',
      title: '创建时间',
      align: 'center'
    },
    {
      key: 'updateTime',
      title: '更新时间',
      align: 'center'
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="success" ghost size="small" onClick={() => preview(row.tableId)}>
            预览
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.tableId)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
          <NPopconfirm onPositiveClick={() => handleSynchDb(row.tableName)}>
            {{
              default: () => `确认要强制同步"${row.tableName}"表结构吗？`,
              trigger: () => (
                <NButton type="warning" ghost size="small">
                  同步
                </NButton>
              )
            }}
          </NPopconfirm>
          <NButton type="primary" ghost size="small" onClick={() => handleGenCode(row)}>
            生成代码
          </NButton>
        </div>
      )
    }
  ]
});
const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const importTableVisible = ref(false);
// 预览参数
const previewData = ref<PreviewData>({
  open: false,
  data: null,
  activeName: 'domain.java'
});

// 预览
function preview(id: Api.SystemTool.GenInfo['tableId']) {
  previewTable(id).then(res => {
    previewData.value = {
      open: true,
      data: res.data,
      activeName: 'domain.java'
    };
  });
}

// 同步数据库
function handleSynchDb(tableName: Api.SystemTool.GenInfo['tableName']) {
  synchDb(tableName).then(res => {
    if (!res.error) {
      window.$message?.success('同步成功');
    }
  });
}

// 生成代码
async function handleGenCode(row?: any) {
  const tableNames = row?.tableId || checkedRowKeys.value;
  if (!tableNames || (typeof tableNames !== 'number' && tableNames?.length === 0)) {
    window.$message?.error('请选择要生成的数据');
    return;
  }
  if (row?.genType === '1') {
    const { error } = await fetchGenCode(row.tableName);
    if (!error) {
      window.$message?.success(`成功生成到自定义路径：${row.genPath}`);
    }
  } else {
    downLoadZip(`/tool/gen/batchGenCode?tableIdStr=${tableNames}`, 'ruoyi');
  }
}
// 批量删除
async function handleBatchDelete() {
  const { error } = await fetchDelTable(checkedRowKeys.value.toString());
  if (!error) {
    await onBatchDeleted();
  }
}
async function handleDelete(id: string) {
  const { error } = await fetchDelTable(id);
  if (!error) {
    await onDeleted();
  }
}
function openImportTable() {
  importTableVisible.value = true;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <GenSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="代码生成" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NButton size="small" ghost type="warning" @click="openImportTable">导入</NButton>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleGenCode()">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              生成
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        :scroll-x="1088"
        remote
        :pagination="mobilePagination"
        :row-key="(row: any) => row.tableId"
        class="sm:h-full"
      />
    </NCard>
    <GenCodePreview v-model:value="previewData" />
    <ImportTableModal v-model:visible="importTableVisible" @submitted="getData" />
  </div>
</template>

<style scoped></style>
