<template>
  <div>
      <el-form label-position="right" label-width="60px">
        <el-form-item label="输入表">
          <span v-for="db in formDb">
            <el-input v-model="db.dbTable" placeholder="无输入表" style="width: 60%;" disabled />
          </span>
        </el-form-item>
        <el-form-item label="输出表">
          <el-input v-model="toDb.dbTable" placeholder="无输出表" style="width: 60%;" disabled />
        </el-form-item>
      </el-form>
    <div>
      <el-button icon="el-icon-refresh-right" type="text" @click="init">刷新</el-button>
      <el-button icon="el-icon-setting" type="text" @click="checkFields">更改</el-button>
    </div>
    <div align="center">
        <el-table ref="table" :data="formFields" height="450px">
          <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-column :show-overflow-tooltip="true" label="输出字段">
            <span slot-scope="scope" v-if="fieldsList && fieldsList.get(scope.row.fieldName)">
              {{ fieldsList.get(scope.row.fieldName).fieldName+ '(' + fieldsList.get(scope.row.fieldName).fieldComment + ')' }}
            </span>
          </el-table-column>
        </el-table>
    </div>
    <div align="center">
      <el-button @click="disp.findFlag = false">返回</el-button>
      <el-button type="primary" @click="disp.findFlag = false">确认</el-button>
    </div>

    <el-dialog title="选择输出表" :visible.sync="checkFieldsFlag" width="60%" :modal="false">
      <div style="padding-left: 10px;padding-right: 10px;">
        <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
          <el-form-item label="数据库名称" prop="dbName">
            <el-select v-model="queryParams.dbName" placeholder="请选择数据库" clearable @change="handleQuery">
              <el-option v-for="item in dbNameOptions" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
          <el-form-item label="表名称" prop="tableName">
            <el-input
              v-model="queryParams.tableName"
              clearable
              @change="handleQuery"
              placeholder="请输入表名称" />
          </el-form-item>
          <el-form-item label="表描述" prop="tableComment">
            <el-input
              v-model="queryParams.tableComment"
              clearable
              @change="handleQuery"
              placeholder="请输入表描述" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">查找</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="table" :data="tableOptions" height="300px">
          <el-table-column :show-overflow-tooltip="true" label="表名称" prop="tableName" />
          <el-table-column :show-overflow-tooltip="true" label="表描述" prop="tableComment" />
          <el-table-column label="操作" width="50px">
            <template slot-scope="scope">
              <el-button type="text" @click="selectTable(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider content-position="left">选择字段 v</el-divider>
        <el-table ref="table" :data="fieldsOptions" height="280px"
                  @row-click="clickRow" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column :show-overflow-tooltip="true" label="字段名称" prop="columnName" />
          <el-table-column :show-overflow-tooltip="true" label="字段描述" prop="columnComment" />
          <el-table-column :show-overflow-tooltip="true" label="字段类型" prop="columnType" />
        </el-table>
        <br><br>
        <div align="center">
          <el-button @click="checkFieldsFlag = false">取 消</el-button>
          <el-button type="primary" @click="checkFieldsFlag = false;checkFieldsMapFlag = true">下一步</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="选择字段" :visible.sync="checkFieldsMapFlag" width="60%" :modal="false">
      <div style="padding-left: 10px;padding-right: 10px;">
        <el-table ref="table" :data="formFields" height="500px">
          <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-column :show-overflow-tooltip="true" label="清洗规则" prop="ruleId">
            <template slot-scope="scope">
                <el-cascader :options="ruleOptions.filter(item => item.ruleVersionType === 'field')" :props="props" @change="checkRules" style="width: 60%;">
                  <template slot-scope="{ node, data }">
                    <span>{{ data.ruleVersionName }}</span>
                    <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                  </template>
                </el-cascader>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="目标字段">
            <template slot-scope="scope">
              <el-select v-model="scope.row.toFidlesName" placeholder="请选择字段">
                <el-option v-for="field in toFields" :label="field.fieldName+'('+field.fieldComment+')'" :value="field.fieldName"/>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <div align="center">
          <el-button @click="checkFieldsMapFlag = false;checkFieldsFlag = true;">上一步</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  // import引入的组件需要注入到对象中才能使用"
  name: 'exporFind',
  props: {
    data: {},
    node: {},
    disp: {
      nodeCode: undefined,
      nodeType: undefined,
      findFlag: false,
      updFlag: false,
      formData: {
        db: {},
        fields: []
      }
    }
  },
  data() {
    // 这里存放数据"
    return {
      formDb: [],
      toDb: {},
      formFields: [],
      toFields: [],
      fieldsList: new Map(),
      checkFieldsFlag: false,
      checkFieldsMapFlag: false,
      // 规则列表
      ruleOptions: [],
      // 数据库列表
      dbNameOptions: [],
      // 展示数据表列表
      tableOptions: [],
      // 字段列表
      fieldsOptions: [],
      // 所有数据库列表
      tableList: [],
      queryParams: {},
      // 级联选择器配置
      props: {
        label: 'ruleVersionName',
        value: 'ruleVersionCode',
        children: 'ruleVersionList'
      }
    }
  },
  // 计算属性 类似于data概念",
  computed: {},
  // 生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.init()
  },
  // 方法集合",
  methods: {
    // 初始化
    init() {
      this.formDb = []
      this.toDb = {}
      this.formFields = []
      // 查询上级的所有节点
      /** 1.查询该节点的上一级节点*/
      this.data.lineList.forEach(line => {
        if (line.to === this.node.id){
          listDisposition({nodeCode: line.from}).then(res => {
            const data = this.getVueDisp(res.data.rows)
            this.formDb = data.db
            this.formFields = data.fields
          })
        }
      })
      // 查询自身
      listDisposition({nodeCode: this.node.id}).then(res => {
        const data = this.getVueDisp(res.data.rows)
        console.log(data)
        this.toDb = data.toDb
        this.fieldsList = data.fieldsMap
      })
    },
    // 选择数据库按钮
    checkFields() {
      this.selDbNameList()
      this.getListAll()
      this.selRules()
      this.checkFieldsFlag = true
    },
    // 查询规则列表
    selRules() {
      // 查询所有规则
      // listRuleInfo({pageNum: 1, pageSize: 100}).then(response => {
      //   response.data.rows.forEach(item => {
      //     if(item.ruleVersionList){
      //       item.ruleVersionList.forEach(rule => this.ruleOptions.push(rule))
      //     }
      //   });
      //   console.log(this.ruleOptions)
      // });
      this.ruleOptions = [{
        ruleVersionName: "非法字符管理",
        ruleVersionClass: "CHAR_MANAGE",
        ruleVersionCode: "对非法字符进行过滤和筛选",
        ruleVersionType: "row",
        ruleVersionList: [
          {
            ruleVersionClass: "BLANK_SPACE_REMOVE",
            ruleVersionName: "空格清除",
            ruleVersionDescribed: "将空格清除",
            ruleVersionType: "row"
          },{
            ruleVersionClass: "SINGLE_QUOTATION_MARKS_REMOVE",
            ruleVersionName: "单引号清除",
            ruleVersionDescribed: "将单引号清除",
            ruleVersionType: "row"
          },{
            ruleVersionClass: "ANTIRADICAL_REMOVE",
            ruleVersionName: "反根号清除",
            ruleVersionDescribed: "将反根号清除",
            ruleVersionType: "row"
          }
        ]
      },
        {
          ruleVersionName: "唯一规则",
          ruleVersionClass: "UNIQUE_RULE",
          ruleVersionCode: "字段唯一性过滤",
          ruleVersionType: "fidle",
          ruleVersionList: []
        }]
    },
    checkRules() {

    },
    // 保存目标数据库
    save() {
      console.log('formDb',this.formDb)
      console.log('toDb',this.toDb)
      console.log('formFields',this.formFields)
      console.log('toFields',this.toFields)
      console.log('fieldsList',this.fieldsList)
      // 处理输入字段与输出字段
      const field = this.formFields
      let map = field.map(item => [item.fieldName, item.toFidlesName]);
      this.fieldsList = new Map()
      map.forEach(item => {
        this.toFields.forEach(toField => {
          if (toField.fieldName === item[1]){
            this.fieldsList.set(item[0], toField)
          }
        })
      })
      // 格式转换
      let mysqlDisp = this.getMysqlDisp(this.toDb,this.fieldsList);
      // 保存数据库
      batchAddUpd(mysqlDisp, this.disp.nodeCode).then(res => {
        this.$message.success(res.msg)
        this.checkFieldsFlag = false
        this.checkFieldsMapFlag = false
      })

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.tableOptions = []
      this.tableList.forEach(table => {
        const params = this.queryParams
        if ((table.dbName === params.dbName || !params.dbName) &&
          (table.tableName.includes(params.tableName) || !params.tableName) &&
          (table.tableComment.includes(params.tableComment) || !params.tableComment)){
          this.tableOptions.push(table)
        }
      })
    },
    /** 表字段查询*/
    selectTable(row) {
      this.toFields.fields = []
      this.toDb = {
        dbName: row.dbName,
        tableName: row.tableName,
        tableComment: row.tableComment,
        dbTable: row.dbName+'.'+row.tableName+'('+ row.tableComment +')'
      }
      selectDbTableColumnsByName(row.dbName, row.tableName).then(res => {
        this.fieldsOptions = res.data
      })
    },
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.toFields = selection.map(item => {
        return {
          dbTable: this.toDb.dbName+'.'+this.toDb.tableName,
          fieldName: item.columnName,
          fieldType: item.columnType,
          fieldComment: item.columnComment
        };
      });
    },
    // 查询所有数据库名称
    selDbNameList() {
      selDbNameAll().then(res => {
        this.dbNameOptions = res.data
      })
    },
    // 查询所有表名称信息
    getListAll() {
      listDbTableAll().then(res => {
        this.tableList = res.data;
        this.tableOptions = res.data;
      });
    },
    /** 节点配置 类型转换 mysql -> vue */
    getVueDisp(dispList) {
      const db = []
      const fields = []
      const fieldsMap = new Map()
      let toDb = {}
      dispList.forEach(disp => {
        if (disp.dispKey === 'table') {
          db.push({
            dbName: disp.dispDesc,
            tableName: disp.dispValue,
            tableComment: disp.dispLabel,
            dbTable: disp.dispDesc+'.'+disp.dispValue+'('+disp.dispLabel+')'
          })
        }
        if (disp.dispKey === 'fields') {
          fields.push({
            tableName: disp.dispDesc,
            fieldName: disp.dispValue,
            fieldType: disp.dispType,
            fieldComment: disp.dispLabel
          })
        }
        // 输出调整
        if (disp.dispKey === 'toDb'){
          toDb = {
            dbName: disp.dispDesc,
            tableName: disp.dispValue,
            tableComment: disp.dispLabel,
            dbTable: disp.dispDesc+'.'+disp.dispValue+'('+disp.dispLabel+')'
          }
        }
        if (disp.dispKey === 'toFields'){
          fieldsMap.set(disp.dispDesc, {
            fieldName: disp.dispValue,
            fieldType: disp.dispType,
            fieldComment: disp.dispLabel
          })
        }
      })
      return {db, fields, toDb, fieldsMap}
    },
    /** 节点配置 expor vue 转 mysql */
    getMysqlDisp(db, fields) {
      const dispList = []
      dispList.push({
        nodeCode: this.node.id,
        dispKey: 'toDb',
        dispDesc: db.dbName,
        dispValue: db.tableName,
        dispLabel: db.tableComment,
        dispType: 'String'
      })
      fields.keys().forEach(key => {
        dispList.push({
          nodeCode: this.node.id,
          dispKey: 'toFields',
          dispDesc: key,
          dispValue: fields.get(key).fieldName,
          dispLabel: fields.get(key).fieldComment,
          dispType: fields.get(key).fieldType
        })
      })
      return dispList;
    }
  }
}
</script>
<style scoped>

</style>
