<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="表格组名" prop="dtName">
        <el-input
          v-model="queryParams.dtName"
          placeholder="请输入表格组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="DeleteTableGroup"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain size="mini" @click="handlePreview"
          >动态页面</el-button
        >
      </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableGroupList"
      ref="tableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表格主键" align="center" prop="id" />
      <el-table-column label="表格组名" align="center" prop="groupName" />
      <el-table-column label="描述" align="center" prop="groupDescription" />
      <el-table-column label="表格数" align="center" prop="groupCount" />

      <el-table-column label="成员表格" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p v-for="(item, index) in scope.row.groupTableInfo" :key="index">
              {{ index == 0 ? "" : item.tablename }}
            </p>

            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{
                scope.row.groupTableInfo[0].tablename
              }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="UpdateTableGroup(scope.row)"
                  >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="DeleteTableGroup(scope.row)"
                  >删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getTableList"
    />

    <!-- 新增联动表格组弹窗 -->
    <el-dialog
      :title="groupTitle ? '新增动态表格组' : '修改动态表格组'"
      :visible.sync="isShowTable"
    >
      <div class="dialog_wrap">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="addOneTable"
          class="mb10"
          >新增</el-button
        >
        <el-form
          :model="groupForm"
          :rules="grouprules"
          ref="groupForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="菜单名称" prop="groupName">
            <el-input
              v-model="groupForm.groupName"
              placeholder="请输入菜单名称"
              @input="iptChange()"
            ></el-input>
          </el-form-item>
          <el-form-item label="菜单描述" prop="groupDescription">
            <el-input
              v-model="groupForm.groupDescription"
              placeholder="请输入菜单描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="菜单路由" prop="routePath">
            <div class="treeselect">
              <treeselect
                :append-to-body="true"
                v-model="groupForm.routePath"
                :options="menus"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="请选择父级路由"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-table
              :data="tableDataList"
              border
              stripe
              @selection-change="handleSelectionChange"
            >
              <el-table-column label="序号" type="index" />
              <el-table-column label="表格标题" prop="dtName" />
              <el-table-column
                label="表格名称"
                prop="dtTableName"
              ></el-table-column>
              <el-table-column label="表格主键" prop="primaryKey">
                <!-- <template slot-scope="scope" v-for="item in conditionDefaultValueMap ">
              {{ item }}
            </template> -->
              </el-table-column>

              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-dropdown>
                    <el-button type="warning" plain size="small">
                      处理<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-edit"
                          @click="relateOne(scope.row, scope.$index)"
                          >修改
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-delete"
                          @click="handleDelete(scope.row)"
                          >删除
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item class="btn">
            <el-button @click="cancelGroup">取消</el-button>
            <el-button type="primary" @click="addTableGroup('groupForm')"
              >确认</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 编辑某一条表格数据弹窗 -->
    <el-dialog
      :title="relateTitle ? '添加关联表格' : '修改关联表格'"
      :visible.sync="isShowForm"
    >
      <div class="formWrap">
        <el-form
          :rules="tableItemRules"
          ref="tableItemForm"
          style="max-width: 750px; width: 1000px"
          :model="tableItemForm"
          label-width="100px"
        >
          <el-form-item label="表格标题:" prop="title">
            <el-input
              v-model="tableItemForm.title"
              style="max-width: 221px"
              @change="iptChange()"
              @input="iptChange()"
            ></el-input>
          </el-form-item>
          <el-form-item label="表格名称:" prop="tableName">
            <el-select
              v-model="tableItemForm.tableName"
              @change="getList()"
              placeholder="请选择表格名称"
              @input="iptChange()"
            >
              <el-option
                v-for="item in tableList"
                :key="item.tableName"
                :label="item.tableComment"
                :value="item.tableName"
              >
                <span style="float: left">{{ item.tableComment }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.tableName
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表格主键:" prop="selectFields">
            <el-select
              v-model="tableItemForm.selectFields"
              placeholder="请选择表格主键"
              @input="iptChange()"
            >
              <el-option
                v-for="item in tableFieldList"
                :key="item.fieldName"
                :label="item.fieldDescription"
                :value="item.fieldName"
              >
                <span style="float: left">{{ item.fieldDescription }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.fieldName
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间格式" prop="timeFormate">
            <el-select
              v-model="tableItemForm.timeFormate"
              placeholder="请选择时间格式"
              @input="iptChange()"
            >
              <el-option
                v-for="val in dict.type.sys_time_format"
                :key="val.value"
                :label="val.label"
                :value="val.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序依赖字段">
            <el-select
              v-model="tableItemForm.orderByColumn"
              placeholder="请选择排序依赖"
              @input="iptChange()"
            >
              <el-option
                v-for="val in orderByFieldList"
                :key="val.fieldName"
                :label="val.fieldDescription"
                :value="val.tableName + '.' + val.fieldName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序方式" v-show="tableItemForm.orderByColumn">
            <el-radio v-model="tableItemForm.isAsc" :label="false"
              >升序</el-radio
            >
            <el-radio v-model="tableItemForm.isAsc" :label="true"
              >降序</el-radio
            >
          </el-form-item>
          <el-form-item label="展示字段:" prop="FieldList">
            <el-table
              :data="tableFieldList"
              border
              ref="dragTable"
              row-key="id"
              max-height="500px"
              class="tablefiled"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                class-name="allowDrag"
              >
              </el-table-column>
              <el-table-column
                prop="fieldName"
                label="数据字段"
              ></el-table-column>
              <el-table-column prop="fieldDescription" label="字段描述">
                <template slot-scope="scope">
                  <input
                    :class="{
                      isNullDesc:
                        scope.row.fieldDescription == '' &&
                        scope.row.isShow &&
                        isInputInvalid
                          ? true
                          : false,
                      ipt: true,
                    }"
                    v-model="scope.row.fieldDescription"
                  />
                </template>
              </el-table-column>
              <el-table-column width="95px" prop="relationTable" label="关联表">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.relationTable"
                    :disabled="
                      !scope.row.relationTableList ||
                      !scope.row.relationTableList.length
                    "
                    placeholder="请选择关联的表"
                    clearable
                    filterable
                    @change="ralationTableChange(scope.row)"
                  >
                    <el-option
                      v-for="(item, index) in scope.row.relationTableList"
                      :key="index"
                      :label="item.tableComment"
                      :value="item.tableName"
                    >
                      <span style="float: left">{{ item.tableComment }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.tableName }}</span
                      >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                width="95px"
                prop="relationFieldName"
                label="关联条件字段"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.relationFieldName"
                    @change="relationFieldChange(scope.row)"
                    :disabled="!scope.row.disableRelaFieldName"
                    placeholder="关联字段"
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in scope.row.relaFieldNameList"
                      :key="index"
                      :label="item.fieldDescription"
                      :value="item.fieldName"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                width="95px"
                prop="relationType"
                label="关联方式"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.relationType"
                    placeholder="请选择关联方式"
                    :disabled="!scope.row.disableRelaType"
                    @change="relationTypeChangeHandler(scope.row)"
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in relaTypeList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="isShow" label="是否显示">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.isShow"> </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="isSearch" label="是否包含查询">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isSearch"
                    @change="isSearchChange($event, scope.row, scope.$index)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item class="btn">
            <el-button @click="cancelAddHandler">取消</el-button>
            <el-button
              type="primary"
              @click="confirmAddHandler('tableItemForm')"
              >确认</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 是否包含查询字段依赖值对话框 -->
    <div class="isSearch">
      <el-dialog title="包含查询依赖值" :visible.sync="isSearchDialog">
        <el-select v-model="relyOption" placeholder="请选择依赖方式">
          <el-option
            v-for="item in relyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          v-show="relyOption === '0'"
          v-model="conditionDefaultValueMap"
          placeholder="请输入依赖值"
        ></el-input>

        <el-select
          v-show="relyOption === '1'"
          v-model="conditionDefaultValueMap"
          placeholder="请选择依赖字段"
        >
          <el-option
            v-for="item in relyFileds.tableFieldList"
            :key="item.fieldName"
            :label="item.fieldDescription"
            :value="item.fieldName"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isSearchCancel">取 消</el-button>
          <el-button type="primary" @click="isSearchBtn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { listTable, removeTableList } from "@/api/dragform/tableList";
import {
  getFormName,
  getListName,
  dragTablePreview,
} from "@/api/dragform/form.js";
import { delMenu } from "@/api/system/menu";
import { getMenuList, addMenu, getRouters } from "@/api/menu.js";
import { getParticMenu, updateMenu } from "@/api/system/menu.js";
import {
  addGroup,
  listGroup,
  getTable,
  delGroup,
  updataGroup,
} from "@/api/relateTable/index.js";
import { mapGetters, mapState } from "vuex";
import { v4 as uuidv4 } from "uuid";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import json from "highlight.js/lib/languages/json";
import { getTableInfo } from "@/api/system/table.js";

export default {
  name: "relateTable",
  components: { Treeselect },
  dicts: ["sys_time_format", "table_statistic_type"],
  data() {
    return {
      editIndex: 0,
      isInputInvalid: false,

      // 包含查询依赖字段dialog
      isSearchDialog: false,
      isSearchIndex: null,
      // 依赖方式
      relyOption: null,
      relyOptions: [
        {
          value: "0",
          label: "自定义依赖值",
        },
        {
          value: "1",
          label: "依赖其他字段",
        },
      ],
      // 依赖值
      conditionDefaultValueMap: "",
      // 上个表格名称及字段
      relyFileds: {},
      formdata: {
        conditionDefaultValueMap: {},
      },
      conditionDefault: {},
      addDragData: [],
      groupList: [],
      menus: [], //路由列表数据
      // 添加关联表格校验规则
      tableItemRules: {
        // title:[{ required: true, message: '请输入表格标题', trigger: 'blur' }],
        // tableName:[{ required: true, message: '请选择表格名称', trigger: 'change' }],
        // selectFields: [{ required: true, message: '请选择关联字段', trigger: 'change' }],
      },
      groupForm: {
        groupName: "",
        groupDescription: "",
        routePath: undefined,
      },
      grouprules: {
        groupName: [
          { required: true, message: "请输入表格组名", trigger: "blur" },
        ],
        groupDescription: [
          { required: true, message: "请输入表格描述", trigger: "blur" },
        ],
        routePath: [
          { required: true, message: "请选择路由", trigger: "change" },
        ],
      },
      menuOrderNum: 0,
      // 关联方式
      relaTypeList: [
        {
          label: "等值连接",
          value: "INNER JOIN",
        },
        {
          label: "左连接",
          value: "LEFT JOIN",
        },
        {
          label: "右连接",
          value: "RIGHT JOIN",
        },
      ],
      searchFieldList: [],
      // 依赖字段
      relyFiledsList: [],
      // 修改row
      updataGroupRow: {},
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      menuIds: [],
      // 选中数组(包含所有数据)
      selection: [],
      Keys: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tableList: [], //所有表格列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        groupType: 0,
        pageNum: 1,
        pageSize: 10,
        dtName: null,
        dtNickname: null,
        tableKey: null,
        sqlKey: null,
        dtTableName: null,
        dtNotes: null,
        dtColumnName: null,
        timeFormat: null,
        spare: null,
        spare1: null,
        isSelection: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      // dialog弹窗数据
      isShowTable: false,
      isShowForm: false,
      // 新增关联表数据
      tableDataList: [],

      tableFieldList: [], // 当前表格字段数据
      tableName: "", // 当前表名称
      selectFields: "", //关联字段
      relateTitle: true,
      relateTableName: "", //关联表名称
      relateFields: "", //子集关联字段
      relateFieldList: [], //子集关联字段数据
      groupTitle: true,
      tableItemForm: {
        tId: "",
        rowId: "",
        title: "",
        tableName: "",
        selectFields: "",
        isAsc: false,
        timeFormate: "",
        orderByColumn: "",
      },
      tableGroupList: [],
      // 成员表格提示
      tableKeyContent: "",
      groupsMenuId: "",
      // 修改表格时的menuId
      menuId: "",
      // 修改是表格的id
      groupId: "",
      serachIndex: "",
      //修改数据回显
      echogroup: {},
    };
  },
  async created() {
    this.getTableList();
  },
  async mounted() {
    await this.getMenuList();
  },
  computed: {
    selectRelate() {
      if (this.tableItemForm.tableName == "") return;
      return this.tableList.filter(
        (item) => item.tableName !== this.tableItemForm.tableName
      );
    },
    dataArr() {
      return this.tableFieldList.filter((item) => item.isShow);
    },
    ...mapGetters(["addRoutes"]),
    ...mapState({
      databaseName: (state) => state.user.dataSource.databaseName,
      databaseType: (state) => state.user.dataSource.databaseType,
      username: (state) => state.user.dataSource.username,
      tenantId: (state) => state.user.tenant.tenantId,
    }),
    orderByFieldList() {
      return this.tableFieldList;
    },
  },
  watch: {
    "tableItemForm.tableName": function (val) {
      if (val) {
        this.relationTableList = this.tableList
          .filter((item) => item.tableName != val)
          .map((item) => {
            return {
              tableName: item.tableName,
              tableComment: item.tableComment,
            };
          });
      } else {
        this.relaiptChangetableItemRulestionTableList = [];
      }
    },
    "groupForm.routePath"(nval, oval) {
      let targetMenu = this.getTargetMenu(this.menus);
      this.menuOrderNum = targetMenu.children ? targetMenu.children.length : 0;
    },
  },
  methods: {
    iptChange() {
      this.$forceUpdate(); //强制刷新
    },
    async getTableList() {
      let res = await listGroup(this.queryParams);
      this.total = res.total;
      let info = [];
      res.rows.forEach((item) => {
        item.groupCount = JSON.parse(item.groupTableInfo).length;

        info = JSON.parse(item.groupTableInfo);
        this.groupsMenuId = info[0].menuId;
        item.menuId = info[0].menuId;
        item.groupTableInfo = info;
      });
      // console.log(info);
      this.tableGroupList = res.rows;
      // console.log(this.tableGroupList)
    },
    // 是否包含查询switch
    isSearchChange(status, row, index) {
      this.serachIndex = index;
      this.isSearchIndex = row.tableName + "." + row.fieldName;
      if (!status) {
        delete this.conditionDefault[this.isSearchIndex];
      }
      this.isSearchDialog = status;
      console.log(111, this.relyFileds);
      this.conditionDefaultValueMap = "";
    },
    // 添加依赖字段取消
    isSearchCancel() {
      this.relyOption = null;
      this.conditionDefaultValueMap = "";
      this.isSearchDialog = false;
      this.tableFieldList[this.serachIndex].isSearch = false;
    },
    isSearchBtn() {
      if (this.relyOption == 0) {
        this.conditionDefault[this.isSearchIndex] =
          this.conditionDefaultValueMap;
      } else {
        if (this.tableDataList.length !== 0) {
          this.relyFileds.tableName =
            this.tableDataList[this.editIndex - 1]?.dtTableName;
        }
        this.conditionDefault[this.isSearchIndex] =
          "#{" +
          this.relyFileds.tableName +
          "." +
          this.conditionDefaultValueMap;
      }

      this.isSearchDialog = false;
      this.conditionDefaultValueMap = "";
      this.relyFileds.tableName = "";
    },
    // 获取路由表单数据
    async getMenuList() {
      let res = await listGroup();
      this.menus = this.handleTree(res.data, "menuId");
    },
    // 递归拼接查询语句
    getSQLString(tableFieldList, fieldArr, tableArr, sqlType = "mysql") {
      let prefix = "{DBNAME}.";
      let asOrSpace = sqlType == "oracle" ? " " : " AS ";
      for (let i = 0; i < tableFieldList.length; i++) {
        let temp = tableFieldList[i];
        if (temp.isShow) {
          let tempArr = prefix + temp.tableName + "." + temp.fieldName;
          if (temp.isChildren) {
            tempArr += asOrSpace + temp.tableName + "_" + temp.fieldName;
          }
          fieldArr.push(tempArr);
        }
        if (temp.relationTable && temp.relationFieldName && temp.relationType) {
          let isNeedUsername = sqlType == "oracle" ? this.username + "." : "";
          tableArr.push(
            temp.relationType +
              " " +
              isNeedUsername +
              prefix +
              temp.relationTable +
              asOrSpace +
              temp.relationTable +
              " ON " +
              prefix +
              temp.relationTable +
              "." +
              temp.relationFieldName +
              " = " +
              prefix +
              temp.tableName +
              "." +
              temp.fieldName
          );
        }
      }
      // 如果主键不包含显示,则添加至sql语句中
      let isNotInclude = this.tableFieldList.find(
        (val) => !val.isShow && val.fieldName == this.tableItemForm.selectFields
      );
      if (isNotInclude) {
        fieldArr.push(
          prefix + isNotInclude.tableName + "." + isNotInclude.fieldName
        );
      }
    },
    // 拼接查询sql语句
    getSQLStr() {
      let prefix = "{DBNAME}.";
      let sqlType = this.databaseType; //数据库类型
      // let sqlType = "oracle";
      let sql = "";
      // mysql
      sql += "SELECT ";
      let fieldNameArr = [],
        relaTypeArr = [];
      this.getSQLString(
        this.tableFieldList,
        fieldNameArr,
        relaTypeArr,
        sqlType
      );
      let isNeedUsername = sqlType == "oracle" ? this.username + "." : "";
      let asOrSpace = sqlType == "oracle" ? " " : " AS ";
      sql +=
        fieldNameArr.join(",") +
        " FROM " +
        isNeedUsername +
        prefix +
        this.tableItemForm.tableName +
        asOrSpace +
        this.tableItemForm.tableName;
      if (relaTypeArr.length) {
        sql += " " + relaTypeArr.join(" ");
      }
      return sql;
    },
    /** 查询列表 */
    getList(queryParams) {
      if (!this.tableItemForm.tableName) return;
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
        tableName: this.tableItemForm.tableName,
      };

      // 获取当前表单结构信息
      getListName(data).then((res) => {
        this.tableFieldList = res.map((item, index) => {
          return {
            id: this.tableItemForm.tableName + "_" + item.fieldName,
            fieldName: item.fieldName,
            fieldDescription: item.fieldDescription,
            relationTable: "",
            relationFieldName: "",
            relaFieldNameList: [],
            disableRelaFieldName: false,
            relationType: "",
            relationShowField: [],
            relationShowFiledList: [],
            disableRelaType: false,
            isShow: true,
            isSearch: false,
            isExport: true,
            relationTableList: this.relationTableList,
            tableName: this.tableItemForm.tableName,
            relationFieldList: [],
          };
        });
      });
    },
    // 关联表变化回调
    async ralationTableChange(row) {
      this.tableFieldList = this.tableFieldList.filter((item) => {
        return !row.relationFieldList.some((val) => {
          return val.id == item.id;
        });
      });
      row.relationFieldName = "";
      row.relationType = "";
      row.disableRelaFieldName = false;
      row.disableRelaType = false;
      row.relationFieldList = [];
      if (!row.relationTable) {
        return;
      }
      // 获取关联表的字段
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
        tableName: row.relationTable,
      };
      let res = await getListName(data);
      // 关联字段下拉列表数据
      row.relaFieldNameList = res.map((item) => {
        return {
          fieldName: item.fieldName,
          fieldDescription: item.fieldDescription,
        };
      });
      let relationTableList = row.relationTableList.filter(
        (item) => row.relationTable != item.tableName
      );
      row.relationFieldList = row.relaFieldNameList.map((item, index) => {
        return {
          id: row.relationTable + "_" + item.fieldName,
          fieldName: item.fieldName,
          fieldDescription: item.fieldDescription,
          relationTable: "",
          relationFieldName: "",
          relaFieldNameList: [],
          disableRelaFieldName: false,
          relationType: "",
          relationShowField: [],
          relationShowFiledList: [],
          disableRelaType: false,
          isShow: true,
          isSearch: false,
          isExport: true,
          relationTableList,
          tableName: row.relationTable,
          relationFieldList: [],
          isChildren: true,
        };
      });
      row.disableRelaFieldName = true;
    },
    // 关联类型变化回调
    relationTypeChangeHandler(row) {
      let tempRelationFieldList = row.relationFieldList.filter((item) => {
        return !this.tableFieldList.find((val) => val.id === item.id);
      });
      this.tableFieldList = [...this.tableFieldList, ...tempRelationFieldList];
    },
    // 关联字段回调
    relationFieldChange(row) {
      if (!row.relationFieldName) {
        row.relationType = "";
        row.disableRelaType = false;
        row.relaFieldNameList = [];
        return;
      }
      row.disableRelaType = true;
    },
    // 递归获取列表信息
    getCol(
      tableFieldList,
      columns,
      searchFieldList = [],
      tableExportField = {}
    ) {
      if (!tableFieldList.length) return;
      for (let i = 0; i < tableFieldList.length; i++) {
        let temp = tableFieldList[i];
        let tempFieldName = "",
          exportFieldName = "";
        if (temp.isChildren) {
          tempFieldName = temp.tableName + "_" + temp.fieldName;
          exportFieldName = temp.tableName + "@" + temp.fieldName;
        } else {
          tempFieldName = temp.fieldName;
          exportFieldName = temp.fieldName;
        }
        if (temp.isShow) {
          let tempObj = {};
          tempObj[tempFieldName] = temp.fieldDescription;
          columns.push(tempObj);
        }
        if (temp.isSearch) {
          searchFieldList.push(temp.tableName + "." + temp.fieldName);
        }

        if (temp.isExport) {
          tableExportField[exportFieldName] = temp.fieldDescription;
        }
      }
    },
    // 获取所有表格
    async getAllTable() {
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
      };
      let res = await getFormName(data);

      const baseTable = await this.getDicts("base_table");

      this.tableList = res.data.filter((item) => {
        return !baseTable.data.some(
          (value) =>
            value.dictValue.toLowerCase() == item.tableName.toLowerCase()
        );
      });
    },
    // 确认添加一个表格
    confirmAddHandler(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let columns = [],
            searchFieldList = [];
          this.getCol(this.tableFieldList, columns, searchFieldList);
          // 判断是否有包含查询字段
          if (!searchFieldList.length) {
            this.$message.warning("请至少选择一个包含查询字段");
            return false;
          }
          let echoData = {};
          // 判断修改还是新增
          if (this.relateTitle) {
            echoData = {
              tableName: this.tableItemForm.tableName,
              tableFieldData: this.tableFieldList,
            };
            console.log(echoData);
            let tableKey = uuidv4();
            let sqlKey = uuidv4();

            this.relyFileds.tableFieldList = this.tableFieldList;
            this.relyFileds.tableName = this.tableItemForm.tableName;
            this.tableItemForm.rowId = Date.now();

            this.tableDataList.push({
              dtName: this.tableItemForm.title,
              dtTableName: this.tableItemForm.tableName,
              rowId: this.tableItemForm.rowId,
              selectFields: this.tableItemForm.selectFields,
              orderByColumn: this.tableItemForm.orderByColumn,
              timeFormate: this.tableItemForm.timeFormate,
              primaryKey: this.tableItemForm.selectFields,
              rowId: this.tableItemForm.rowId,
              tId: this.tId,
              tableKey: tableKey,
              sortOrder: this.tableItemForm.isAsc,
              sqlKey: sqlKey,
              dtColumnName: columns,
              timeFormat: "yyyy-MM-dd",
              searchFieldList: searchFieldList,
              conditionDefaultValueMap: this.conditionDefault,
              tableSql: this.getSQLStr(),
              tableExportField: "",
              echoData: JSON.stringify(echoData),
            });

            // 选择依赖字段
            this.groupList.push({
              tableFieldList: this.tableFieldList,
              tableItemForm: this.tableItemForm,
              conditionDefaultValueMap: this.conditionDefaultValueMap,
            });

            if (this.groupTitle) {
              this.addDragData.push({
                rowId: this.tableItemForm.rowId,
                tId: this.tId,
                dtName: this.tableItemForm.title,
                tableKey: tableKey,
                dtTableName: this.tableItemForm.tableName,
                primaryKey: this.tableItemForm.selectFields,
                orderByColumn: this.tableItemForm.orderByColumn,
                sortOrder: this.tableItemForm.isAsc,
                sqlKey: sqlKey,
                dtColumnName: columns,
                timeFormat: "yyyy-MM-dd",
                searchFieldList: searchFieldList,
                conditionDefaultValueMap: this.conditionDefault,
                tableSql: this.getSQLStr(),
                tableExportField: "",
                echoData: JSON.stringify(echoData),
              });
            }
          } else {
            echoData = {
              tableName: this.tableItemForm.tableName,
              tableFieldData: this.tableFieldList,
            };
            console.log("123456", echoData);
            this.tableDataList.forEach((item, index) => {
              if (item.tId == this.tableItemForm.tId) {
                item.conditionDefaultValueMap = this.conditionDefault;
                console.log(this.conditionDefault);
                item.echoData = JSON.stringify(echoData);
                item.sortOrder = this.tableItemForm.isAsc;
                item.orderByColumn = this.tableItemForm.orderByColumn;
                item.primaryKey = this.tableItemForm.selectFields;
                item.dtTableName = this.tableItemForm.tableName;
                item.dtName = this.tableItemForm.title;
                item.dtColumnName = JSON.stringify(columns);
                item.searchFieldList = searchFieldList;
              }
            });
          }
          this.isShowForm = false;
          echoData = {};
          this.tableItemForm = {};
          this.tableFieldList = [];
          this.relyFiledsList = [];
          this.conditionDefault = {};
          this.conditionDefaultValueMap = "";
          this.formdata.conditionDefaultValueMap = {};
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },
    // 修改一个表格数据
    relateOne(row, index) {
      this.editIndex = index;
      console.log(row);
      // console.log(this.orderByFieldList)
      if (row.tableKey) {
        this.menuId = row.menuId;
        this.conditionDefault = row.conditionDefaultValueMap;
        let echoData = JSON.parse(row.echoData);
        console.log(this.tableDataList);
        this.tableDataList.forEach((item, index) => {
          if (item.tableKey == row.tableKey) {
            if (index == 0) {
              this.relyFileds.tableFieldList = "";
            } else {
              let beforeEcho = JSON.parse(
                this.tableDataList[index - 1].echoData
              );

              this.relyFileds.tableFieldList = beforeEcho.tableFieldData;
            }
          }
        });
        this.tableFieldList = echoData.tableFieldData;
        this.tableItemForm.tId = row.tId;
        this.tableItemForm.rowId = row.tableKey;
        this.tableItemForm.isAsc = false;
        this.tableItemForm.orderByColumn = row.orderByColumn;
        this.tableItemForm.title = row.dtName;
        this.tableItemForm.tableName = row.dtTableName;
        this.tableItemForm.selectFields = row.primaryKey;
        this.tableItemForm.timeFormate = row.timeFormat;
      } else {
        (this.tableItemForm.rowId = row.rowId),
          (this.tableItemForm.title = row.dtName);
        this.tableItemForm.selectFields = row.selectFields;
        this.tableItemForm.tableName = row.dtTableName;
        this.tableItemForm.orderByColumn = row.orderByColumn;
        this.tableItemForm.timeFormate = row.timeFormat;

        this.getList();
        this.groupList.forEach((item) => {
          if (item.tableItemForm.rowId == row.rowId) {
            item.tableFieldList = this.tableFieldList;
          }
        });
      }

      this.getAllTable();
      // console.log('修改', this.groupList);
      // 展示字段的回显
      this.relateTitle = false;
      this.isShowForm = true;
    },
    // 删除表格组
    DeleteTableGroup(row) {
      const fIds = row.id || this.ids;
      const menus = row.menuId || this.menuIds;
      this.$modal
        .confirm(
          '是否确认删除动态单编号为"' +
            fIds +
            '"的数据项？删除后表格中所有的数据都将删除！'
        )
        .then(function () {
          return delMenu(menus);
        })
        .then(async () => {
          await delGroup(fIds);
          this.getTableList();
          this.reloadRouter();
          await getRouters();

          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 取消新增
    cancelAddHandler() {
      this.isShowForm = false;
      this.tableItemForm = {};
      this.tableFieldList = [];
    },
    // 关联类型变化回调
    relationTypeChangeHandler(row) {
      let tempRelationFieldList = row.relationFieldList.filter((item) => {
        return !this.tableFieldList.find((val) => val.id === item.id);
      });
      this.tableFieldList = [...this.tableFieldList, ...tempRelationFieldList];
    },
    // 更新路由
    reloadRouter() {
      this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
        this.$router.addRoutes(accessRoutes); // 动态添加可访问路由表
      });
    },
    // 获取目标menu
    getTargetMenu(menus) {
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].menuId == this.groupForm.routePath) {
          return menus[i];
        } else if (menus.children?.length) {
          return this.getTargetMenu(menus.children);
        }
      }
      return false;
    },
    // 获取父级menuId
    getParentMenuId(menuId, menus) {
      let res;
      for (let i = 0; i < menus.length; i++) {
        let item = menus[i];
        if (item.menuId == menuId) {
          res = item.parentId;
          break;
        } else if (item.children?.length) {
          if (
            this.getParentMenuId(
              menuId,
              JSON.parse(JSON.stringify(item.children))
            )
          ) {
            res = this.getParentMenuId(
              menuId,
              JSON.parse(JSON.stringify(item.children))
            );
          }
        }
      }
      return res;
    },
    // 修改表格回显数据
    async initTableData(tId) {
      let res = await getTableInfo(tId);
      console.log("回显数据", res);
      if (res.code == 200) {
        if (!this.formData.routePath) {
          this.$message.warning("该表格菜单路由已经删除,请重新配置");
        }
        // this.formData.routePath
        this.editData = res.data;
        let val = await getParticMenu(res.data.tableKey);
        if (val.code == 200) {
          this.menuId = val.data.menuId;
        }
      } else {
        this.$message.error("数据回显失败");
      }
    },
    // 新增动态表格组
    addTableGroup(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // console.log('groupList', this.groupList);
          if (this.addDragData.length < 2) {
            this.$message.error("请包含多个表格");
            return;
          }
          if (this.groupTitle) {
            let uuid = uuidv4();
            let groupKeyObj = {
              groupKey: uuid,
            };

            let payLoad = {
              component: "relateTable/relateTableEdit",
              icon: "",
              isCache: "0",
              isFrame: "1",
              menuName: this.groupForm.groupName,
              menuType: "C",
              orderNum: this.menuOrderNum,
              parentId: this.groupForm.routePath,
              path: groupKeyObj.groupKey,
              query: JSON.stringify(groupKeyObj),
              status: "0",
              visible: "0",
              tenantId: this.tenantId,
            };
            let result;

            result = await addMenu(payLoad);

            if (result.code == 200) {
              this.reloadRouter();
              let data = {
                groupKey: groupKeyObj.groupKey,
                groupName: "",
                groupDescription: "",
                groupTableInfo: [],
                dragTables: [],
              };
              console.log(this.addDragData);
              // return;
              this.addDragData.forEach((item, index) => {
                item.menuId = result.data;
                // item.sqlKey = tableKeyObj.tableKey
                let echo = JSON.parse(item.echoData);
                console.log(echo);
                echo.formData = this.groupForm;
                // item.echoData = JSON.stringify(echo)
                data.groupTableInfo.push({
                  tableKey: item.tableKey,
                  sort: index,
                  tablename: item.dtTableName,
                  menuId: result.data,
                });
              });
              data.groupName = this.groupForm.groupName;
              data.groupDescription = this.groupForm.groupDescription;
              data.groupTableInfo = JSON.stringify(data.groupTableInfo);
              data.dragTables = this.addDragData;

              // 添加表格组
              let res = await addGroup(data);
              console.log(res);
              if (res.code == 200) {
                this.$message.success("创建成功");

                this.isShowTable = false;
                this.groupForm = {};
              } else {
                this.$message.success("创建失败");
                this.isShowTable = false;
                this.groupForm = {};
              }
            }
          } else {
            let data = {
              groupKey: this.echogroup.groupKey,
              groupName: "",
              groupDescription: "",
              groupTableInfo: [],
              dragTables: [],
              id: this.groupId,
            };
            this.addDragData.forEach((item, index) => {
              // item.sqlKey = tableKeyObj.tableKey
              let echo = JSON.parse(item.echoData);
              // echo.formData = this.groupForm
              // console.log(echo);
              item.echoData = JSON.stringify(echo);
              data.groupTableInfo.push({
                tableKey: item.tableKey,
                sort: index,
                tablename: item.dtTableName,
                menuId: item.menuId,
              });
            });
            data.groupName = this.groupForm.groupName;
            data.groupDescription = this.groupForm.groupDescription;
            data.groupTableInfo = JSON.stringify(data.groupTableInfo);
            data.dragTables = this.addDragData;
            console.log(data);
            let res = await updataGroup(data);

            if (res.code == 200) {
              let payLoad = {
                menuId: this.menuId,
                menuName: this.groupForm.groupName,
                parentId: this.groupForm.routePath,
                component: "relateTable/relateTableEdit",
                icon: "",
                isCache: "0",
                isFrame: "1",
                menuType: "C",
                orderNum: this.menuOrderNum,
                status: "0",
                visible: "0",
                tenantId: this.tenantId,
              };
              let result = await updateMenu(payLoad);

              if (result.code == 200) {
                this.$message.success("修改成功");

                this.isShowTable = false;
                this.groupForm = {};
              } else {
                this.$message.success("修改失败");
                this.isShowTable = false;
                this.groupForm = {};
              }
            }
          }
          this.isShowTable = false;
          this.addDragData = [];
          this.groupForm = {};
          this.tableDataList = [];
          this.reloadRouter();
          this.getTableList();
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },
    /** 新增按钮操作 */
    async handleAdd() {
      await this.getMenuList();
      if (this.groupTitle) {
        this.groupForm.groupName = "";
        this.groupForm.groupDescription = "";
        this.groupForm.routePath = undefined;
        this.tableDataList = [];
      }
      this.groupTitle = true;
      this.isShowTable = true;
    },
    // 取消
    cancelGroup() {
      this.groupTitle = true;
      this.isShowTable = false;
    },
    // 获取路由表单数据
    async getMenuList() {
      let res = await getMenuList();
      this.menus = this.handleTree(res.data, "menuId");
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children,
      };
    },
    // 修改动态表格组回显
    async UpdateTableGroup(row) {
      await this.getMenuList();
      // let id = JSON.parse(row.id)
      getTable({ id: row.id }).then((res) => {
        this.echogroup = res.data;
        this.groupId = res.data.id;
        // 关联表格
        this.groupTableInfo = JSON.parse(res.data.groupTableInfo);
        this.menuId = res.data.dragTables[0].menuId;

        this.groupForm = res.data;
        // res.data.dragTables.forEach(item => {
        //   if(item.orderByColumn.includes('.')){
        //     item.orderByColumn = item.orderByColumn.split('.')[1]
        //   }
        // })
        this.addDragData = res.data.dragTables;
        // 菜单路由回显
        this.tableDataList = this.groupForm.dragTables;
        this.groupForm.routePath = this.getParentMenuId(
          res.data.dragTables[0].menuId,
          this.menus,
          {}
        );

        if (!this.groupForm.routePath) {
          this.$message.warning("该表格菜单路由已经删除,请重新配置");
        }
      });

      this.groupTitle = false;
      this.isShowTable = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tId: null,
        dtName: null,
        dtNickname: null,
        tableKey: null,
        sqlKey: null,
        dtTableName: null,
        dtNotes: null,
        dtColumnName: null,
        timeFormat: null,
        spare: null,
        spare1: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isSelection: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.getTableList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.id);
      this.Keys = selection.map((item) => item.sqlKey);
      selection.forEach((vals) => {
        this.menuIds = vals.groupTableInfo.map((item) => item.menuId);
        console.log(this.menuIds);
      });
      this.selection = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      // 兼容勾选单个的修改
      let tId = row?.tId || this.ids[0];
      // this.$router.push({
      //   path: "/system/fromModel/index/tableMange",
      //   query: {
      //     tId: tId,
      //   },
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.tId != null) {
            updateTable(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTable(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row);
      this.tableDataList.forEach((item, index) => {
        if (row.tableKey == item.tableKey) {
          this.tableDataList.splice(index, 1);
        }
      });
    },
    // 更新路由
    reloadRouter() {
      this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
        this.$router.addRoutes(accessRoutes); // 动态添加可访问路由表
      });
    },
    // 新增一个联动表格
    addOneTable() {
      this.relateTitle = true;
      if (this.relateTitle) {
        this.tableItemForm = {};
        this.tableFieldList = [];
        this.conditionDefaultValueMap = "";
      }
      if (!this.groupTitle) {
        // console.log(this.tableDataList[this.tableDataList.length-1].dtTableName)

        this.relyFileds.tableName =
          this.tableDataList[this.tableDataList.length - 1].dtTableName;

        let echoData = JSON.parse(
          this.tableDataList[this.tableDataList.length - 1].echoData
        );

        this.relyFileds.tableFieldList = echoData.tableFieldData;
      }
      this.getAllTable();
      // 注意校验最后一条数据是否合法
      this.isShowForm = true;
    },

    // 重置表单
    // tableItemFormReset() {
    //   Object.assign(this.tableItemForm, {
    //     title: "",
    //     tableId: "",
    //     tableName: "",
    //     showFields: [],
    //     theRelateField: "",
    //     executeOptions: [],
    //   });
    // },
    // handlePreview() {
    //   this.$router.push({
    //     path: "/system/fromModel/index/relateTableEdit",
    //   });
    // },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog:not(.is-fullscreen) {
  width: 900px !important;
}
.isSearch {
  ::v-deep .el-dialog:not(.is-fullscreen) {
    width: 320px !important;
  }
  ::v-deep .el-input--medium .el-input__inner {
    margin-bottom: 10px !important;
  }
}
.tablefiled {
  ::v-deep .el-input--medium .el-input__inner {
    width: 70px !important;
  }
}
::v-deep .el-input--medium .el-input__inner {
  width: 230px !important;
}
::v-deep .btn {
  text-align: right !important;
}
.ipt {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  outline: none;
  text-align: center;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  display: inline-block;
  border-radius: 4px;
}
.isNullDesc {
  border-color: #ff4949 !important;
}

.ipt:focus {
  border-color: #1890ff;
}
::v-deep .vue-treeselect--has-value .vue-treeselect__input {
  vertical-align: middle !important;
}
.formWrap {
  display: flex;
  justify-content: center;
}

::v-deep .el-table {
  margin-top: 10px;
}
.nameipt {
  display: inline;
  margin-left: 10px;
  ::v-deep .el-input--medium .el-input__inner {
    width: 30%;
  }
  ::v-deep .el-input--medium {
    display: inline;
  }
}
.desc {
  margin-left: 10px;
}
::v-deep .vue-treeselect--has-value .vue-treeselect__input {
  vertical-align: middle !important;
}
.treeselect {
  .vue-treeselect {
    width: 230px !important;
  }
}
</style>

<style lang="scss">
.vue-treeselect {
  z-index: 9999 !important;
}
</style>
