<template>
  <div class="gen-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search-wrapper">
        <el-card shadow="hover" class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="数据源" prop="dataName">
                  <el-select v-model="queryParams.dataName" filterable clearable placeholder="请选择数据源" style="width: 100%">
                    <el-option key="" label="全部" value="" />
                    <el-option v-for="item in dataNameList" :key="item" :label="item" :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="表名称" prop="tableName">
                  <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="表描述" prop="tableComment">
                  <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间" prop="dateRange">
                  <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" class="search-btn-group">
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">代码生成列表</span>
          </div>
          <div class="header-right">
            <el-button v-hasPermi="['tool:gen:code']" type="primary" size="small" @click="handleGenTable()">生成代码</el-button>
            <el-button v-hasPermi="['tool:gen:import']" type="success" size="small" @click="openImportTable">导入表</el-button>
            <el-button v-hasPermi="['tool:gen:edit']" type="warning" size="small" :disabled="single" @click="handleEditTable()">修改</el-button>
            <el-button v-hasPermi="['tool:gen:remove']" type="danger" size="small" :disabled="multiple" @click="handleDelete()">删除</el-button>
            <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableList" stripe @selection-change="handleSelectionChange" class="gen-table">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据源" align="center" prop="dataName" :show-overflow-tooltip="true" width="120">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">{{ row.dataName || '默认' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="表名称" align="center" prop="tableName" :show-overflow-tooltip="true" min-width="150">
          <template #default="{ row }">
            <span class="table-name">{{ row.tableName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="实体类名" align="center" prop="className" :show-overflow-tooltip="true" min-width="150">
          <template #default="{ row }">
            <el-tag type="info" size="small" effect="plain">{{ row.className }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" width="260" fixed="right">
          <template #default="scope">
            <el-button v-hasPermi="['tool:gen:preview']" link type="primary" size="small" @click="handlePreview(scope.row)">预览</el-button>
            <el-button v-hasPermi="['tool:gen:edit']" link type="primary" size="small" @click="handleEditTable(scope.row)">编辑</el-button>
            <el-button v-hasPermi="['tool:gen:edit']" link type="warning" size="small" @click="handleSynchDb(scope.row)">同步</el-button>
            <el-button v-hasPermi="['tool:gen:code']" link type="success" size="small" @click="handleGenTable(scope.row)">生成</el-button>
            <el-button v-hasPermi="['tool:gen:remove']" link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 预览界面 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="85%" top="5vh" append-to-body class="preview-dialog">
      <el-tabs v-model="preview.activeName" type="border-card" class="preview-tabs">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :key="value"
          :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
        >
          <div class="code-header">
            <span class="file-name">{{ key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm')) }}</span>
            <el-button v-copyText="value" v-copyText:callback="copyTextSuccess" type="primary" size="small">
              复制代码
            </el-button>
          </div>
          <div class="code-content">
            <highlightjs :code="value" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
  </div>
</template>

<script setup name="Gen" lang="ts">
import { delTable, genCode, getDataNames, listTable, previewTable, synchDb } from '@/api/tool/gen';
import { TableQuery, TableVO } from '@/api/tool/gen/types';
import router from '@/router';
import ImportTable from './importTable.vue';

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableList = ref<TableVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const uniqueId = ref('');
const dataNameList = ref<Array<string>>([]);

const queryFormRef = ref<ElFormInstance>();
const importRef = ref<InstanceType<typeof ImportTable>>();

const queryParams = ref<TableQuery>({
  pageNum: 1,
  pageSize: 10,
  tableName: '',
  tableComment: '',
  dataName: ''
});

const preview = ref<{
  data: Record<string, string>;
  activeName: string;
}>({
  data: {},
  activeName: 'domain.java'
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: '代码预览'
});

/** 查询多数据源名称 */
const getDataNameList = async () => {
  const res = await getDataNames();
  dataNameList.value = res.data;
};

/** 查询表集合 */
const getList = async () => {
  loading.value = true;
  const res = await listTable(proxy?.addDateRange(queryParams.value, dateRange.value));
  tableList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 生成代码操作 */
const handleGenTable = async (row?: TableVO) => {
  const tbIds = row?.tableId || ids.value;
  if (tbIds == '') {
    proxy?.$modal.msgError('请选择要生成的数据');
    return;
  }
  if (row?.genType === '1') {
    await genCode(row.tableId);
    proxy?.$modal.msgSuccess('成功生成到自定义路径：' + row.genPath);
  } else {
    proxy?.$download.zip('/tool/gen/batchGenCode?tableIdStr=' + tbIds, 'ruoyi.zip');
  }
};
/** 同步数据库操作 */
const handleSynchDb = async (row: TableVO) => {
  const tableId = row.tableId;
  await proxy?.$modal.confirm('确认要强制同步"' + row.tableName + '"表结构吗？');
  await synchDb(tableId);
  proxy?.$modal.msgSuccess('同步成功');
};
/** 打开导入表弹窗 */
const openImportTable = () => {
  importRef.value?.show(queryParams.value.dataName);
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 预览按钮 */
const handlePreview = async (row: TableVO) => {
  const res = await previewTable(row.tableId);
  preview.value.data = res.data;
  dialog.visible = true;
  preview.value.activeName = 'domain.java';
};
/** 复制代码成功 */
const copyTextSuccess = () => {
  proxy?.$modal.msgSuccess('复制成功');
};
// 多选框选中数据
const handleSelectionChange = (selection: TableVO[]) => {
  ids.value = selection.map((item) => item.tableId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 修改按钮操作 */
const handleEditTable = (row?: TableVO) => {
  const tableId = row?.tableId || ids.value[0];
  if (!tableId) {
    proxy?.$modal.msgError('请选择要修改的数据');
    return;
  }
  router.push({ path: '/tool/gen-edit/index/' + tableId, query: { pageNum: queryParams.value.pageNum } });
};
/** 删除按钮操作 */
const handleDelete = async (row?: TableVO) => {
  const tableIds = row?.tableId || ids.value;
  await proxy?.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？');
  await delTable(tableIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  const time = route.query.t;
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time as string;
    queryParams.value.pageNum = Number(route.query.pageNum);
    dateRange.value = ['', ''];
    queryFormRef.value?.resetFields();
  }
  getList();
  getDataNameList();
});
</script>

<style lang="scss" scoped>
.gen-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-card {
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.search-btn-group {
  text-align: right;
  padding-top: 10px;
}

.table-card {
  :deep(.el-card__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    .header-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-right {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: nowrap;
  }
}

.gen-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  .table-name {
    color: #409eff;
    font-weight: 500;
  }
}

.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-tabs {
  border: none;
  box-shadow: none;

  :deep(.el-tabs__header) {
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
    margin: 0;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }

  :deep(.el-tab-pane) {
    background-color: #282c34;
    min-height: 500px;
  }
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #21252b;
  border-bottom: 1px solid #181a1f;

  .file-name {
    color: #abb2bf;
    font-size: 14px;
    font-weight: 500;
  }
}

.code-content {
  padding: 20px;
  background-color: #282c34;
  overflow-x: auto;

  :deep(pre) {
    margin: 0;
    background-color: transparent !important;
  }

  :deep(code) {
    background-color: transparent !important;
    color: #abb2bf;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.6;
  }
}
</style>
