<template>
  <div class="table">
    <h2 class="title">数据库表配置</h2>
    <TableFromHeader @changeColData="changeColData" @changeTableName="changeTableName"></TableFromHeader>
    <el-button type="text" @click="add()">关联表</el-button>
    <el-table
        :data="tableData.tableColEntityList"
        style="width: 100%;max-height: 600px;overflow: auto">
      <el-table-column align="center"
                       prop="colName"
                       label="列名称"
                       width="150">
      </el-table-column>
      <el-table-column align="center"
                       prop="chinaName"
                       label="展示中文名"
                       width="150">
        <template slot-scope="scope">
          <el-input v-model="scope.row.chinaName" placeholder="请输入内容"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="date"
          label="属性类型"
          width="150">
        <template slot-scope="scope">
          <el-select v-model="scope.row.paramType" placeholder="请选择">
            <el-option
                v-for="item in paramType"
                :key="item.value"
                :label="item.value"
                :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="name"
          label="查询配置"
          width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.compareType" placeholder="请选择">
            <el-option
                v-for="item in compareType"
                :key="item.value"
                :label="item.value"
                :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="搜索" width="80" align="center">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.searchShow"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="表格展示" width="80" align="center">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.tableShow"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="name"
          label="显示类型"
          width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.showType" @change="tableTypeChange(scope.row)" placeholder="请选择">
            <el-option
                v-for="item in showType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="编辑展示" width="80" align="center">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.updateShow"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          prop="name"
          label="编辑类型"
          width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.updateType" @change="updateTypeChange(scope.row)" placeholder="请选择">
            <el-option
                v-for="item in updateType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="图片上传" width="80" align="center">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.uploadImg"></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <div class="my-button">
      <el-button @click="goHome">上一步</el-button>
      <el-button @click="submitMainFrom">确认</el-button>
    </div>
    <div>
      <el-select v-model="type" @change="updateModuleType" placeholder="请选择">
        <el-option
            v-for="item in updateModuleTypeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div class="my-button">
      <el-button @click="generateCode" type="success">生成代码</el-button>
    </div>
    <AddSonTable :dialogVisible=addSonTableDialog @dismissDialog="close" :col-data="currentColData"
                 :table-name="tableData.tableName" @addSonTableList="addSonTableList"></AddSonTable>

    <el-dialog
        title="数据来源"
        :visible.sync="dialogVisible"
        width="50%"
    >
      <TableFromHeader :showName="false" @changeColData="selectColName"></TableFromHeader>
      <el-form>
        <el-form-item label="字段">
          <el-select v-model="dataSource.tableFiled" @change="updateFileChange" placeholder="请选择">
            <el-option
                v-for="item in colName"
                :key="item.colName"
                :label="item.colName"
                :value="item.colName">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
        title="下拉选择配置"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="selectDialogVisible"
        width="50%">
      <el-form :model="selectDataParam" label-width="100px" inline>
        <TableFromHeader @changeColData="changeSwitchTableName" lable="数据来源表" :showName="false"></TableFromHeader>
        <el-form-item label="name列">
          <el-select v-model="selectDataParam.nameCol" @change="updateFileChange" placeholder="请选择">
            <el-option
                v-for="item in selectDataFromTableCol"
                :key="item.colName"
                :label="item.chinaName"
                :value="item.colName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="value列">
          <el-select v-model="selectDataParam.valueCol" @change="updateFileChange" placeholder="请选择">
            <el-option
                v-for="item in selectDataFromTableCol"
                :key="item.colName"
                :label="item.chinaName"
                :value="item.colName">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="selectDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitSelectForm">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="枚举来源"
        :visible.sync="dialogEnumVisible" width="50%">
      <el-form :model="addEnumForm" ref="addEnumForm" label-width="100px" inline>
        <div v-for="(domain, index) in addEnumForm.enums">
          <el-form-item
              :label="'枚举值-' + index"
              :key="domain.key"
              :prop="'enums.' + index + '.name'"
              :rules="{
            required: true, message: '枚举key不能为空', trigger: 'blur'}">
            <el-input v-model="domain.name"></el-input>
          </el-form-item>
          <el-form-item
              :label="'中文解释-' + index"
              :key="domain.key1"
              :prop="'enums.' + index + '.value'"
              :rules="{required: true, message: '枚举value不能为空', trigger: 'blur'}">
            <el-input v-model="domain.value"></el-input>
          </el-form-item>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </div>
        <el-form-item>
          <el-button @click="addDomain">新增枚举</el-button>
          <el-button @click="resetForm('addEnumForm')">重置</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogEnumVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitForm('addEnumForm')">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
import {message} from "../util/notice";
import {get, post} from "../util/http";
import AddSonTable from "../components/AddSonTable";
import TableFromHeader from "../components/TableFromHeader";

export default {
  components: {AddSonTable, TableFromHeader},
  data() {
    return {
      random: '',
      paramType: [
        {value: "String"},
        {value: "Boolean"},
        {value: "Long"},
        {value: "Integer"}
      ],
      compareType: [
        {value: "="},
        {value: "like"},
        {value: "eq"},
        {value: "nt"}
      ],
      showType: [
        {label: "文本", value: 'text'},
        {label: "枚举", value: 'enum'},
        {label: "图片", value: 'image'}
      ],
      updateModuleTypeArr: [
        {label: "vue-element-admin", value: '1'},
        {label: "vue", value: '2'},
        {label: "layui+html", value: '3'}
      ],
      type: 1,
      updateType: [
        {label: "文本", value: 'text'},
        {label: "开关", value: 'switch'},
        {label: "枚举", value: 'enum'},// 作为单选框组
        {label: "下拉选择", value: 'select'},
        {label: "数字", value: 'number'},
        {label: "日期选择", value: 'date'},
        {label: "文本域", value: 'textArea'},
      ],
      tableData: {
        tableComment: "",
        tableName: '',
        tableColEntityList: [],
        sonTableEntities: [],
        enumsEntities: [],
        selectEntities: [],
        tableEnumsEntities: []
      },
      correlationList: [],
      sonTableEntities: [],
      addSonTableDialog: false,
      // 当前列数据
      currentColData: {},
      dialogVisible: false,
      dialogEnumVisible: false,
      selectDialogVisible: false,
      colName: [],
      // 下拉框数据来源对象
      dataSource: {
        tableName: '',
        tableFiled: ''
      },
      addEnumForm: {
        enums: [{
          name: '',
          value: ''
        }]
      },
      currentCol: '',// 当前列
      // 开关相关
      addSwitchForm: {},
      // 下拉选择相关
      selectDataFromTableCol: [],
      selectDataParam: {
        fromTableName: '',
        nameCol: '',
        valueCol: ''
      }
    }
  },
  mounted() {
    let random = localStorage.getItem("random");
    if (!random) {
      message("数据库连接信息有误,请重新配置", "error");
      this.goHome();
      return;
    }
    this.random = random;
  },
  methods: {
    goHome() {
      this.$router.push("/");
    },
    close(obj) {
      this.addSonTableDialog = false;
    },
    add() {
      if (this.tableData.tableColEntityList.length <= 0) {
        message("请先选择主表!", "error")
        return
      }
      this.addSonTableDialog = true
    },
    changeColData(obj) {
      this.tableData = []
      this.tableData = obj.res;
      this.tableData.tableName = obj.name;
    },
    changeTableName(obj) {
      this.tableData.tableComment = obj.name;
    },
    changeSwitchTableName(obj) {
      this.selectDataParam.fromTableName = obj.name
      this.selectDataFromTableCol = obj.res.tableColEntityList
    },
    updateTypeChange(obj) {
      localStorage.setItem("type", 1)
      this.currentCol = obj.colName
      if (obj.updateType == "select") {
        this.selectDialogVisible = true
      }
      if (obj.updateType == 'enum') {
        this.dialogEnumVisible = true;
      }
    },
    tableTypeChange(obj) {
      localStorage.setItem("type", 2)
      this.currentCol = obj.colName
      if (obj.showType == 'enum') {
        this.dialogEnumVisible = true;
      }
    },
    selectColName(obj) {
      if (this.tableData.tableName == obj.name) {
        this.colName = [];
        message("数据表来源不能是当前表！", "error")
        return;
      }
      this.dataSource.tableName = obj.name;
      this.colName = obj.res.tableColEntityList;
    },
    updateFileChange(obj) {
      // console.log(this.dataSource)
    },
    submitSelectForm() {
      if (this.selectDataParam.fromTableName && this.selectDataParam.nameCol && this.selectDataParam.valueCol) {
        this.selectDataParam.colName = this.currentCol
        if (this.tableData.selectEntities && this.tableData.selectEntities.length > 0) {
          this.tableData.selectEntities.push(this.selectDataParam)
        } else {
          let arr = []
          arr.push(this.selectDataParam)
          this.tableData.selectEntities = arr
        }
      }
      this.selectDataParam = {}
      this.selectDialogVisible = false
    },
    submitForm(formName) {
      let type = localStorage.getItem("type")
      let that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {};
          param.colName = that.currentCol
          param.enumsDTOS = that.addEnumForm.enums
          if (type == 1) {
            if (that.tableData.enumsEntities && that.tableData.enumsEntities.length > 0) {
              that.tableData.enumsEntities.push(param)
            } else {
              let arr = []
              arr.push(param)
              that.tableData.enumsEntities = arr
            }
          } else {
            if (that.tableData.tableEnumsEntities && that.tableData.tableEnumsEntities.length > 0) {
              that.tableData.tableEnumsEntities.push(param)
            } else {
              let arr = []
              arr.push(param)
              that.tableData.tableEnumsEntities = arr
            }
          }
          message("枚举添加成功！", "success")
          that.dialogEnumVisible = false;
          that.addEnumForm.enums = []
          localStorage.removeItem("type")
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    removeDomain(item) {
      var index = this.addEnumForm.enums.indexOf(item)
      if (index !== -1) {
        this.addEnumForm.enums.splice(index, 1)
      }
    },
    addDomain() {
      this.addEnumForm.enums.push({
        value: '',
        name: "",
        key: Date.now(),
        key1: Date.now() + 1
      });
    },
    submitMainFrom() {
      this.tableData.correlationList = this.correlationList
      this.tableData.sonTableEntities = this.sonTableEntities
      let random = localStorage.getItem("random")
      var that = this;
      post("/table/" + random, this.tableData).then(res => {
        that.correlationList = []
        message("配置成功!", "success");
      })
    },

    addSonTableList(param) {
      let obj = param.tableData
      this.addSonTableDialog = false
      if (obj && obj.tableName) {
        message("子表添加成功！")
        if (this.sonTableEntities.length > 0) {
          this.checkObjExist(obj);
        }
        if (this.correlationList.length > 0) {
          this.checkCorrelationExist(param.correlation);
        }
        this.correlationList.push(param.correlation)
        this.sonTableEntities.push(obj)
      }
    },
    // 校验数据在数据中是否存在
    checkObjExist(obj) {
      for (let i in this.sonTableEntities) {
        let item = this.sonTableEntities[i]
        if (item.tableName == obj.tableName) {
          this.sonTableEntities.splice(i, 1)
        }
      }
    },
    checkCorrelationExist(obj) {
      for (let i in this.correlationList) {
        let item = this.correlationList[i]
        if (item == obj) {
          this.correlationList.splice(i, 1)
        }
      }
    },
    updateModuleType(e) {
      this.type = e
    },
    generateCode() {
      let random = localStorage.getItem("random")

      let url = "/generator/" + random + "/" + this.type
      get(url).then(res => {
        console.log(res)
      })
    }
  }
}
</script>
<style scoped>
.title {
  height: 50px;
  line-height: 50px;
}

.my-button {
  margin-top: 20px;
}
</style>
