<template>
  <div>
    <div>
      <el-form :model="formData" label-width="100px" label-position="left" style="width: 80%">
        <el-form-item label="一号表">
          <el-input v-model="reqDispData.db[0].dbTable" placeholder="请选择表" disabled />
        </el-form-item>
        <el-form-item label="二号表">
          <el-input v-model="reqDispData.db[1].dbTable" placeholder="请选择表" disabled />
        </el-form-item>
        <el-form-item label="连接方式">
          <el-select v-model="respDispData.join" placeholder="请选择连接方式">
            <el-option label="左连接" value="LEFT JOIN" />
            <el-option label="右连接" value="RIGHT JOIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接条件">
          <el-select v-model="respDispData.joinData.form.fieldName" placeholder="请选择一号表字段">
            <el-option v-for="item in reqDispData.fields[0]" :label="item.tableName+'.'+item.fieldName+'('+item.fieldComment+')'" :value="item.fieldName" />
          </el-select>
          &nbsp;&nbsp;
          <el-select v-model="respDispData.joinData.to.fieldName" placeholder="请选择二号表字段">
            <el-option v-for="item in reqDispData.fields[1]" :label="item.tableName+'.'+item.fieldName+'('+item.fieldComment+')'" :value="item.fieldName" />
          </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="disp.findFlag = false">返回</el-button>
            <el-button type="primary" @click="checkFields">下一步</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="选择字段" :visible.sync="checkFieldsFlag" width="70%" append-to-body>
      <el-table ref="table" :data="reqDispData.fieldList" height="450px"
                @row-click="clickRow" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column :show-overflow-tooltip="true" label="字段名称" prop="fieldName" />
        <el-table-column :show-overflow-tooltip="true" label="字段描述" prop="fieldComment" />
        <el-table-column :show-overflow-tooltip="true" label="字段类型" prop="fieldType" />
        <el-table-column :show-overflow-tooltip="true" label="字段所属表" prop="tableName" />
      </el-table>
      <br><br>
      <div align="center">
        <el-button @click="checkFieldsFlag = false">返回</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
// 例如：import 《组件名称》 from '《组件路径》,
import {listDisposition} from "@/api/quest/disposition";
import {selectDbTableColumnsByName} from "@/api/tool/gen";
import {batchAddUpd} from "@/api/quest/disposition";

export default {
  // import引入的组件需要注入到对象中才能使用"
  name: 'uniteFind',
  props: {
    data: {},
    node: {},
    disp: {
      nodeCode: undefined,
      nodeType: undefined,
      findFlag: false,
      updFlag: false,
      formData: {
        db: {},
        fields: []
      }
    }
  },
  data() {
    // 这里存放数据"
    return {
      reqDispData: {
        db: [],
        fields: [],
        fieldList: []
      },
      respDispData: {
        db: [],
        fields: [],
        join: '',
        joinData: {
          form: {},
          to: {}
        }
      },
      formData: {},
      checkFieldsFlag: false,
      i: 0
    }
  },
  // 计算属性 类似于data概念",
  computed: {},
  // 生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.init()
  },
  // 方法集合",
  methods: {
    init() {
      // 查询上级的所有节点
      /** 1.查询该节点的上一级节点*/
      let preNodeId = []
      this.data.lineList.forEach(line => {
        if (line.to === this.node.id){
          preNodeId.push(line.from)
        }
      })
      // 去重
      preNodeId = [...new Set(preNodeId)]
      preNodeId.push(this.node.id)
      /** 2.获取节点的配置参数*/
      if (preNodeId){
        preNodeId.forEach(id => {
          this.findDisp(id)
        })
      }
      /** 3.查询表字段 */
      console.log('reqDispData',this.reqDispData)
      console.log('respDispData',this.respDispData)

    },
    // 根据节点编码查询节点的配置参数
    findDisp(nodeCode) {
      listDisposition({nodeCode: nodeCode}).then(res => {
        if (!res.data.rows){
          return
        }
        let data = this.getVueDisp(res.data.rows);
        if (this.node.id === nodeCode){
          this.respDispData.db.push(data.db)
          this.respDispData.fields.push(data.fields)
          this.respDispData.join = data.join
        }else{
          this.reqDispData.db.push(data.db)
          this.reqDispData.fields.push(data.fields)
        }
      })
    },
    // 下一步按钮
    checkFields() {
      this.respDispData.db = this.reqDispData.db
      this.reqDispData.fieldList = []
      this.reqDispData.fieldList.push(...this.reqDispData.fields[0])
      this.reqDispData.fieldList.push(...this.reqDispData.fields[1])
      // 查询表字段
      this.reqDispData.fields[0].forEach(field => {
        if (this.respDispData.joinData.form.fieldName === field.fieldName){
          this.respDispData.joinData.form = field
        }
      })
      this.reqDispData.fields[1].forEach(field => {
        if (this.respDispData.joinData.to.fieldName === field.fieldName){
          this.respDispData.joinData.to = field
        }
      })
      this.checkFieldsFlag = true
    },
    // 保存选择
    save() {
      console.log('reqDispData',this.reqDispData)
      console.log('respDispData',this.respDispData)
      const dispList = this.getMysqlDisp(this.respDispData)
      batchAddUpd(dispList, this.disp.nodeCode).then(res => {
        this.$message.success(res.msg)
        this.checkFieldsFlag = false
      })
      // this.disp.findFlag = false
    },
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.respDispData.fields = selection.map(item => {
        return {
          tableName: item.tableName,
          fieldName: item.fieldName,
          fieldType: item.fieldType,
          fieldComment: item.fieldComment,
          fieldDesc: item.fieldDesc
        };
      });
    },
    /** 节点配置 类型转换 mysql -> vue */
    getVueDisp(dispList) {
      const db = {}
      const fields = []
      let tableName = ''
      let join = ''
      let joinData = {
        form: '',
        to: ''
      }
      dispList.forEach(disp => {
        if (disp.dispKey === 'db') {
          db.dbName = disp.dispValue
        }
        if (disp.dispKey === 'table') {
          db.tableName = disp.dispValue
          db.tableComment = disp.dispLabel
        }
        tableName = db.dbName+'.'+db.tableName
        db.dbTable = db.dbName+'.'+db.tableName+'('+db.tableComment +')'
        if (disp.dispKey === 'fields') {
          fields.push({
            tableName: tableName,
            fieldName: disp.dispValue,
            fieldType: disp.dispType,
            fieldComment: disp.dispLabel,
            fieldDesc: disp.fieldDesc
          })
        }
        if (disp.dispKey === 'joinDataForm') {
          joinData.form.push({
            tableName: tableName,
            fieldName: disp.dispValue,
            fieldType: disp.dispType,
            fieldComment: disp.dispLabel,
            fieldDesc: disp.fieldDesc
          })
        }
        if (disp.dispKey === 'joinDataTo') {
          joinData.to.push({
            tableName: tableName,
            fieldName: disp.dispValue,
            fieldType: disp.dispType,
            fieldComment: disp.dispLabel,
            fieldDesc: disp.fieldDesc
          })
        }
        if (disp.dispKey === 'join') {
          join = disp.dispValue
        }
      })
      if (join !== '') {
        return {db, fields, join, joinData}
      }
      return {db, fields}
    },
    /** 节点配置--unite 类型转换 vue -> mysql*/
    getMysqlDisp(resp) {
      const db = resp.db
      const table = resp.db
      const fields = resp.fields
      const join = resp.join
      const form = resp.joinData.form
      const to = resp.joinData.to
      // 处理数据库
      const dispList = []
      // 数据库
      db.forEach(item => {
        dispList.push({
          nodeCode: this.node.id, // 节点编码
          dispKey: 'db',  // 存储编码
          dispLabel: '数据库', // 显示名称
          dispValue: item.dbName, // 存储值
          dispType: 'string',  // 存储类型
          dispDesc: item.dbTable // 备注信息
        })
      })
      // 数据表
      table.forEach(item => {
        dispList.push({
          nodeCode: this.node.id,
          dispKey: 'table',
          dispLabel: item.tableComment,
          dispValue: item.tableName,
          dispType: 'string',
          dispDesc: item.dbName+'.'+item.tableName
        })
      })
      // 表结构
      fields.forEach(field => {
        dispList.push({
          nodeCode: this.node.id,
          dispKey: 'fields',
          dispLabel: field.fieldComment,
          dispValue: field.fieldName,
          dispType: field.fieldType,
          dispDesc: field.tableName
        })
      })
      // 连接方式
      dispList.push({
        nodeCode: this.node.id,
        dispKey: 'join',
        dispLabel: join,
        dispValue: join,
        dispType: 'String',
        dispDesc: ''
      })
      // 连接字段1
      dispList.push({
        nodeCode: this.node.id,
        dispKey: 'joinDataForm',
        dispLabel: form.fieldComment,
        dispValue: form.fieldName,
        dispType: form.fieldType,
        dispDesc: form.tableName
      })
      // 连接字段2
      dispList.push({
        nodeCode: this.node.id,
        dispKey: 'joinDataTo',
        dispLabel: to.fieldComment,
        dispValue: to.fieldName,
        dispType: to.fieldType,
        dispDesc: to.tableName
      })

      return dispList
    }

  }
}
</script>
<style scoped>

</style>
