<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Gen } from '#/api/tool/gen/model';

import { useRouter } from 'vue-router';

import { Page, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteGen, genCode, getGenList, syncTable } from '#/api/tool/gen/gen';
import { downloadByData } from '#/utils/file/download';

import CodeModalComp from './code-modal.vue';
import { columns, querySchema } from './config-data';
import DbModalComp from './db-modal.vue';
import SqlModalComp from './sql-modal.vue';

const [DbModal, dbModalApi] = useVbenModal({
  connectedComponent: DbModalComp,
});
const [CodeModal, codeModalApi] = useVbenModal({
  connectedComponent: CodeModalComp,
});
const [SqlModal, sqlModalApi] = useVbenModal({
  connectedComponent: SqlModalComp,
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.roleId !== 1,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getGenList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'roleId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 单个删除表
async function confirmEvent(gen: Gen) {
  await deleteGen([gen.tableId!]);
  await BasicTableApi.reload();
}
// 多个删除表
function deleteRoles() {
  // 获取全部选中的数据
  const checkRecords = BasicTableApi.grid.getCheckboxRecords();
  // 数据转换只要tableId
  const ids = checkRecords.map((item: Gen) => item.tableId) as [];
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除角色
    await deleteGen(ids);
    // 重置查询
    await BasicTableApi.reload();
  });
}
async function exportDbHandle() {
  dbModalApi.open();
}
// 代码预览
function previewHandle(tableId: number) {
  codeModalApi.setData({ tableId }).open();
}
// 同步表结构
function syncHandle(tableName: string) {
  ElMessageBox.confirm(`确认要强制同步${tableName}表结构吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除角色
    await syncTable(tableName);
    // 重置查询
    await BasicTableApi.query();
  });
}
// 下载生成代码
async function genHandle(tableName: string) {
  const blobData = await genCode([tableName]);
  downloadByData(blobData, 'ruoyi', 'application/zip');
}
// 多选生成代码
async function batchGenHandle() {
  const checkRecords = BasicTableApi.grid.getCheckboxRecords();
  if (checkRecords.length <= 0) {
    return;
  }
  const tableNames = checkRecords.map((item) => item.tableName);
  const blobData = await genCode(tableNames);
  downloadByData(blobData, 'ruoyi', 'application/zip');
}
// 根据sql创建表
function createHandle() {
  sqlModalApi.open();
}
// 编辑
const router = useRouter();
function editHandle(gen: Gen) {
  router.push(`/tool/gen/edit-gen/${gen.tableId}`);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="代码生成列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton @click="exportDbHandle" v-access:code="['tool:gen:import']">
            导入
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(BasicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteRoles"
            v-access:code="['tool:gen:remove']"
          >
            删除
          </ElButton>
          <ElButton
            @click="batchGenHandle"
            :disabled="
              !(BasicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            type="warning"
            v-access:code="['tool:gen:code']"
          >
            生成
          </ElButton>
          <ElButton
            type="primary"
            @click="createHandle"
            v-access:role="['admin']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace v-if="row.roleId !== 1">
          <ElButton
            size="small"
            type="primary"
            plain
            @click="editHandle(row)"
            v-access:code="['tool:gen:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['tool:gen:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
          <ElDropdown>
            <ElButton
              type="primary"
              size="small"
              link
              v-access:code="[
                'tool:gen:preview',
                'tool:gen:edit',
                'tool:gen:code',
              ]"
            >
              更多
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <span v-access:code="['tool:gen:preview']">
                  <ElDropdownItem @click="previewHandle(row.tableId)">
                    预览
                  </ElDropdownItem>
                </span>
                <span v-access:code="['tool:gen:edit']">
                  <ElDropdownItem @click="syncHandle(row.tableName)">
                    同步
                  </ElDropdownItem>
                </span>
                <span v-access:code="['tool:gen:code']">
                  <ElDropdownItem @click="genHandle(row.tableName)">
                    生成代码
                  </ElDropdownItem>
                </span>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </ElSpace>
      </template>
    </BasicTable>
    <DbModal @reload="BasicTableApi.query()" />
    <CodeModal />
    <SqlModal @reload="BasicTableApi.query()" />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
