<template>
  <el-dialog v-model="isVisited" title="编辑表格" width="1150px">
    <el-form :model="queryParams" inline label-width="100px" :rules="rules">
      <el-row>
        <el-col :span="7">
          <el-form-item label="表名: " prop="table.tableName">
            <el-text>{{ queryParams.table.tableName }}</el-text>
          </el-form-item>
          <el-form-item label="数据源名称: ">
            <el-text>{{ dataSourceName }}</el-text>
          </el-form-item>
          <el-form-item label="数据源类型: " prop="table.dataSourceType">
            <el-text>{{ queryParams.table.dataSourceType }}</el-text>
          </el-form-item>
          <el-form-item label="角色: " prop="roleIds" style="width: 300px">
            <el-select
              v-model="queryParams.roleIds"
              multiple
              placeholder="请选择角色"
              filterable
              clearable
            >
              <el-option
                v-for="item in roleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="表描述: "
            prop="table.tableComment"
            style="width: 300px"
          >
            <el-input
              v-model="queryParams.table.tableComment"
              :rows="2"
              type="textarea"
              placeholder="请输入表描述"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="17">
          <el-form-item>
            <el-button type="primary" @click="handleAddRelation" :icon="Plus"
              >新增</el-button
            >
            <el-button type="danger" @click="handleDelete" :icon="Delete"
              >删除</el-button
            >
          </el-form-item>
          <div class="table">
            <el-table
              :data="queryParams.relationMappings"
              row-key="mainId"
              v-loading="loading"
              @selection-change="handleSelectionChange"
              :header-cell-style="{ background: '#f5f5f8' }"
              ref="relationalMap"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
                prop="index"
              />
              <el-table-column
                label="序号"
                align="center"
                type="index"
                width="60"
              />
              <el-table-column label="外键" prop="mainKey" align="center">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.mainKey"
                    placeholder="外键"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="item in queryParams.columnList"
                      :key="item.id"
                      :label="item.columnName + ':' + item.columnComment"
                      :value="item.columnName"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联表" prop="childId" align="center">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.childId"
                    placeholder="关联表"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in tableInfoList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联字段" prop="childKey" align="center">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.childKey"
                    placeholder="关联字段"
                    @visible-change="
                      handleVisibleChange(
                        scope.row.childId,
                        scope.$index,
                        $event
                      )
                    "
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in scope.row.childListColumn"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联方式" prop="type" align="center">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.type"
                    multiple
                    placeholder="关联方式"
                    filterable
                    clearable
                  >
                    <el-option label="hasOne" value="1" />
                    <el-option label="hasMany" value="2" />
                    <el-option label="belongsTo" value="3" />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <el-divider content-position="center">ER可视化查询字段信息</el-divider>
      <el-table
        :data="queryParams.columnList"
        row-key="columnId"
        :lazy="true"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f5f8' }"
        style="height: 400px"
        ref="topSearchColumn"
      >
        <el-table-column label="序号" align="center" type="index" width="60" />
        <el-table-column label="列名称" prop="columnName" align="center">
          <template #default="scope">
            <span>{{ scope.row.columnName }}</span>
            <span class="isPk" v-if="scope.row.pk">*</span>
          </template>
        </el-table-column>
        <el-table-column label="列描述" prop="columnComment" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.columnComment"
              placeholder="请输入列描述"
            />
          </template>
        </el-table-column>
        <el-table-column label="列类型" prop="columnType" align="center">
          <template #default="scope">
            <span>{{ scope.row.columnType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否使用" prop="use" align="center">
          <template #default="scope">
            <el-checkbox v-model="scope.row.use" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineExpose, defineProps } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  getTableDetails,
  editTable,
  getAssociationFieldOption,
  getAssociationTableOption,
} from "@/api/custom-query/table";
import { getRoleOption } from "@/api/role/role";

const isVisited = ref(false);
let queryParams = reactive({
  table: {
    dataSourceId: "",
    dataSourceType: "",
    tableName: "",
    tableComment: "",
  },
  roleIds: [],
  relationMappings: [],
  columnList: [],
});
const roleList = ref([]);
const mainIdArray = ref([]);
const loading = ref(true);
const tableInfoList = ref([]);
const rules = reactive({
  roleIds: [
    {
      required: true,
      message: "请选择角色",
      trigger: ["blur", "change"],
      type: "array",
    },
  ],
});

const props = defineProps({
  tableId: {
    type: String,
    default: "",
  },
  dataSourceName: {
    type: String,
    default: "",
  },
});
const restForm = () => {
  queryParams = {
    table: {
      dataSourceId: "",
      dataSourceType: "",
      tableName: "",
      tableComment: "",
    },
    roleIds: [],
    relationMappings: [],
    columnList: [],
  };
};
//获取角色option
const getRole = () => {
  getRoleOption().then((res) => {
    if (res.code === 1000) {
      roleList.value = res.data;
    }
  });
};
//获取关联表option
const getAssociationOption = async (id) => {
  getAssociationTableOption(id).then((res) => {
    if (res.code === 1000) {
      tableInfoList.value = res.data;
    }
  });
};
//获取对应关联表的关联字段
const handleVisibleChange = (id, index, e) => {
  if (e === true) {
    getAssociationFieldOption(id).then((res) => {
      if (res.code === 1000) {
        queryParams.relationMappings[index].childListColumn = res.data;
      }
    });
  }
};
//获取表详情
const getTableDetail = async () => {
  loading.value = true;
  await getTableDetails(props.tableId).then((res) => {
    if (res.code === 1000) {
      loading.value = false;
      if (res.data.roleIds) {
        queryParams.table = res.data.table;
        getAssociationOption(res.data.table.dataSourceId);
      }
      if (res.data.roleIds) {
        queryParams.roleIds = res.data.roleIds;
      }
      if (res.data.relationMappings) {
        queryParams.relationMappings = res.data.relationMappings;
      }
      if (res.data.roleIds) {
        queryParams.columnList = res.data.columnList;
      }
      isVisited.value = true;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
//编辑表格中的selection
const handleSelectionChange = (selection) => {
  console.log("selection", selection);
  mainIdArray.value = selection.map((item) => item.mainId);
};
//新增表之间关联关系
const handleAddRelation = () => {
  let obj = {
    mainId: queryParams.table.tableId,
    childId: null,
    mainKey: null,
    childKey: null,
    type: [],
    childListColumn: [],
  };
  queryParams.relationMappings.push(obj);
};
//删除表之间关联关系
const handleDelete = () => {
  queryParams.relationMappings.forEach((item, index) => {
    mainIdArray.value.forEach((mainId) => {
      if (item.mainId === mainId) {
        queryParams.relationMappings.splice(index, 1);
      }
    });
  });
};
//取消
const handleCancel = () => {
  isVisited.value = false;
};
//提交
const handleSubmit = async () => {
  let params = {
    ...queryParams,
  };
  editTable(params).then((res) => {
    if (res.code === 1000) {
      ElMessage.success(res.msg);
      isVisited.value = false;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const show = () => {
  isVisited.value = true;
  getTableDetail();
  getRole();
};
defineExpose({
  show,
  restForm,
});
</script>

<style scoped>
.isPk {
  /*width: 5px;*/
  /*height: 5px;*/
  /*border-radius: 4px;*/
  /*background-color: red;*/
  position: absolute;
  color: red;
}
</style>
