<template>
  <j-editable-table
    ref="editableTable"
    :loading="loading"
    :columns="columns"
    :dataSource="dataSource"
    :dragSort="true"
    dragSortKey="orderNum"
    :rowNumber="true"
    :rowSelection="true"
    :actionButton="actionButton"
    :maxHeight="300"
    :addButtonSettings="true"
    :disabledRows="{dbFieldName: 'id'}"
    @added="handleAdded"
    @deleted="handleDeleted"
    @dragged="handleDragged"
    @inserted="handleInserted"
    @valueChange="handleValueChange"
  />
</template>

<script>

import {FormTypes} from '@/utils/JEditableTableUtil'

let keywords = ["ADD", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE", "COLUMN", "CONDITION", "CONNECTION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DELAYED", "DELETE", "DESC", "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "ENCLOSED", "ESCAPED", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FLOAT", "FLOAT4", "FLOAT8", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GOTO", "GRANT", "GROUP", "HAVING", "HIGH_PRIORITY", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "IS", "ITERATE", "JOIN", "KEY", "KEYS", "KILL", "LABEL", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MATCH", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NOT", "NO_WRITE_TO_BINLOG", "NULL", "NUMERIC", "ON", "OPTIMIZE", "OPTION", "OPTIONALLY", "OR", "ORDER", "OUT", "OUTER", "OUTFILE", "PRECISION", "PRIMARY", "PROCEDURE", "PURGE", "RAID0", "RANGE", "READ", "READS", "REAL", "REFERENCES", "REGEXP", "RELEASE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESTRICT", "RETURN", "REVOKE", "RIGHT", "RLIKE", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET", "SHOW", "SMALLINT", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SSL", "STARTING", "STRAIGHT_JOIN", "TABLE", "TERMINATED", "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "WHEN", "WHERE", "WHILE", "WITH", "WRITE", "X509", "XOR", "YEAR_MONTH", "ZEROFILL", "FILE", "DATE", "TIME", "DATETIME", "TEXT"]
let primaryKey = "_pk"

export default {
  name: 'DbAttributeTable',
  components: {},
  inject: ["getAllTable"],
  props: {
    actionButton: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  data() {
    let self = this;
    return {
      loading: false,
      primaryKey:primaryKey,
      deleteIds : [],
      selectedRowKeys : [],
      jet: null, // jeecg editableTable => jet
      addBatching : false,
      columns: [
        {
          title: "字段名称",
          key: "dbFieldName",
          width: "160px",
          type: FormTypes.input,
          defaultValue: "",
          placeholder: "请输入${title}",
          validateRules: [
            { required: true, message: "${title}不能为空"},
            { pattern: /^[a-zA-Z]{1}(?!_)[a-zA-Z0-9_\\$]+$/,
              message: "命名规则:只能由字母、数字、下划线、$符号组成;必须以字母开头;不能以单个字母加下滑线开头"
            },
            {
              handler: function (type, value, row, column, callback, target) {
                // type 触发校验的类型（input、change、blur、getValues）
                // value 当前校验的值
                // callback(flag, message) 方法必须执行且只能执行一次
                //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                //          message = 提示的消息，默认使用配置的 message
                // target 行编辑的实例对象
                let count = 0;
                for (let inputValue of target.inputValues) {
                  let dbFieldName = inputValue["dbFieldName"];
                  if (target.getCleanId(inputValue.id) === row.id && keywords.includes(dbFieldName.toUpperCase())){
                    return void callback(false, value + "是关键字，不能作为字段名称使用！");
                  }
                  if (dbFieldName === value && ++count >= 2) {
                    return void callback(false, value + "已存在，不能重复！")
                  }
                }
                callback(true)
              },
              message: "不能有重复的值"
            }
          ],
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "字段备注",
          key: "dbFieldTxt",
          width: "140px",
          type: FormTypes.input,
          defaultValue: "",
          placeholder: "请输入${title}",
          validateRules: [
            {required: true, message: "${title}不能为空"}
          ]
        },
        {
          title: "字段长度",
          key: "dbLength",
          width: "100px",
          type: FormTypes.inputNumber,
          defaultValue: 32,
          placeholder: "请输入${title}",
          validateRules: [
            {required: true, message: "${title}不能为空"}
          ],
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "小数点",
          key: "dbPointLength",
          width: "100px",
          type: FormTypes.inputNumber,
          defaultValue: 0,
          placeholder: "请输入${title}",
          validateRules: [
            {required: true, message: "${title}不能为空"}
          ],
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "默认值",
          key: "dbDefaultVal",
          width: "130px",
          type: FormTypes.input,
          defaultValue: "",
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "字段类型",
          key: "dbType",
          width: "140px",
          type: FormTypes.select,
          options: [
            {title: "String", value: "string"},
            {title: "Integer", value: "int"},
            {title: "Double",value: "double"},
            {title: "Date", value: "Date"},
            {title: "Datetime", value: "Datetime"},
            {title: "BigDecimal",value: "BigDecimal"},
            {title: "Text", value: "Text"},
            {title: "Blob", value: "Blob"}
          ],
          defaultValue: "string",
          placeholder: "请选择${title}",
          props: {
            disabled: !this.actionButton
          },
          validateRules: [
            {required: true, message: "请选择${title}"},
            {handler: function (type, value, row, column, callback, target) {
                // type 触发校验的类型（input、change、blur、getValues）
                // value 当前校验的值
                // callback(flag, message) 方法必须执行且只能执行一次
                //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                //          message = 提示的消息，默认使用配置的 message
                // target 行编辑的实例对象
                if ("getValues" !== type) {
                  try{
                    self.getAllTable().then(function (tables) {
                      let table1 = tables[0];
                      let table2 = tables[1];

                      let fieldShowType = table2.$refs.editableTable.getValuesSync({validate: false, rowIds: [row.id]}).values[0].fieldShowType;

                      if ("date" !== fieldShowType && "datetime" !== fieldShowType) {
                        let aa = table2.$refs.editableTable.getValuesSync({validate: true, rowIds: [row.id]});
                        console.log(aa);
                      }
                      callback();
                    }).catch((function (e) {
                      callback(false, "校验出错")
                    }))
                  } catch (e) {
                    console.log(e)
                  }

                } else {
                  callback()
                }
              },message: "${title}校验失败"}
          ]
        },
        {
          title: "主键",
          key: "dbIsKey",
          width: "80px",
          type: FormTypes.checkbox,
          customValue: ["1", "0"],
          defaultChecked: false,
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "允许空值",
          key: "dbIsNull",
          width: "80px",
          type: FormTypes.checkbox,
          customValue: ["1", "0"],
          defaultChecked: true,
          props: {
            disabled: !this.actionButton
          }
        },
        {
          title: "排序",
          key: "orderNum",
          isOrder: true,
          type: FormTypes.hidden,
          defaultValue: 0
        }
      ],
      dataSource: [],

    }
  },
  // created: function () {
  //   this.jet = null
  // },
  // mounted: function () {
  //   // jeecg editableTable => jet
  //   this.jet = this.$refs.editableTable
  // },
  methods: {
    initialTable() {
      this.dataSource = []
      this.deleteIds = []
      this.selectedRowKeys = []
      this.$refs.editableTable.initialize()
    },
    handleAdded() {
      this.$emit("added", this)
    },
    handleDeleted() {
      this.$emit("deleted", this)
    },
    /**
     * 处理拖拽回调
     * @param {Object} item item结构-{oldIndex: string, newIndex: string, target: {}}
     */
    handleDragged(item) {
      // item 结构： {oldIndex: string, newIndex: string, target: {}}
      this.$emit("dragged", {
        oldIndex: item.oldIndex,
        newIndex: item.newIndex,
        target: this
      });
    },
    handleInserted(item) {
      this.$emit("inserted", {...item,...{target: this}})
    },
    handleValueChange(obj) {
      let type = obj.type
      let row = obj.row
      let column = obj.column
      let value = obj.value
      let target = obj.target;
      if (type === FormTypes.select && "dbType" === column.key) {
        // 同步数据库字段
        if (!("Date" !== value && "Datetime" !== value)) {
          this.$emit("syncDbType", {row: row, value: value, target: this})
        }
        // Blob、Text、Date、Datetime 字段长度设置为 0
        if ("Blob" === value || "Text" === value || "Date" === value || "Datetime" === value) {
          target.setValues([{rowKey: row.id, values: {dbLength: "0"}}])
        } else {
          // int double BigDecimal 字段长度为 10
          if ("int" === value || "double" === value || "BigDecimal" === value) {
            target.setValues([ {rowKey: row.id, values: { dbLength: "10" } } ])
          } else {
            // 字段长度为0 设置为32
            if ("0" === row["dbLength"]) {
              target.setValues([ { rowKey: row.id, values: { dbLength: "32" } } ])
            }
          }
        }
      }
    },
    tableAddLine(record) {
      this.$refs.editableTable.push(record)
      if (!this.addBatching) {
        this.$emit("added", this)
      }
    },
    tableDeleteLines(rowIds) {
      this.$refs.editableTable.removeRows(rowIds)
    },
    addBatchBegin() {
      this.addBatching = true
      this.loading = true
    },
    addBatchEnd() {
      this.addBatching = false
      this.loading = false
      this.$emit("added", this)
    }
  }
}
</script>

<style scoped>

</style>