<template>
  <div class="app-container">
    <basic-table
      ref="tableRef"
      :columns="columns"
      :search-columns="searchColumns"
      :query="queryList"
      row-key="tableId"
      show-index
      :default-sort="defaultSort"
      :default-params="defaultParams"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <template #toolbar="{ selection, ids }">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Download"
            :disabled="!selection.length"
            @click="handleGenTable()"
            v-hasPermi="['tool:gen:code']"
          >生成</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="openCreateTable"
            v-hasRole="['admin']"
          >创建</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="openImportTable"
            v-hasPermi="['tool:gen:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="selection.length !== 1"
            @click="handleEditTable(selection[0])"
            v-hasPermi="['tool:gen:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="!selection.length"
            @click="handleDelete(ids)"
            v-hasPermi="['tool:gen:remove']"
          >删除</el-button>
        </el-col>
      </template>

      <template #col-action="{ row }">
        <el-tooltip content="预览" placement="top">
          <el-button link type="primary" icon="View" @click="handlePreview(row)" v-hasPermi="['tool:gen:preview']"></el-button>
        </el-tooltip>
        <el-tooltip content="编辑" placement="top">
          <el-button link type="primary" icon="Edit" @click="handleEditTable(row)" v-hasPermi="['tool:gen:edit']"></el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button link type="primary" icon="Delete" @click="handleDelete(row.tableId)" v-hasPermi="['tool:gen:remove']"></el-button>
        </el-tooltip>
        <el-tooltip content="同步" placement="top">
          <el-button link type="primary" icon="Refresh" @click="handleSynchDb(row)" v-hasPermi="['tool:gen:edit']"></el-button>
        </el-tooltip>
        <el-tooltip content="生成代码" placement="top">
          <el-button link type="primary" icon="Download" @click="handleGenTable(row)" v-hasPermi="['tool:gen:code']"></el-button>
        </el-tooltip>
      </template>
    </basic-table>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="value"
        >
          <el-link underline="never" icon="DocumentCopy" v-copyText="value" v-copyText:callback="copyTextSuccess" style="float:right">&nbsp;复制</el-link>
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
    <create-table ref="createRef" @ok="handleQuery" />
  </div>
</template>

<script setup name="Gen">
import { listTable, previewTable, delTable, genCode, synchDb } from "@/api/tool/gen"
import importTable from "./importTable"
import createTable from "./createTable"

const route = useRoute()
const { proxy } = getCurrentInstance()

const tableRef = ref()
const importRef = ref()
const createRef = ref()
const uniqueId = ref("")
const selectedTableNames = ref([])

// 默认排序
const defaultSort = { prop: "createTime", order: "descending" }
const defaultParams = {
  orderByColumn: "createTime",
  isAsc: "descending"
}

const preview = reactive({
  open: false,
  title: "代码预览",
  data: {},
  activeName: "domain.java"
})

// 搜索项配置
const searchColumns = [
  { label: "表名称", prop: "tableName", component: "input", placeholder: "请输入表名称", width: "200px" },
  { label: "表描述", prop: "tableComment", component: "input", placeholder: "请输入表描述", width: "200px" },
  { label: "创建时间", prop: "dateRange", component: "daterange", width: "308px" }
]

// 表格列配置
const columns = [
  { label: "表名称", prop: "tableName", align: "center" },
  { label: "表描述", prop: "tableComment", align: "center" },
  { label: "实体", prop: "className", align: "center" },
  { label: "创建时间", prop: "createTime", align: "center", width: 160, sortable: "custom" },
  { label: "更新时间", prop: "updateTime", align: "center", width: 160, sortable: "custom" },
  { label: "操作", prop: "action", align: "center", width: 330, showInToolbar: false }
]

// 查询函数
function queryList(params) {
  const p = proxy.addDateRange({ ...params }, params.dateRange)
  delete p.dateRange
  return listTable(p)
}

/** 搜索按钮操作（供子组件 @ok 回调） */
function handleQuery() {
  tableRef.value.reload()
}

/** 排序触发事件 */
function handleSortChange(column) {
  tableRef.value.setQueryParams({ orderByColumn: column.prop, isAsc: column.order })
  tableRef.value.reload()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectedTableNames.value = selection.map(item => item.tableName)
}

// keep-alive 页面重新激活时，从路由参数恢复分页并重置搜索
onActivated(() => {
  const time = route.query.t
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time
    tableRef.value.getSearchFormRef()?.resetFields()
    tableRef.value.setQueryParams({ pageNum: Number(route.query.pageNum) || 1 })
    tableRef.value.refresh()
  }
})

/** 生成代码操作 */
function handleGenTable(row) {
  const tbNames = row?.tableName || selectedTableNames.value
  if (!tbNames || (Array.isArray(tbNames) && tbNames.length === 0)) {
    proxy.$modal.msgError("请选择要生成的数据")
    return
  }
  if (row?.genType === "1") {
    genCode(row.tableName).then(response => {
      proxy.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath)
    })
  } else {
    const zipName = Array.isArray(tbNames) ? "ruoyi.zip" : tbNames + ".zip"
    proxy.$download.zip("/tool/gen/batchGenCode?tables=" + tbNames, zipName)
  }
}

/** 同步数据库操作 */
function handleSynchDb(row) {
  const tableName = row.tableName
  proxy.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
    return synchDb(tableName)
  }).then(() => {
    proxy.$modal.msgSuccess("同步成功")
  }).catch(() => {})
}

/** 打开导入表弹窗 */
function openImportTable() {
  importRef.value.show()
}

/** 打开创建表弹窗 */
function openCreateTable() {
  createRef.value.show()
}

/** 预览按钮 */
function handlePreview(row) {
  previewTable(row.tableId).then(response => {
    preview.data = response.data
    preview.open = true
    preview.activeName = "domain.java"
  })
}

/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功")
}

/** 修改按钮操作 */
function handleEditTable(row) {
  const params = { pageNum: tableRef.value.getQueryParams().pageNum }
  proxy.$tab.openPage("修改[" + row.tableName + "]生成配置", '/tool/gen-edit/index/' + row.tableId, params)
}

/** 删除按钮操作 */
function handleDelete(tableIds) {
  proxy.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
    return delTable(tableIds)
  }).then(() => {
    tableRef.value.refresh()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
</script>
