<template>
  <!-- 面包屑 -->
  <el-breadcrumb>
    <el-breadcrumb-item>生成代码</el-breadcrumb-item>
    <el-breadcrumb-item to="/news/list">生成代码列表</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="app-container">
    <el-form ref="codeform" :inline="true" :model="queryParams">
      <el-form-item label="表名" prop="tableName">
        <el-input v-model="queryParams.tableName" clearable placeholder="输入要查询的表名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList()">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="info" plain icon="upload" @click="openImportTable">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" plain icon="delete" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success">
          <a href="https://drive.aerwen.net/d/aerwen/%E9%A1%B9%E7%9B%AE/AerwenTool.zip" target="_blank"
            style="text-decoration:none;color:white;">下载一键建表工具</a>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success">
          <a href="https://space.bilibili.com/270021386/channel/series" target="_blank"
            style="text-decoration:none;color:white;">使用教程</a>
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain @click="handleCreateTable">一键生成表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleDeleteTable">一键删除表</el-button>
      </el-col> -->
    </el-row>
    <br>
    <el-table ref="gridtable" v-loading="tableloading" :data="tableList" border @selection-change="handleSelectionChange"
      highlight-current-row height="480px">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column prop="tableId" label="id" width="70" sortable="" />
      <el-table-column prop="tableName" label="表名" width="110" :show-overflow-tooltip="true" />
      <el-table-column prop="tableComment" label="表描述" :show-overflow-tooltip="true" width="120" />
      <el-table-column prop="className" label="实体" :show-overflow-tooltip="true" />
      <el-table-column prop="create_time" label="创建时间" sortable />
      <el-table-column prop="update_time" label="更新时间" sortable />
      <el-table-column label="操作" align="center" width="320">
        <template #default="scope">

          <el-link type="primary" icon="edit" :underline="false" class="ml10" @click="handleEditTable(scope.row)">
            编辑
          </el-link>
          <el-link type="primary" icon="delete" :underline="false" class="ml10" @click="handleDelete(scope.row)">
            删除
          </el-link>
          <el-link type="primary" icon="download" :underline="false" class="ml10" @click="handleGenTable(scope.row)">
            生成代码
          </el-link>
          <el-link type="primary" icon="download" :underline="false" class="ml10" @click="handleGenTableApi(scope.row)">
            生成Api接口
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:page="queryParams.page" v-model:limit="queryParams.limit" v-model:total="total"
      @pagination="getList" />

    <import-table ref="importRef" @ok="getList" />
  </div>
</template>

<script setup name="gen">
// import { codeGenerator, codeGeneratorApi, listTable, delTable, previewTable, synchDb } from '@/api/tool/gen'
import { getGenTablesList, delTable, genCode, createTable, deleteTable, codeGeneratorApi } from '~/service/Gen';
import { useRouter } from 'vue-router'
import importTable from './importTable.vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/dark.css' // 这里有多个样式，自己可以根据需要切换
import { useClipboard } from '@vueuse/core'
import { ref } from 'vue'
// const route = useRoute()
const router = useRouter()
// const { proxy } = getCurrentInstance()

const tableList = ref([])
const tableloading = ref(true)
const tableIds = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])
const showGenerate = ref(false)
// 选中行的表
const currentSelected = ref({})

let queryParams = ref({
  page: 1,
  limit: 10,
  tableName: undefined,
})

const importRef = ref(null);


/** 查询表集合 */
function getList() {
  tableloading.value = true
  getGenTablesList(queryParams.value).then((response) => {
    tableList.value = response.data
    total.value = response.count
    tableloading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1
  getList()
}
/** 生成代码操作 */
function handleGenTable(row) {
  currentSelected.value = row
  if (!currentSelected.value) {
    ElMessage({
      message: "请先选择要生成代码的数据表...",
      type: 'info',
    })
    return false
  }

  ElMessage({
    message: "正在生成代码...",
    type: 'info',
  })

  genCode({
    tableId: currentSelected.value.tableId,
  })
    .then((res) => {
      const { data } = res
      showGenerate.value = false
      ElMessage({
        message: "生成完成",
        type: 'success',
      })
    })
    .catch((erre) => {
    })

}
/** 生成Api代码操作 */
function handleGenTableApi(row) {
  currentSelected.value = row
  if (!currentSelected.value) {
    ElMessage({
      message: "请先选择要生成代码的数据表",
      type: 'error',
    })
    return false
  }
  ElMessage({
    message: "正在生成代码...",
    type: 'info',
  })

  codeGeneratorApi({
    tableId: currentSelected.value.tableId,
  })
    .then((res) => {
      const { data } = res
      showGenerate.value = false
      ElMessage({
        message: "生成完成",
        type: 'success',
      })
    })
    .catch((erre) => {
    })
}

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

// 多选框选中数据
function handleSelectionChange(selection) {
  tableIds.value = selection.map((item) => item.tableId)
  multiple.value = !selection.length
}
/** 编辑表格 */
function handleEditTable(row) {
  queryParams.value.tableName = row.tableName
  getList()

  router.push({
    path: '/gen/editTable',
    query: { tableId: row.tableId },
  })
}
/** 一键生成操作 */
function handleCreateTable(row) {
  const Ids = row.tableId
  createTable({ tableId: Ids }).then((res) => {
    if (res.code == 0) {
      ElMessage({
        message: "生成表成功",
        type: 'success',
      })
      handleQuery()
    }
  })
}
/** 一键删除操作 */
function handleDeleteTable(row) {
  const Ids = row.tableId
  deleteTable({ tableId: Ids }).then((res) => {
    if (res.code == 0) {
      ElMessage({
        message: "删除表成功",
        type: 'success',
      })
      handleQuery()
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const Ids = row.tableId || tableIds.value
  console.log(Ids);
  // const Ids = {tableId: row.map(v => v.tableId).join()}
  ElMessageBox.alert('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      delTable({ tableId: Ids }).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "删除成功",
            type: 'success',
          })
          handleQuery()
        }
      })
    })
}

/** 高亮显示 */
function highlightedCode(code, key) {
  // var language = key.substring(key.lastIndexOf(".") , key.length)
  const result = hljs.highlightAuto(code || '')
  return result.value || '&nbsp;'
}

const { copy, isSupported } = useClipboard()
function onCopy(input) {
  if (isSupported) {
    copy(input)
    proxy.$modal.msgSuccess('复制成功！')
  } else {
    ElMessage({
      message: "当前浏览器不支持",
      type: 'info',
    })
  }
}
getList()
</script>
<style>
.btn-copy {
  position: absolute;
  right: 0;
  top: -5px;
}
</style>
