<template>
  <div class="page">
    <!-- <header>
      <i class="el-icon-arrow-left"
         @click="goBack"></i>
      外键管理—{{status}}
    </header> -->
    <el-form ref="form"
             class="form"
             :model="form"
             :rules="rules"
             label-width="100px">
      <el-form-item label="主表名"
                    prop="mainTableName"
                    class="dataItem">
            <el-select size="small"
                        clearable
                        filterable
                        v-model="form.mainTableName"
                        :disabled="code === 'edit' || code === 'show'"
                        @change="changeMainTable"
                        placeholder="请选择主表">
                <el-option v-for="(item, index) in tableData"
                        :key="index"
                        :disabled="form.foreignTableName === item.tableName"
                        :label="item.tableName"
                        :value="item.tableName">
                </el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="从表名"
                    prop="foreignTableName"
                    class="dataItem">
        <el-select size="small"
                        clearable
                        filterable
                        v-model="form.foreignTableName"
                        :disabled="code === 'edit' || code === 'show'"
                        @change="changeForeignTable"
                        placeholder="请选择从表">
                <el-option v-for="(item, index) in tableData"
                        :key="index"
                        :disabled="form.mainTableName === item.tableName"
                        :label="item.tableName"
                        :value="item.tableName">
                </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主键"
                    prop="mainField"
                    class="dataItem">
        <el-select size="small"
                    clearable
                    filterable
                    :disabled="code === 'edit' || code === 'show'"
                    v-model="form.mainField"
                    placeholder="请选择主键">
            <el-option v-for="(item, index) in mainTableField"
                    :key="index"
                    :label="item.fieldName"
                    :value="item.fieldName">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="外键"
                    prop="foreignField"
                    class="dataItem">
        <el-select size="small"
                    clearable
                    filterable
                    :disabled="code === 'edit' || code === 'show'"
                    v-model="form.foreignField"
                    placeholder="请选择从键">
            <el-option v-for="(item, index) in foreignTableField"
                    :key="index"
                    :label="item.fieldName"
                    :value="item.fieldName">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联名"
                    prop="relateName"
                    class="dataItem">
        <el-input v-model="form.relateName"
                  :disabled="isShow"
                  size="small"></el-input>
      </el-form-item>
      <el-form-item label="是否已创建"
                    prop="isCrt"
                    class="dataItem">
        <el-select size="small"
                   v-model="form.isCrt"
                   :disabled="isShow"
                   class="dataItem">
          <el-option v-for="item in yesOrNo"
                     :key="item.index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联描述"
                    prop="relateDesc"
                    class="dataRow">
        <el-input v-model="form.relateDesc"
                  :disabled="isShow"
                  size="small"></el-input>
      </el-form-item>
      <el-form-item label="关联类型"
                    prop="relateType"
                    class="dataItem">
        <el-select size="small"
                   v-model="form.relateType"
                   :disabled="isShow"
                   class="dataItem">
          <el-option v-for="item in correlationClassList"
                     :key="item.index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="对多关系"
                    prop="corrType"
                    class="dataItem">
        <el-select size="small"
                   v-model="form.corrType"
                   :disabled="isShow"
                   class="dataItem">
          <el-option v-for="item in slaveTableList"
                     :key="item.index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="searchButton"
           v-if="!isShow">
        <el-button type="primary"
                   @click="saveData"
                   size="small"
                   icon="el-icon-document">保存</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import qs from 'qs';
import { checkCharLength,
        checkCharLength2,
        checkCharNoChinese,
        checkCharNoChinese2,
        checkCharNoChinese3,
        checkChar,
        checkChinese,
        checkURL} from '@/utils/validator.js';
export default {
    props: {
        code: String,
        item: Object,
        dialogColose: {
            type: Boolean
        }
    },
  data () {
    return {
      isShow: false,
      status: '查看',
      form: {
        id: '',
        tableRelateId: '',
        tableId: '',
        relateName: '',
        relateDesc: '',
        relateType: '',
        mainTableId: '',
        mainTableName: '',
        mainField: '',
        foreignTableId: '',
        foreignTableName: '',
        foreignField: '',
        corrType: '',
        isCrt: '',
        crtUserCode: '',
        crtOrgCode: '',
        crtDate: '',
        updUserCode: '',
        updOrgCode: '',
        updDate: '',
        mdTableRelate: ''
      },
      yesOrNo: [{
        label: '是',
        value: '1'
      }, {
        label: '否',
        value: '0'
      }],
      // primaryTableList: [{
      //   label: '表1',
      //   value: 'table1'
      // }, {
      //   label: '表2',
      //   value: 'table2'
      // }],
      rules: {
            mainTableName: [
                { required: true, message: '请选择主表', trigger: 'blur' }
            ],
            foreignTableName: [
                { required: true, message: '请选择从表', trigger: 'blur' }
            ],
            mainField: [
                { required: true, message: '请选择主键', trigger: 'blur' }
            ],
            foreignField: [
                { required: true, message: '请选择外键', trigger: 'blur' }
            ],
            isCrt: [
                { required: true, message: '请选择是否创建', trigger: 'blur' }
            ],
            relateType: [
                { required: true, message: '请选择关联类型', trigger: 'blur' }
            ],
            corrType: [
                { required: true, message: '请选择对多关系', trigger: 'blur' }
            ],
            relateName: [
                { validator: checkCharLength, max: 100, trigger: 'change' },
                { validator: checkChar, trigger: 'change' }
            ],
            relateDesc: [
                { validator: checkCharLength, max: 200, trigger: 'change' },
                { validator: checkChar, trigger: 'change' }
            ]
        },
      slaveTableList: [{
        label: '1对1',
        value: '1'
      }, {
        label: '1对多',
        value: '2'
      }, {
        label: '多对多',
        value: '3'
      }],
      correlationClassList: [{
        label: '左外关联',
        value: '1'
      }, {
        label: '右外关联',
        value: '2'
      }, {
        label: '内关联',
        value: '3'
      }],
      tableData: [],
      mainTableField: [],
      foreignTableField: []
    }
  },
  mounted: function () {
      this.clearForm();
      this.queryTable();
        if (this.code === 'show') {
            this.isShow = true;
            this.status = '查看'
            this.setForm(this.item)
        } else if (this.code === 'add') {
            this.status = '新增';
        } else {
            this.status = '修改';
            this.isEdit = true;
            this.setForm(this.item)
        }
  },
  watch: {
        code: function (newValue) {
            this.clearForm();
            if (newValue) {
                if (this.code === 'show') {
                    this.isShow = true;
                    this.status = '查看'
                    this.setForm(this.item)
                } else if (this.code === 'add') {
                    this.status = '新增';
                } else {
                    this.status = '修改';
                    this.isEdit = true;
                    this.setForm(this.item);
                    this.getTableField(this.item.mainTableName, 1)
                    this.getTableField(this.item.foreignTableName)
                }
            } else {
                this.isShow = false;
            }
        }
    },
  methods: {
    goBack () {
      this.$router.go(-1)
    },
    setForm (data) {
      let that = this;
      for (let i in that.form) {
        that.form[i] = data[i]
      }
    },
    saveData () {
      let that = this;
      this.$refs['form'].validate((valid) => {
        if (valid) {
            if (that.form.id) {
                that.axios.put('pass/v1/mdtablerelates/' + that.form.id, that.form).then(function (response) {
                    if (response.code === '0') {
                        that.$message.success('编辑成功');
                        that.$emit('save', response.data);
                        that.clearForm();
                    } else {
                        that.$message.error(response.message);
                    }
                }).catch(function () {
                    that.clearForm();
                });
            } else {
                delete that.form.id;
                that.axios.post('pass/v1/mdtablerelates/', that.form).then(function (response) {
                    if (response.code === '0') {
                        that.$message.success('新增成功');
                        that.$emit('add', response.data);
                        that.clearForm();
                    } else {
                        that.$message.error(response.message);
                    }
                }).catch(function () {
                    that.clearForm();
                });
            }
        }
      })
    },
    // 获取表
    queryTable: function () {
      let that = this,
        defaultParms = {
          pageSize: 1000,
          pageNum: 1
        },
        params = defaultParms,
        getUrl = 'pass/v1/mdtables/';
      that.axios.get(getUrl, {
        params: params
      }
      ).then(function (response) {
        if (response) {
          let data = response.data;
          that.tableData = data.list;
        }
      }).catch(function () {
      });
    },
    clearForm () {
        for (let item in this.form) {
            this.form[item] = ''
        }
        this.form['status'] = '1'
    },
    changeMainTable (val) {
        this.getTableField(val, 1)
    },
    changeForeignTable (val) {
        this.getTableField(val)
    },
    // 获取字段
    getTableField (tableName, type) {
      let that = this,
        defaultParms = {
          pageSize: 10000,
          pageNum: 1,
          tableName: tableName,
          tableCnName: '',
          fieldName: '',
          fieldCnName: '',
          isPk: ''
        },
        params = defaultParms,
        getUrl = 'pass/v1/mdfields/';
      that.tableLoading = true;
      that.axios.get(getUrl, {
        params: params
      }
      ).then(function (response) {
        if (response) {
          let data = response.data;
          if (type) {
              that.mainTableField = data.list;
          } else {
              that.foreignTableField = data.list;
          }
        }
        that.tableLoading = false;
      }).catch(function () {
        that.tableLoading = false;
      });
    }
  }
}
</script>
<style scoped>
.page {
  padding: 10px;
}
header {
  width: 100%;
  height: 50px;
  background: rgb(248, 248, 248);
  padding-left: 60px;
  font-size: 15px;
  color: #000;
  line-height: 50px;
  position: relative;
}
header i {
  display: block;
  width: 50px;
  height: 50px;
  position: absolute;
  left: 0;
  top: 0;
  text-align: center;
  line-height: 50px;
  font-size: 25px;
  cursor: pointer;
}
header i:hover {
  color: #70baf2;
}
.form {
  width: 100%;
  height: auto;
  padding: 10px 0;
  text-align: left;
}
.dataItem {
  width: 48%;
  display: inline-block;
}
.el-select--small {
  width: 100% !important;
}
.dataRow {
  width: 96.4%;
}
.searchButton {
  width: 100%;
  text-align: center;
}
.searchButton button {
  display: inline-block;
}
</style>
