<template>
  <el-card>
    <div>
      <el-form-item>
        <el-button type="primary" @click="addToTableRelation">添加</el-button>
      </el-form-item>
    </div>
    <div>
      <el-table
        :data="tableRelationList"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        v-loading="loading"
        setScrollLeft="left"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="tableName" label="表名称" width="230" sortable/>
        <el-table-column prop="tableHeader" label="表名" align="center" width="220"/>
        <el-table-column prop="tableDate" label="表头日期字段" align="center" width="155"/>
        <el-table-column
          prop="subTableHeader"
          label="父表名(-1代表没有)"
          align="center"
          width="155"
        />
        <el-table-column prop="primaryKey" label="主键" align="center" width="220"/>
        <el-table-column prop="foreignKey" label="外键" align="center" width="220"/>
        <el-table-column prop="createTime" label="创建时间" align="center" width="220"/>
        <el-table-column fixed="right" label="操作" align="center" width="155">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="modifyTableRelation(scope.row)"
              >修改
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="cutOutTableRelation(scope.row.id)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSizes"
        :page-sizes="[10, 20, 30]"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 添加对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="表关系管理"
    width="50%"
    :before-close="handleClose"
  >
    <div>
      <el-form
        ref="tableRelationRef"
        :model="tableRelationForm"
        :rules="rules"
        label-width="150px"
        status-icon
      >
        <el-form-item label="表名称：" prop="tableName">
          <el-input
            v-model="tableRelationForm.tableName"
            placeholder="请输入表名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="表名：" prop="tableHeader">
          <el-input
            v-model="tableRelationForm.tableHeader"
            placeholder="请输入表名"
          ></el-input>
        </el-form-item>
        <el-form-item label="表头日期字段：" prop="tableDate">
          <el-input
            v-model="tableRelationForm.tableDate"
            placeholder="请输入日期字段"
          ></el-input>
        </el-form-item>
        <el-form-item label="父表名(-1代表没有)：" prop="subTableHeader">
          <el-input
            v-model="tableRelationForm.subTableHeader"
            placeholder="请输入父表名"
          ></el-input>
        </el-form-item>
        <el-form-item label="主键：" prop="primaryKey">
          <el-input
            v-model="tableRelationForm.primaryKey"
            placeholder="请输入主键"
          ></el-input>
        </el-form-item>
        <el-form-item label="外键：" prop="foreignKey">
          <el-input
            v-model="tableRelationForm.foreignKey"
            placeholder="请输入外键"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sortOrder">
          <el-input
            v-model="tableRelationForm.sortOrder"
            placeholder="请输入排序顺序"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">关闭</el-button>
        <el-button type="primary" @click="onConfirm(tableRelationRef)"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessageBox, FormInstance, ElMessage } from "element-plus";
import {
  getTableRelation,
  addTableRelation,
  editTableRelation,
  deleteTableRelation,
} from "@/services/api/systemApi/tableRelation/tableRelationAPI";

const tableRelationRef = ref<FormInstance>();
const tableRelationList = ref([]);
const loading = ref(true)
const currentPage = ref(1);
const pageSizes = ref(10);
const total = ref(0);
const modifyId = ref();
const tableRelationForm = ref({
  children: [],
  tableName: "",
  tableHeader: "",
  tableDate: "",
  subTableHeader: "",
  primaryKey: "",
  foreignKey: "",
  sortOrder: 1,
});
const rules = ref({});
const dialogVisible = ref(false);
const init = (val?: number, pageSize?: number) => {
  getTableRelation(currentPage.value, pageSizes.value).then((res: any) => {
    tableRelationList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false
    console.log("表关系数据", tableRelationList.value);
  });
};
init();
// 添加按钮
const addToTableRelation = () => {
  dialogVisible.value = true;
};

const handleSizeChange = (val: number) => {
  if (val === pageSizes.value) val = currentPage.value;
  init(val, pageSizes.value);
};
const handleCurrentChange = (val: number) => {
  init(val, pageSizes.value);
};
const handleClose = () => {
  tableRelationRef.value?.resetFields()
  dialogVisible.value = false;
};
const onClose = () => {
  tableRelationRef.value?.resetFields()
  dialogVisible.value = false;
}
const modifyTableRelation = (scope: any) => {
  tableRelationForm.value = scope;
  modifyId.value = scope.id;
  dialogVisible.value = true;
};
// 删除
const cutOutTableRelation = (id: any) => {
  console.log(id);
  ElMessageBox.confirm("请确认删除?", "删除", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteTableRelation(id).then((res: any) => {
        if (res.code === 200) {
          init();
          ElMessage({
            type: "success",
            message: "删除成功！",
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除！",
      });
    });
};
// 添加修改
const onConfirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if (!modifyId.value) {
        Reflect.deleteProperty(tableRelationForm.value, "children");
        addTableRelation({ recordsList: [tableRelationForm.value] }).then(
          (res: any) => {
            if (res.code !== 200)
              return ElMessage({ type: "error", message: "添加失败！" });
            init();
            ElMessage({ type: "success", message: "添加成功！" });
          }
        );
      } else {
        // 删除children属性
        Reflect.deleteProperty(tableRelationForm.value, "children");
        editTableRelation({ recordsList: [tableRelationForm.value] }).then(
          (res: any) => {
            if (res.code !== 200)
              return ElMessage({ type: "error", message: "修改失败！" });
            init();
            ElMessage({ type: "success", message: "修改成功！" });
          }
        );
      }
    } else {
      console.log("校验失败", fields);
    }
  });
  console.log(tableRelationRef.value?.resetFields);
  formEl.resetFields()
  dialogVisible.value = false;
};
</script>

<style lang="scss"></style>
