<template>
  <div class="tool-generator">
    <el-card class="!border-none mb-4" shadow="never" v-if="showSearch">
      <el-form class="mb-[-16px]" ref="queryFormRef" :model="queryParams" inline @submit.prevent="handleQuery">
        <el-form-item class="w-[280px]" label="表名/描述" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入表名或描述" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never" v-loading="isLoading">
      <div class="wd-card-header">
        <el-button v-perms="['tool.generator/import']" type="primary" @click="handleImportOpen">导入数据表</el-button>
        <el-button
          v-perms="['tool.generator/save']"
          type="warning"
          icon="Edit"
          :disabled="multipleSelection.length != 1"
          @click="handleEdit()"
        >
          编辑
        </el-button>
        <el-button
          v-perms="['tool.generator/delete']"
          type="danger"
          icon="Delete"
          :disabled="multipleSelection.length == 0"
          @click="handleDelete()"
        >
          删除
        </el-button>
        <el-button
          v-perms="['tool.generator/generate']"
          type="primary"
          icon="Edit"
          :disabled="multipleSelection.length == 0"
          @click="handleGenerateCode()"
        >
          生成代码
        </el-button>
        <right-toolbar v-model:showSearch="showSearch" v-model:columns="columns" @refresh="getLists"></right-toolbar>
      </div>
      <el-table size="large" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" min-width="60" align="center" v-if="columns.id.visible" />>
        <el-table-column
          prop="name"
          label="表名称"
          align="center"
          min-width="150"
          show-overflow-tooltip
          v-if="columns.name.visible"
        />
        <el-table-column
          prop="comment"
          label="表描述"
          align="center"
          min-width="150"
          show-overflow-tooltip
          v-if="columns.comment.visible"
        />
        <el-table-column prop="engine" label="Engine" align="center" min-width="100" v-if="columns.engine.visible" />
        <el-table-column prop="rows" label="行数" align="center" min-width="100" v-if="columns.rows.visible" />
        <el-table-column
          prop="create_time"
          label="创建时间"
          align="center"
          min-width="170"
          v-if="columns.create_time.visible"
        />
        <el-table-column label="操作" fixed="right" align="center" width="250" v-if="columns.operation.visible">
          <template #default="scope">
            <el-button type="primary" link v-perms="['tool.generator/save']" @click="handleEdit(scope.row.id)">
              编辑
            </el-button>
            <el-button type="primary" link v-perms="['tool.generator/preview']" @click="handlePreview(scope.row.id)">
              预览
            </el-button>
            <el-button
              type="primary"
              link
              v-perms="['tool.generator/generate']"
              @click="handleGenerateCode(scope.row.id)"
            >
              生成代码
            </el-button>
            <el-button type="danger" link v-perms="['tool.generator/delete']" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex mt-4 justify-end">
        <Pagination v-model="queryParams" :total="total" @change="getLists" />
      </div>
    </el-card>
    <import-table ref="importRef" @success="handleQuery" />
    <preview ref="previewRef" />
  </div>
</template>

<script setup lang="ts" name="ToolGenerator">
import { ElLoading, type FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { generatorLists, generatorDelete, generatorCode } from '@/api/tool/generator'
import ImportTable from './components/import.vue'
import Preview from './components/preview.vue'

// 组件参数
const queryFormRef = shallowRef<FormInstance>()
const importRef = shallowRef<InstanceType<typeof ImportTable>>()
const previewRef = shallowRef<InstanceType<typeof Preview>>()
const queryParams = reactive({
  page: 1,
  limit: 10,
  name: '',
  type: 'imported'
})
const multipleSelection = ref<any[]>([])
const total = ref(0)
const isLoading = ref(false)
const tableData = ref<any[]>([])
const showSearch = ref(true)
const columns = ref({
  id: { label: 'ID', visible: true },
  name: { label: '表名称', visible: true },
  comment: { label: '表描述', visible: true },
  engine: { label: 'Engine', visible: true },
  rows: { label: '行数', visible: true },
  create_time: { label: '创建时间', visible: true },
  operation: { label: '操作', visible: true }
})
const router = useRouter()

// 获取列表
const getLists = async () => {
  isLoading.value = true
  generatorLists(queryParams)
    .then((res) => {
      tableData.value = res.data || []
      total.value = res.total || 0
      isLoading.value = false
    })
    .catch(() => {
      isLoading.value = false
    })
}
// 搜索
const handleQuery = async () => {
  queryParams.page = 1
  getLists()
}
// 重置
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}
// 导入
const handleImportOpen = () => {
  importRef.value?.open()
}
// 编辑
const handleEdit = (id?: number) => {
  const editId = id || multipleSelection.value[0]?.id
  if (editId) {
    router.push({ path: '/tool/generator/edit', query: { id: editId } })
  }
}
// 预览
const handlePreview = (id: number) => {
  previewRef.value?.open(id)
}
// 删除
const handleDelete = (id?: number) => {
  const generatorIds = id || multipleSelection.value.map((item) => item.id)
  ElMessageBox.confirm(`确定要删除表ID为 ${generatorIds} 的数据项吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await generatorDelete({ id: generatorIds })
      ElMessage.success('删除成功')
      getLists()
    })
    .catch(() => {})
}
// 生成代码
const handleGenerateCode = (id?: number) => {
  const generatorIds = id || multipleSelection.value.map((item) => item.id)
  ElMessageBox.confirm(`确定要为选中的表生成代码吗？这将覆盖已存在的文件。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const loadingInstance = ElLoading.service({ fullscreen: true, text: '正在生成代码...' })
      try {
        await generatorCode({ id: generatorIds })
        ElMessage.success('代码生成成功！')
      } catch (error) {
        console.error(error)
      } finally {
        loadingInstance.close()
      }
    })
    .catch(() => {})
}

onMounted(() => {
  handleQuery()
})
</script>
