<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="表名称" prop="tableName">
              <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="表描述" prop="tableComment">
              <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleAdd" v-hasPermi="['ai:aiSqlTable:add']">导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['ai:aiSqlTable:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Refresh" @click="handleRefresh" v-hasPermi="['ai:aiSqlTable:refresh']">
              刷新
            </el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="aiSqlTableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="编号" align="center" prop="tableId" v-if="columns[0].visible"/>
        <el-table-column label="数据源" align="center" prop="dataName" />
        <el-table-column label="表名称" align="center" prop="tableName" v-if="columns[2].visible"/>
        <el-table-column label="表描述" align="center" prop="tableComment" v-if="columns[3].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['ai:aiSqlTable:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改AI生成sql信息对话框 -->

    <import-table ref="importRef" @ok="handleQuery"/>

  </div>
</template>

<script setup name="AiSqlTable" lang="ts">
import {
  listAiSqlTable,
  getAiSqlTable,
  deleteAiSqlTable,
  addAiSqlTable,
  updateAiSqlTable,
  refreshCache
} from '@/api/ai/base/aiSqlTable';
import {AiSqlTableVO, AiSqlTableQuery, AiSqlTableForm} from '@/api/ai/base/aiSqlTable/types';
import ImportTable from '../common/importTable.vue';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

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

const aiSqlTableList = ref<AiSqlTableVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const selectedRows = ref<AiSqlTableVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const aiSqlTableFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  {key: 0, label: `编号`, visible: true},
  {key: 1, label: `租户ID`, visible: true},
  {key: 2, label: `表名称`, visible: true},
  {key: 3, label: `表描述`, visible: true},
  {key: 4, label: `关联子表的表名`, visible: true},
  {key: 5, label: `子表关联的外键名`, visible: true},
  {key: 6, label: `创建部门`, visible: true},
  {key: 7, label: `创建者`, visible: true},
  {key: 8, label: `创建时间`, visible: true},
  {key: 9, label: `更新者`, visible: true},
  {key: 10, label: `更新时间`, visible: true},
  {key: 11, label: `删除标志`, visible: true},
]);

const initFormData: AiSqlTableForm = {
  tableId: undefined,
  tableName: undefined,
  tableComment: undefined,
  subTableName: undefined,
  subTableFkName: undefined,
}
const data = reactive<PageData<AiSqlTableForm, AiSqlTableQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tableId: undefined,
    tableName: undefined,
    tableComment: undefined,
    subTableName: undefined,
    subTableFkName: undefined,
    params: {}
  },
  rules: {
    tableId: [
      {required: true, message: "编号不能为空", trigger: "blur"}
    ],
    tableName: [
      {required: true, message: "表名称不能为空", trigger: "blur"}
    ],
    tableComment: [
      {required: true, message: "表描述不能为空", trigger: "blur"}
    ],
    subTableName: [
      {required: true, message: "关联子表的表名不能为空", trigger: "blur"}
    ],
    subTableFkName: [
      {required: true, message: "子表关联的外键名不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询AI生成sql信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiSqlTable(queryParams.value);
  aiSqlTableList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  aiSqlTableFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AiSqlTableVO[]) => {
  ids.value = selection.map(item => item.tableId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectedRows.value = selection;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加AI生成sql信息";
  importRef.value?.show(queryParams.value.dataName);

}

/** 修改按钮操作 */
const handleUpdate = async (row?: AiSqlTableVO) => {
  reset();
  const _tableId = row?.tableId || ids.value[0]
  const res = await getAiSqlTable(_tableId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改AI生成sql信息";
}

/** 提交按钮 */
const submitForm = () => {
  aiSqlTableFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.tableId) {
        await updateAiSqlTable(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addAiSqlTable(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AiSqlTableVO) => {
  const _tableIds = row?.tableId || ids.value;
  let toDeletedRows = [];
  if (row) {
    toDeletedRows.push(row);
  } else {
    toDeletedRows = selectedRows.value;
  }

  await proxy?.$modal.confirm('是否确认删除AI生成sql信息编号为"' + _tableIds + '"的数据项？').finally(() => loading.value = false);
  await deleteAiSqlTable(toDeletedRows);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('ai/aiSqlTable/export', {
    ...queryParams.value
  }, `aiSqlTable_${new Date().getTime()}.xlsx`)
}

/** 刷新按钮操作 */
const handleRefresh = async () => {
  await refreshCache();
  proxy?.$modal.msgSuccess("刷新成功");
}


onMounted(() => {
  getList();
});
</script>
