<template>
  <el-card>
    <el-row style="margin-bottom: 20px" justify="start">
      <!-- <el-col :span="4">
        <el-input v-model="searchValue" />
      </el-col>
      <el-col :span="3" style="text-align: center;">
        <el-button type="primary" @click="synchronization">筛选</el-button>
      </el-col> -->
      <el-col :span="2">
        <el-button type="primary" @click="addToTableRelation" style="margin-right: 20px">添加</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="synchronization">同步</el-button>
      </el-col>
    </el-row>
    <div>
      <el-table :data="tableRelationList" ref="multipleTableRef" style="width: 100%; margin-bottom: 20px" row-key="id"
        border v-loading="loading" setScrollLeft="left" @selection-change="handleSelectionChange">
        <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="235" />
        <el-table-column prop="tableDate" label="表头日期字段" align="center" width="155" />
        <el-table-column prop="subTableHeader" label="父表名(-1代表没有)" align="center" width="235" />
        <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="addToTableRelation(scope.row)">添加
            </el-button> -->
            <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">
    <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>
    <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 { ref } from "vue";
import { ElMessageBox, FormInstance, ElMessage } from "element-plus";
import {
  getTableRelation,
  addTableRelation,
  editTableRelation,
  deleteTableRelation,
} from "@/services/api/systemApi/tableRelation/tableRelationAPI";
import {
  postManual,
} from "@/services/api/systemApi/synchronization/synchronizationAPI";

const tableRelationRef = ref<FormInstance>();
const tableRelationList = ref([]);
const multipleTableRef = ref();
const loading = ref(true)
const currentPage = ref(1);
const pageSizes = ref(10);
const total = ref(0);
const modifyId = ref();
const searchValue = ref();
// 多选框
const multipleSelection = ref([] as any);
const tableRelationForm = ref({
  children: [],
  tableName: "",
  tableHeader: "",
  tableDate: "",
  subTableHeader: "-1",
  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 = (data?: any) => {
  // if(data)
  dialogVisible.value = true;
};

const handleSelectionChange = (val: []) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
}

const synchronization = () => {
  if (multipleSelection.value.length != 0) {
    ElMessageBox.confirm("请确认同步?", "同步", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const tableHeaderList = []
        for (const s in multipleSelection.value) {
          tableHeaderList.push(multipleSelection.value[s].tableHeader)
        }
        postManual(tableHeaderList).then((res: any) => {
          if (res.code === 200) {
            multipleTableRef.value!.clearSelection()
            ElMessage({
              type: "success",
              message: "同步成功！",
            });
          }
        })
      })

  }

}

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 = () => {
  tableRelationForm.value = ({
    children: [],
    tableName: "",
    tableHeader: "",
    tableDate: "",
    subTableHeader: "-1",
    primaryKey: "",
    foreignKey: "",
    sortOrder: 1,

  });
  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) => {
  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) {
        console.log(tableRelationForm.value);
        Reflect.deleteProperty(tableRelationForm.value, "children");
        addTableRelation(tableRelationForm.value).then(
          (res: any) => {
            if (res.code !== 200)
              return ElMessage({ type: "error", message: "添加失败！" });
            init();
            formEl?.resetFields()
            ElMessage({ type: "success", message: "添加成功！" });
          }
        );
      } else {
        // 删除children属性
        Reflect.deleteProperty(tableRelationForm.value, "children");
        console.log(tableRelationForm.value);
        editTableRelation({ recordsList: tableRelationForm.value }).then(
          (res: any) => {
            if (res.code !== 200)
              return ElMessage({ type: "error", message: "修改失败！" });
            init();
            formEl?.resetFields()
            ElMessage({ type: "success", message: "修改成功！" });
          }
        );
      }
    } else {
      console.log("校验失败", fields);
    }
  });
  dialogVisible.value = false;
};
</script>

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