<template>
  <ed-dialog v-model="dialogVisible" :close-on-press-escape="true" :fullscreen="fullscreen" :showFooter="false"
               title="表属性管理">
    <el-form ref="tableInfoForm" :inline="true" :model="tableInfoForm" :rules="rules" class="demo-form-inline">
      <el-card class="es-box-card">
        <div slot="header" class="es-box-card--header">
          <span>表信息</span>
          <div class="es-card-header-operate">
            <el-button :loading="loading" icon="el-icon-document-add" type="primary" @click="saveTableInfo">保存
            </el-button>
          </div>
        </div>

        <el-form-item :rules="[{required: true, message: '请输入表名称', trigger: 'blur'}]" label="表名称" prop="tableName">
          <el-input v-model="tableInfoForm.tableName" :disabled="isExistTable" placeholder="表名称"
                    style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="表备注" label-width="300px" prop="remark">
          <el-input v-model="tableInfoForm.remark" placeholder="表备注" style="width:300px"></el-input>
        </el-form-item>
      </el-card>

      <el-card class="es-box-card es-box-card--top">
        <div slot="header" class="es-box-card--header">
          <span>虚拟列信息</span>
          <div>
            <el-button :loading="loading" icon="el-icon-plus" plain type="primary" @click="addVirtualColumns">添加
            </el-button>
          </div>
        </div>
        <el-table ref="virtualTable" :data="tableInfoForm.tableData" :height="350" :loading="loading" row-key="id" style="width: 100%">
          <el-table-column label="#" type="index" key="index"></el-table-column>

          <el-table-column v-for="(column, index) in tableColumns" :key="index" :label="column.label"
                           :prop="column.prop">
            <template v-slot:default="{row, $index}">
              <el-form-item :prop="`tableData[${$index}].${column.prop}`" :rules="rules[column.prop]">
                <template v-if="column.slots === 'operate'">
                  <el-button style="color: red" type="text" @click="deleteRow(row, $index)">删除</el-button>
                </template>

                <component :is="column.tags" v-else v-model="row[column.prop]" :placeholder="column.placeholder"
                           v-on="column.on">
                  <template v-if="column.hasOwnProperty('options')">
                    <el-option
                      v-for="(item, index) in column.options"
                      :key="index"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </template>
                </component>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="es-box-card es-box-card--top" style="margin-top: 15px">
        <div slot="header" class="es-box-card--header">
          <span>表SQL信息</span>
          <div>
            <el-button :loading="loading" icon="el-icon-plus" plain type="primary"
                       @click="tableInfoForm.sqlData.push({})">
              添加
            </el-button>
          </div>
        </div>
        <el-table v-loading="loading" :data="tableInfoForm.sqlData" :loading="loading" row-key="id" style="width: 100%">
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="sqlId" prop="sqlId">
            <template slot-scope="scope">
              <el-form-item :prop="`sqlData[${scope.$index}].sqlId`" :rules="rules.sqlId" style="margin-top: 3px">
                <el-input v-model="scope.row.sqlId" placeholder="sqlId"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="sql内容" prop="sqlId">
            <template slot-scope="scope">
              <el-form-item :prop="`sqlData[${scope.$index}].sqlContent`" :rules="rules.sqlContent"
                            style="margin-top: 3px">
                <el-input v-model="scope.row.sqlContent" autosize placeholder="sql内容" style="width:300px"
                          type="textarea"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="action">
            <template slot-scope="scope">
              <el-button slot="reference" style="color: red" type="text" @click="deleteSqlRow(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>
  </ed-dialog>
</template>

<script>
import ds from '../../../../api/ds'
export default {
  name: "TablePropsModal",
  data() {
    const validateFieldName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('必填'));
      }
      let arr = ['id', 'key_info', 'data_info', 'create_time', 'update_time', 'insert_user', 'insert_user_name', 'insert_org', 'select', 'insert', 'update', 'orgCode', 'updater', 'creator']
      let index = arr.indexOf(value)
      if (index > -1) {
        this.$message.error(`不能使用 ${value} 作为字段名称`)
        return callback(new Error(`不能使用 ${value}' 作为字段名称`));
      }
      callback();
    };
    return {
      dialogVisible: false,
      loading: false,
      isExistTable: false,
      fullscreen: true,
      deleteIds: [],
      deleteSqlIds: [],
      dataSourceId: '',
      isGeneralColumn: 0,

      tableInfoForm: {id: '', tableData: [], sqlData: []},
      rules: {
        fieldName: [
          {validator: validateFieldName, trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '必填', trigger: 'blur'},
        ],
        length: [
          {required: true, message: '必填', trigger: 'blur'},
        ],
        dataType: [
          {required: true, message: '必选', trigger: 'change'},
        ],
        sqlId: [
          {required: true, message: '必填', trigger: 'blur'},
        ],
        sqlContent: [
          {required: true, message: '必填', trigger: 'blur'},
        ],
      },
      options: [ // 下拉选项
        {label: 'varchar', value: 'VARCHAR'},
        {label: 'integer', value: 'INTEGER'},
        {label: 'bigint', value: 'BIGINT'},
        {label: 'jsontext', value: 'JSONTEXT'},
        {label: 'longtext', value: 'LONGTEXT'},
        {label: 'datetime', value: 'DATETIME'},
      ],
    }
  },
  computed: {
    tableColumns() {
      let columns = [
        {
          label: "字段名称",
          prop: 'fieldName',
          tags: 'EdInputPop',
          placeholder: '字段名称'
        },
        {
          label: "长度",
          prop: 'length',
          tags: 'el-input',
          placeholder: '长度',
          on: {
            input: (value) => value.replace(/[^0-9]/g, '')
          }
        },
        {
          label: "字段类型",
          prop: 'dataType',
          tags: 'el-select',
          placeholder: '字段类型',
          options: [ // 下拉选项
            {label: 'varchar', value: 'VARCHAR'},
            {label: 'integer', value: 'INTEGER'},
            {label: 'bigint', value: 'BIGINT'},
            {label: 'jsontext', value: 'JSONTEXT'},
            {label: 'longtext', value: 'LONGTEXT'},
            {label: 'datetime', value: 'DATETIME'},
          ]
        },
        {
          label: "备注",
          prop: 'remark',
          tags: 'EdInputPop',
          placeholder: '备注'
        },
        {
          label: "虚拟列表达式",
          prop: 'expression',
          tags: 'EdInputPop',
          placeholder: '虚拟列表达式',
        },
        {
          label: "是否唯一",
          prop: 'isUnique',
          tags: 'el-switch'
        },
        {
          label: "组合唯一索引",
          prop: 'isAllUnique',
          tags: 'el-switch'
        },
        {
          label: "是否索引",
          prop: 'isIndex',
          tags: 'el-switch'
        },
        {
          label: "启用存储模式",
          prop: 'isStored',
          tags: 'el-switch'
        },
        {
          label: "操作",
          prop: 'isIndex',
          slots: "operate",
        },
      ]
      if(this.isGeneralColumn == 1) {
        columns.splice(4,1)
        columns.splice(7,1)
      }
      return columns
    }
  },
  methods: {
    showModal(record) {
      this.tableInfoForm = {tableData: [], sqlData: []}
      this.dataSourceId = record.id
      this.isGeneralColumn = record.isGeneralColumn

      this.isExistTable = false
      const param = {dataSourceId: record.id}
      ds.getTableInfoByDsId(param).then((resp) => {
        if (resp.success) {
          if (resp.data) {
            this.tableInfoForm = Object.assign({}, this.tableInfoForm, resp.data)
            this.isExistTable = resp.data.isExistTable
            this.getFieldListByDsId(param)
            this.getSqlIdList(param)
          }
        }
      }).finally(() => {
        this.dialogVisible = true
      })

    },
    saveTableInfo() {
      this.$refs['tableInfoForm'].validate((valid) => {
        if (valid) {
          const tableData = this.tableInfoForm.tableData
          if (tableData) {
            let names = tableData.map(item => item["fieldName"]);
            let nameSet = new Set(names);
            if (nameSet.size !== names.length) {
              this.$message.error("存在重复字段名称,请检查!")
              return
            }
          }
          this.loading = true
          let params = Object.assign({dataSourceId: this.dataSourceId}, this.tableInfoForm);
          ds.addTableInfo(params).then(async (resp) => {
            this.tableInfoForm.id = resp.data.id
            if (resp.success) {
              let formData = {
                fieldInfos: this.tableInfoForm.tableData,
                deleteIds: this.deleteIds,
                dataSourceId: this.dataSourceId
              }
              const resp = await ds.addFieldModel(formData)
              if (resp.success) {
                await this.getFieldListByDsId({dataSourceId: this.dataSourceId})
                let formData = {
                  tableSqls: this.tableInfoForm.sqlData,
                  deleteIds: this.deleteSqlIds,
                  dataSourceId: this.dataSourceId
                }
                ds.addSqlIdInfo(formData).then((resp) => {
                  if (resp.success) {
                    this.getSqlIdList({dataSourceId: this.dataSourceId})
                    this.$message.success(resp.msg || "操作成功!")
                  }
                }).finally(() => {
                  this.loading = false
                })
              }
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    deleteRow(row, $index) {
      if (row.id) {
        this.deleteIds.push(row.id)
      }
      this.tableInfoForm.tableData.splice($index, 1)
    },
    deleteSqlRow(data) {
      if (data.row.id) {
        this.deleteSqlIds.push(data.row.id)
      }
      this.tableInfoForm.sqlData.splice(data.$index, 1)
    },
    async getFieldListByDsId(param) {
      const resp = await ds.getFieldListByDsId(param)
      if (resp.success) {
        if (resp.data) {
          this.tableInfoForm.tableData = resp.data
        }
      }
    },
    async getSqlIdList(param) {
      const resp = await ds.getSqlIdList(param)
      if (resp.success) {
        if (resp.data) {
          this.tableInfoForm.sqlData = resp.data
        }
      }
    },
    // 添加虚拟列
    addVirtualColumns() {
      this.tableInfoForm.tableData.push({
        length: 100,
        dataType: 'VARCHAR',
        isUnique: false,
        isStored: false,
        isIndex: false,
        isAllUnique: false
      })

      this.searchMember()
    },

    //跳转表格指定位置
    searchMember() {
      let length = this.tableInfoForm.tableData.length
      let scrollTop = this.$refs.virtualTable.bodyWrapper.scrollTop
      let top = Math.floor(scrollTop / 52)
      // 实现滚动效果
      const timeTop = setInterval(() => {
        top++;
        this.$refs.virtualTable.bodyWrapper.scrollTop = 52 * top;
        if (top >= length) {
          clearInterval(timeTop)
        }
      }, 10)
    },
    validateFieldName() {

    }
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 3px;
}
</style>
