<template>
  <div class="app-container">
    <el-card style="margin-bottom: 15px">
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <!-- <el-form-item label="数据库名称" prop="dataBaseName">
            <el-input v-model="form.dataBaseName" style="width: 600px;"></el-input>
        </el-form-item> -->
        <el-form-item label="数据表名称" prop="tableName">
          <el-input
            v-model="form.tableName"
            :disabled="isEdited"
            style="width: 600px"
          ></el-input>
        </el-form-item>
        <el-form-item label="表描述">
          <el-input v-model="form.tableComment" style="width: 600px"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div class="titleitem">
        <span>数据表字段</span>
      </div>
      <el-form ref="tableform" :rules="tableform" :model="experienceDataForm">
        <el-table
          ref="dragTable"
          :data="experienceData"
          stripe
          row-key="tag"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="50"
            class-name="allowDrag"
          />
          <el-table-column prop="fieldName" label="字段名称" width="200">
            <template slot-scope="scope">
              <el-form-item
                :prop="'fieldName' + scope.$index"
                :name="'fieldName' + scope.$index"
                style="margin: 0px; padding: 0px"
              >
                <el-input
                  v-model="scope.row.fieldName"
                  :disabled="scope.$index == 0"
                  @blur="fieldNameChange(scope.row)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="fieldType" label="字段类型" width="200">
            <template slot-scope="scope">
              <el-form-item
                :prop="'fieldType' + scope.$index"
                :name="'fieldType' + scope.$index"
                style="margin: 0px; padding: 0px"
              >
                <el-select
                  :disabled="scope.$index == 0"
                  v-model="scope.row.fieldType"
                  filterable
                  @blur="selectBlur(scope)"
                  @change="
                    handleSelected(
                      dataType.find(
                        (item) => item.label === scope.row.fieldType
                      ),
                      scope,
                      scope.$index,
                      scope.row
                    )
                  "
                >
                  <!-- <el-option v-for="item in list" :key="item" :label="item" :value="item">
                  </el-option> -->
                  <!--
                  <el-option v-for="item in dict.type.mysql_data_type"  :label="item.dictLabel" :value="item.dictValue">
                  </el-option> -->
                  <el-option
                    v-for="item in dataType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="fieldLength" label="长度" width="200">
            <template slot-scope="scope">
              <el-form-item
                :prop="'fieldLength' + scope.$index"
                :name="'fieldLength' + scope.$index"
                style="margin: 0px; padding: 0px"
              >
                <!--                <el-input v-model="scope.row.fieldLength"-->
                <!--                          :disabled="handleSelected(dict.type.mysql_data_type.find(item => item.label === scope.row.fieldType), scope)"></el-input>-->
                <el-input
                  v-model="scope.row.fieldLength"
                  @blur="fieldLengthChange(scope.$index, scope.row)"
                  :disabled="changduclick(scope.$index) || scope.$index == 0"
                  @input="
                    scope.row.fieldLength = scope.row.fieldLength.replace(
                      /^(0+)|[^\d]+/g,
                      ''
                    )
                  "
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="isNull" label="不是null" width="100">
            <template slot-scope="scope">
              <el-checkbox
                :disabled="scope.$index == 0"
                @change="isNullChange(scope.row)"
                v-model="scope.row.isNull"
              ></el-checkbox>
            </template>
          </el-table-column>

          <el-table-column prop="isPrimary" label="主键" width="100">
            <template slot-scope="scope">
              <el-checkbox
                :disabled="scope.$index == 0"
                v-model="scope.row.isPrimary"
                @change="hanleCheckbox(scope.$index, scope.row)"
              ></el-checkbox>
            </template>
          </el-table-column>

          <el-table-column prop="isAuto" label="自增" width="100">
            <template slot-scope="scope">
              <el-checkbox
                :disabled="scope.$index == 0"
                @change="isAutoChange(scope.row)"
                v-model="scope.row.isAuto"
              ></el-checkbox>
            </template>
          </el-table-column>

          <el-table-column prop="fieldDescription" label="字段描述" width="200">
            <template slot-scope="scope">
              <el-input
                :disabled="scope.$index == 0"
                @change="fieldDescriptionChange(scope.row)"
                v-model="scope.row.fieldDescription"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="operate" label="操作">
            <template slot-scope="scope">
              <!-- <el-button size="mini" type="success" icon="el-icon-save"
                  @click="handlesaveExperience(scope.$index, scope.row)">保存
              </el-button> -->
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                :disabled="scope.$index == 0"
                @click="handleDeleteExperience(scope.$index, scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddExperienceline"
          >新增字段
        </el-button>
      </div>
    </el-card>

    <div style="margin-top: 15px">
      <el-button v-if="!isEdited" @click="add" type="primary">添加</el-button>
      <el-button v-else @click="edit" type="primary">修改</el-button>
    </div>
  </div>
</template>

<script>
import { createDatabase } from "@/api/datasheet/index";
import { tableInfo, editTable } from "@/api/dataEngine/index";
import { mapState } from "vuex";
import { getDicts } from "@/api/system/dict/data";
import Sortable from "sortablejs";
import { v4 as uuidv4 } from "uuid";
export default {
  name: "Datasheet",
  // dicts: [
  //   "dm_data_type",
  //   "mysql_data_type",
  //   "sqlserver_data_type",
  //   "oracle_data_type",
  // ],
  data() {
    return {
      sqlStringList: [],
      isEdited: false,
      testzidian: null,
      form: {
        dataBaseName: "",
        tableName: "",
        tableComment: "",
      },
      experienceDataForm: {},
      experienceData: [
        {
          fieldName: "id",
          fieldType: "bigint",
          fieldLength: undefined,
          isNull: true,
          isPrimary: true,
          fieldDescription: "主键",
          isAuto: true,
        },
      ],
      rules: {
        dataBaseName: {
          validator: this.checkDataBaseName,
          trigger: "blur",
        },

        tableName: {
          validator: this.checkTableName,
          trigger: "blur",
        },
      },
      tableform: {
        // fieldName0: { required: true, message: '请输入字段名称', trigger: 'blur' },
        // fieldType0: { required: true, message: '请选择', trigger: 'change' },
        // fieldLength0: { required: true, message: '请输入', trigger: 'blur' },
      },
      list: ["int", "varchar"],
      dataType: [], //数据类型字典

      Inoputdisabled: [],
      // 需要指定长度
      mysqlAllowLength: ["char", "varchar", "numeric", "decimal"],
      modifySQLString: {
        modify: {},
        delete: {},
        addNew: {},
      },
    };
  },
  async created() {
    await this.getDict();
    if (this.$route.query.tableName) {
      this.isEdited = true;
      this.info();
    } else {
      Object.keys(this.form).forEach((item) => {
        this.form[item] = "";
      });
      // this.experienceData = [];
    }
  },
  mounted() {
    this.initDragTable();
  },
  computed: {
    ...mapState({
      databaseName: (state) => state.user.dataSource.databaseName,
      databaseType: (state) => state.user.dataSource.databaseType,
    }),
  },
  watch: {
    experienceData: {
      handler(n, o) {
        // do something
        // this.experienceDataForm = {};
        let rulesAdd = {};
        this.experienceData.forEach((item, index) => {
          this.$set(
            this.experienceDataForm,
            "fieldName" + index,
            item.fieldName
          );
          this.$set(
            this.experienceDataForm,
            "fieldType" + index,
            item.fieldType
          );
          this.$set(
            this.experienceDataForm,
            "fieldLength" + index,
            item.fieldLength
          );
          // rulesAdd['' + index] = item.fieldName
          // rulesAdd['fieldType' + index] = item.fieldType
          // rulesAdd['fieldLength' + index] = item.fieldLength
          // this.experienceDataForm = {...rulesAdd}
        });
      },
      deep: true, // 深度监听父组件传过来对象变化
      immediate: true,
    },
  },
  methods: {
    /* 修改记录回调start */
    // 字段名称修改回调
    fieldNameChange(row) {
      if (!row.fieldName) return;
      if (this.databaseType == "mysql") {
        if (row.oldVal) {
          if (!this.modifySQLString.modify[row.oldVal.fieldName]) {
            this.modifySQLString.modify[row.oldVal.fieldName] = {};
          }
          //更改
          this.modifySQLString.modify[row.oldVal.fieldName].fieldName =
            this.mysqlMotifySQLString("fieldName", row);
          this.sqlStringList.push(this.mysqlMotifySQLString("fieldName", row));
        } else if (row.fieldType) {
          //新增
          this.modifySQLString.addNew[row.fieldName] =
            this.mysqlMotifySQLString("addNew", row);
          this.sqlStringList.push(this.mysqlMotifySQLString("addNew", row));
        }
      }
    },
    // 字段类型改变回调
    fieldTypeChange(index, row) {
      if (!row.fieldType) return;
      if (this.databaseType == "mysql") {
        if (!this.modifySQLString.modify[row.fieldName]) {
          this.modifySQLString.modify[row.fieldName] = {};
        }
        if (row.oldVal) {
          this.modifySQLString.modify[row.fieldName].fieldType =
            this.mysqlMotifySQLString("fieldType", row);
          this.sqlStringList.push(this.mysqlMotifySQLString("fieldType", row));
        } else if (row.fieldName) {
          //新增
          this.modifySQLString.addNew[row.fieldName] =
            this.mysqlMotifySQLString("addNew", row);
          this.sqlStringList.push(this.mysqlMotifySQLString("addNew", row));
        }
      }
    },
    // 字段长度改变回调
    fieldLengthChange(idnex, row) {
      if (!row.fieldLength) return;
      if (this.databaseType == "mysql") {
        if (!this.modifySQLString.modify[row.fieldName]) {
          this.modifySQLString.modify[row.fieldName] = {};
        }
        if (row.oldVal) {
          this.modifySQLString.modify[row.fieldName].fieldLength =
            this.mysqlMotifySQLString("fieldLength", row);
          this.sqlStringList.push(
            this.mysqlMotifySQLString("fieldLength", row)
          );
        }
      }
    },
    //处理非空选框问题
    isNullChange(row) {
      if (!row.isNull) {
        row.isPrimary = false;
      }
      if (this.databaseType == "mysql") {
        if (row.oldVal) {
          if (!this.modifySQLString.modify[row.fieldName]) {
            this.modifySQLString.modify[row.fieldName] = {};
          }
          this.modifySQLString.modify[row.fieldName].isNull = row.isNull
            ? this.mysqlMotifySQLString("NOT NULL", row)
            : this.mysqlMotifySQLString("NULL", row);
          this.sqlStringList.push(
            row.isNull
              ? this.mysqlMotifySQLString("NOT NULL", row)
              : this.mysqlMotifySQLString("NULL", row)
          );
        }
      }
    },
    // 处理主键选框问题
    hanleCheckbox(ind, row) {
      if (!this.modifySQLString.modify[row.fieldName]) {
        this.modifySQLString.modify[row.fieldName] = {};
      }
      if (row.isPrimary && (!row.oldVal || !row.oldVal.isPrimary)) {
        //添加新的主键
        this.modifySQLString.modify[row.fieldName].addPrimary =
          this.mysqlMotifySQLString("primary", row);
        this.sqlStringList.push(this.mysqlMotifySQLString("primary", row));
      }
      this.experienceData.forEach((item, index) => {
        if (index != ind) {
          if (item.oldVal?.isPrimary) {
            if (!this.modifySQLString.delete[item.fieldName]) {
              this.modifySQLString.delete[item.fieldName] = {};
            }
            //去掉原来的主键
            this.modifySQLString.delete[item.fieldName].dropPrimary =
              this.mysqlMotifySQLString("drop primary", item);
            this.sqlStringList.push(
              this.mysqlMotifySQLString("drop primary", item)
            );
          }
          item.isPrimary = false;
        }
        if (index == ind && item.isPrimary == true) {
          item.isNull = true;
          item.isAuto = true;
        }
      });
    },
    // 是否自增改变
    isAutoChange(row) {
      let sqlString = "";
      if (!this.modifySQLString.modify[row.fieldName]) {
        this.modifySQLString.modify[row.fieldName] = {};
      }
      if (row.oldVal) {
        if (row.oldVal.isAuto != row.isAuto) {
          this.modifySQLString.modify[row.fieldName].increment = row.isAuto
            ? this.mysqlMotifySQLString("increment", row)
            : this.mysqlMotifySQLString("no increment", row);
          sqlString = row.isAuto
            ? this.mysqlMotifySQLString("increment", row)
            : this.mysqlMotifySQLString("no increment", row);
        }
      } else {
        this.modifySQLString.modify[row.fieldName].increment = row.isAuto
          ? this.mysqlMotifySQLString("increment", row)
          : this.mysqlMotifySQLString("no increment", row);
        sqlString = row.isAuto
          ? this.mysqlMotifySQLString("increment", row)
          : this.mysqlMotifySQLString("no increment", row);
      }
      if (sqlString) {
        this.sqlStringList.push(sqlString);
      }
    },
    // 字段描述改变
    fieldDescriptionChange(row) {
      let sqlString = "";
      if (!this.modifySQLString.modify[row.fieldName]) {
        this.modifySQLString.modify[row.fieldName] = {};
      }
      if (row.oldVal) {
        if (row.oldVal.fieldDescription != row.fieldDescription) {
          this.modifySQLString.modify[row.fieldName].fieldDescription =
            this.mysqlMotifySQLString("describe", row);
          sqlString = this.mysqlMotifySQLString("describe", row);
        }
      } else {
        this.modifySQLString.modify[row.fieldName].fieldDescription =
          this.mysqlMotifySQLString("describe", row);
        sqlString = this.mysqlMotifySQLString("describe", row);
      }
      if (sqlString) {
        this.sqlStringList.push(sqlString);
      }
    },

    // 删除字段回调
    deleteField(row) {
      let sqlString = "";
      if (row.oldVal) {
        this.modifySQLString.delete[row.fieldName] = this.mysqlMotifySQLString(
          "deleteField",
          row
        );
        sqlString = this.mysqlMotifySQLString("deleteField", row);
      }
      delete this.modifySQLString.modify[row.fieldName];
      delete this.modifySQLString.addNew[row.fieldName];
      // delete this.modifySQLString.delete[row.fieldName];
      if (sqlString) {
        this.sqlStringList.push(sqlString);
      }
    },

    // 拼接mysql的修改语句
    mysqlMotifySQLString(type, row) {
      let table_name = this.form.tableName,
        res = "ALTER TABLE";

      switch (type) {
        case "fieldName": //改字段
          res += ` ${table_name} CHANGE ${row.oldVal.fieldName} ${row.fieldName} ${row.fieldType};`;
          break;
        case "fieldLength": //改长度
          res += ` ${table_name} MODIFY ${row.fieldName} ${row.fieldType}(${row.fieldLength});`;
          break;
        case "fieldType": //改类型
          res += ` ${table_name} MODIFY ${row.fieldName} ${row.fieldType};`;
          break;
        case "NULL": //改允许为NULL
          res += ` ${table_name} MODIFY ${row.fieldName} ${row.fieldType} NULL;`;
          break;
        case "NOT NULL": //改不允许为NULL
          res += ` ${table_name} MODIFY ${row.fieldName} ${row.fieldType} NOT NULL;`;
          break;
        case "primary": //设为主键
          res += ` ${table_name} ADD PRIMARY KEY (${row.fieldName});`;
          break;
        case "drop primary": //删除主键
          res += ` ${table_name} DROP PRIMARY KEY;`;
          break;
        case "increment": //添加自增
          res += ` ${table_name} MODIFY ${row.fieldName} INT AUTO_INCREMENT;`;
          break;
        case "no increment": //删除自增属性
          res += ` ${table_name} MODIFY ${row.fieldName} INT;`;
          break;
        case "describe": //修改字段描述
          res += ` ${table_name} MODIFY ${row.fieldName} ${row.fieldType}${
            row.fieldLength ? "" : "(" + row.fieldLength + ")"
          } comment '${row.fieldDescription}';`;
          break;
        case "deleteField":
          res += ` ${table_name} DROP ${row.fieldName};`;
          break;
        case "addNew": //新增列
          res += ` ${table_name} ADD ${row.fieldName} ${row.fieldType};`;
          break;
        default:
          break;
      }

      return res;
    },

    // 获取sql列表
    getSQLStringList() {
      let res = [];
      console.log(this.modifySQLString);
      let deleteList = Object.values(this.modifySQLString.delete);
      if (deleteList.length) {
        for (const value of deleteList) {
          res.push(Object.values(value)[0]);
        }
      }
      let addNewList = Object.values(this.modifySQLString.addNew);
      if (addNewList.length) {
        res = [...res, ...addNewList];
      }
      let modifyList = Object.values(this.modifySQLString.modify);
      if (modifyList.length) {
        for (const value of modifyList) {
          res.push(Object.values(value)[0]);
        }
      }
      console.log(res);
      return res;
    },

    /* 修改记录回调start */

    // 加载数据字典
    async getDict() {
      let res = await this.getDicts(this.databaseType + "_data_type");
      if (res.code == 200) {
        this.dataType = res.data.map((item) => {
          return {
            raw: item,
            value: item.dictValue,
            label: item.dictLabel,
          };
        });
      } else {
        console.log(res.msg);
      }
    },
    // 初始化表格数据
    info() {
      const tableName = this.$route.query.tableName;
      const tableComment = this.$route.query.tableComment;
      this.form.tableName = tableName;
      this.form.tableComment = tableComment;

      let data = {
        tableName,
        databaseType: this.databaseType,
        databaseName: this.databaseName,
      };
      tableInfo(data).then((response) => {
        this.experienceData = [];
        response.data.forEach((item, index) => {
          item.oldVal = JSON.parse(JSON.stringify(item)); // 保留原始数据
          // item.sort = index;
          item.tag = uuidv4();
          this.experienceData.push(item);
          this.handleRules("add");
        });
        // 初始化校验规则
        this.initInputEditable();
      });
    },
    // 初始化长度框是否禁用
    initInputEditable() {
      this.experienceData.map((val, index) => {
        let temp = JSON.parse(JSON.stringify(this.dataType));
        let targetDictItem = temp.find((item) => {
          return item.label === val.fieldType;
        });
        this.handleSelected(targetDictItem, { $index: index, row: val });
      });
    },
    // 处理长度框是否可输入
    changduclick(inputIndex) {
      return this.Inoputdisabled[inputIndex];
    },
    // 下拉选中事件  // 处理选中类型后长度输入框是否禁用
    handleSelected(tem, scope, index, val) {
      console.log(val);
      if (val) {
        //判断是否是由change事件触发的函数
        this.fieldTypeChange(index, val);
      }
      if (tem == undefined) return;
      if (!this.tableform["fieldLength" + scope.$index]) {
        this.tableform["fieldLength" + scope.$index] = {};
      }
      if (tem.raw.listClass === "success") {
        this.Inoputdisabled[scope.$index] = true; // 禁用长度输入框
        scope.row.fieldLength = "";
        this.tableform["fieldLength" + scope.$index].required = false; // 禁用长度输入框的校验
        return this.$set(
          this.experienceDataForm,
          "fieldType" + scope.$index,
          scope.row.fieldType
        );
      }
      this.Inoputdisabled[scope.$index] = false; // 解除禁用
      this.tableform["fieldLength" + scope.$index].required = true; // 启用长度输入框的校验
      return this.$set(
        this.experienceDataForm,
        "fieldType" + scope.$index,
        scope.row.fieldType
      );
    },

    // 下拉选中事件
    selectBlur(aa) {
      if (aa.row.fieldType == "") {
        aa.row.fieldType = undefined;
      }
    },
    //判断一个字符串是否只包含数字、下划线和小写字母
    isValidString(str) {
      const regex = /^[a-z0-9_]+$/;
      return regex.test(str);
    },
    // 字段名规则校验
    checkFieldName(rule, value, callback) {
      let msg = "";
      if (!value.trim().length) {
        msg = "请输入字段名称";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (value[0] == "_") {
        msg = "请不要以下划线开头";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (!isNaN(value[0])) {
        msg = "请不要以数字开头";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (!this.isValidString(value)) {
        msg = "字段名应该只有下划线,数字和小写字母";
        this.$message.error(msg);
        callback(new Error(msg));
      } else {
        //字段名去重校验
        if (
          this.experienceData.filter((item) => item.fieldName == value)
            .length == 1
        ) {
          callback();
        } else {
          callback(new Error("字段名称不能重复"));
        }
      }
    },
    // 校验数据表名称
    checkTableName(rule, value, callback) {
      let msg = "";
      if (!value.trim().length) {
        msg = "请输入数据表名称";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (value[0] == "_") {
        msg = "数据表名,请不要以下划线开头";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (!isNaN(value[0])) {
        msg = "数据表名,请不要以数字开头";
        this.$message.error(msg);
        callback(new Error(msg));
      } else if (!this.isValidString(value)) {
        msg = "数据表名,字段名应该只有下划线,数字和小写字母";
        this.$message.error(msg);
        callback(new Error(msg));
      } else {
        callback();
      }
    },
    //

    // 处理非空校验问题
    handleRules(type, delindex, addindex) {
      if (type == "add") {
        let rulesAdd = {};
        // 得到添加一行的下标
        let index = this.experienceData.length - 1;
        rulesAdd["fieldName" + index] = [
          {
            required: true,
            message: "请输入字段名称",
            trigger: "blur",
          },
          {
            validator: this.checkFieldName,
            trigger: "blur",
          },
        ];
        rulesAdd["fieldType" + index] = {
          required: true,
          message: "请选择",
          trigger: "change",
        };
        rulesAdd["fieldLength" + index] = {
          required: true,
          message: "请输入",
          trigger: "blur",
        };
        // 序列化当前校验规则对象
        this.tableform = {
          ...this.tableform,
          ...rulesAdd,
        };
      } else if (type == "del") {
        // 删除校验规则对象中的元素
        this.$delete(this.tableform, "fieldName" + delindex);
        this.$delete(this.tableform, "fieldType" + delindex);
        this.$delete(this.tableform, "fieldLength" + delindex);
      }
    },
    // 校验表格数据完整性
    validateTableData() {
      return this.experienceData.every((item) => {
        return item.fieldName && item.fieldType;
      });
    },
    //增加经验行
    handleAddExperienceline() {
      let flag = this.validateTableData();
      if (!flag) {
        this.$message.error("请完善表单信息");
        return;
      }
      if (this.experienceData == undefined) {
        this.experienceData = new Array();
      }
      let obj = {
        sort: this.experienceData.length + 1,
        tag: uuidv4(),
        fieldName: "",
        fieldType: "",
        fieldLength: undefined,
        isDisableFieldLength: true,
        isNull: false,
        isPrimary: false,
        fieldDescription: "",
        isAuto: false,
      };
      this.experienceData.push(obj);
      this.handleRules("add");
      this.Inoputdisabled.push(false);
    },
    //保存经验行
    handlesaveExperience(a, b) {
      // console.log(a + b);
      // console.log(b);
    },
    //删除经验行
    handleDeleteExperience(index, row) {
      this.experienceData.splice(index, 1);
      this.handleRules("del", index);
      this.deleteField(row);
      this.initInputEditable();
    },
    add() {
      const rule1 = new Promise((resolve, reject) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
      const rule2 = new Promise((resolve, reject) => {
        this.$refs["tableform"].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
      Promise.all([rule1, rule2]).then(() => {
        if (this.experienceData.length == 0) {
          this.$modal.msgWarning("字段不可为空！");
          return;
        }
        this.experienceData.forEach((field) => {
          if (field.fieldLength) {
            field.fieldType = `${field.fieldType}(${field.fieldLength})`;
          }
        });
        let query = {
          databaseType: this.$store.state.user.dataSource.databaseType,
          databaseName: this.$store.state.user.dataSource.databaseName,
          tableName: this.form.tableName,
          tableComment: this.form.tableComment,
          field: this.experienceData,
        };
        createDatabase(query)
          .then((res) => {
            this.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
              this.visible = false;
              this.$emit("ok");
              Object.keys(this.form).forEach((key) => (this.form[key] = ""));
              this.experienceData = [];
              this.$tab.closePage().then(() => {
                this.$router.push({
                  path: "/data/datamodeling",
                });
              });
              // 新增成功之后关闭当前页面
              // this.$router.replace({
              //   path: "/data/datamodeling",
              // });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    edit() {
      const rule1 = new Promise((resolve, reject) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
      const rule2 = new Promise((resolve, reject) => {
        this.$refs["tableform"].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            return false;
          }
        });
      });
      Promise.all([rule1, rule2]).then(() => {
        if (this.experienceData.length == 0) {
          this.$modal.msgWarning("字段不可为空！");
          return;
        }
        this.experienceData = this.experienceData.filter((item) => {
          return item.fieldName && item.fieldType;
        });
        this.experienceData.forEach((field) => {
          if (field.fieldLength) {
            field.fieldType = `${field.fieldType}(${field.fieldLength})`;
          }
        });

        // console.log(this.sqlStringList);
        // return;
        let query = {
          databaseType: this.$store.state.user.dataSource.databaseType,
          databaseName: this.$store.state.user.dataSource.databaseName,
          tableName: this.form.tableName,
          tableComment: this.form.tableComment,
          field: this.experienceData,
        };
        editTable(query)
          .then((res) => {
            this.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
              this.visible = false;
              this.$emit("ok");
              Object.keys(this.form).forEach((key) => (this.form[key] = ""));
              this.experienceData = [];
              this.$tab.closePage().then(() => {
                this.$router.push({
                  path: "/data/datamodeling",
                });
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
        // 关闭当前页面
        this.$tab.closePage();
      });
    },
    //处理表格行拖拽
    initDragTable() {
      const el = this.$refs.dragTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      const sortable = Sortable.create(el, {
        handle: ".allowDrag",
        onEnd: (evt) => {
          const targetRow = this.experienceData.splice(evt.oldIndex, 1)[0];
          this.experienceData.splice(evt.newIndex, 0, targetRow);
          for (let index in this.experienceData) {
            this.experienceData[index].sort = parseInt(index) + 1;
          }
          // 初始化校验规则
          this.experienceData.map((val, index) => {
            let temp = JSON.parse(JSON.stringify(this.dataType));
            let targetDictItem = temp.find((item) => {
              return item.label === val.fieldType;
            });
            this.handleSelected(targetDictItem, { $index: index, row: val });
          });
          this.$nextTick(() => {
            this.$refs.dragTable.doLayout();
          });
        },
      });
    },
  },
};
</script>
<style scoped lang="scss"></style>
