<template>
  <div>
    <el-form label-position="right" label-width="120px" :model="disp.formData.db" :inline="true">
      <el-form-item label="数据库" style="width: 30%;">
        <el-input v-model="disp.formData.db.dbName" placeholder="未配置" disabled />
      </el-form-item>
      <el-form-item label="数据表" style="width: 30%;">
        <el-input v-model="disp.formData.db.tableName" placeholder="未配置" disabled />
      </el-form-item>
      <el-form-item label="数据表备注" style="width: 30%;">
        <el-input v-model="disp.formData.db.tableComment" placeholder="无备注" disabled />
      </el-form-item>
    </el-form>
    <span>
          <el-table ref="table" :data="disp.formData.fields" height="300px">
            <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>
      </span>
    <br><br>
    <div align="center">
      <el-button @click="disp.findFlag = false">确认</el-button>
      <el-button type="primary" @click="toTableUpdFlag">修改配置</el-button>
    </div>
    <el-dialog title="修改配置" :visible.sync="tableUpdFlag" width="80%" :modal="false">
      <div>
        <el-form v-model="checkTable">
          <el-form-item label="数据来源" prop="dbTable">
            <el-cascader :options="treeList" :props="props" @change="checkDbTable" style="width: 60%;">
              <template slot-scope="{ node, data }">
                <span v-if="data.tableRemark">{{ data.tableName + '[' + data.tableRemark + ']' }}</span>
                <span v-else>{{ data.tableName }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item prop="fields">
            <el-table ref="table" :data="fieldsOptions" height="300px"
                      @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>
          </el-form-item>
          <el-form-item>
            <div align="center">
              <el-button @click="tableUpdFlag = false">取消</el-button>
              <el-button type="primary" @click="save">保存修改</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  // import引入的组件需要注入到对象中才能使用"
  name: 'tableFind',
  props: {
    node: {},
    disp: {
      nodeCode: undefined,
      nodeType: undefined,
      findFlag: false,
      updFlag: false,
      formData: {
        db: {},
        fields: []
      }
    }
  },
  data() {
    // 这里存放数据"
    return {
      loading: false,
      // 修改窗口显示状态
      tableUpdFlag: false,
      // 数据库+表 树形列表
      treeList: [],
      // 级联选择器配置
      props: {
        value: 'tableName',
        label: 'tableName',
        children: 'children'
      },
      // 数据库与表与字段
      checkTable: {
        source: {},
        db: {
          dbName: '',
          dbComment: '',
        },
        table: {
          tableName: '',
          tableComment: ''
        },
        fields: []
      },
      // 全部字段列表
      fieldsOptions: [],
    }
  },
  // 计算属性 类似于data概念",
  computed: {},
  // 生命周期 - 创建完成（可以访问当前this实例）",
  created() {

  },
  // 方法集合",
  methods: {
    /** 点击修改配置按钮 */
    toTableUpdFlag() {
      this.selDataSourceTreeListAll()
      this.tableUpdFlag = true
    },
    // 查询所有已同步的数据源的数据库+表 树形列表
    selDataSourceTreeListAll(){
      listSource({pageNum: 1, pageSize: 100,}).then(response => {
        this.treeList = []
        response.data.rows.forEach(item => {
          this.treeList.push({
            id: item.id,
            basicId: item.id,
            tableName: item.name,
            tableRemark: item.systemName,
            dataNum: item.initTotal,
            isCenter: 'Y',
            children: []
          })
        })
        console.log(this.treeList)
        findTableInfoList().then(res=>{
          const trees = res.data
          this.treeList.forEach(treeMaste => {
            trees.forEach(tree => {
              if (treeMaste.id === tree.basicId){
                  treeMaste.children.push(tree)
              }
            })
          })
        })
      });
    },
    // 选中数据库与表
    checkDbTable(value) {
      this.checkTable.source = this.treeList.filter(item => item.tableName === value[0])[0]
      const db = this.checkTable.source.children.filter(item => item.tableName === value[1])[0]
      this.checkTable.db = {
        dbName: db.tableName,
        dbComment: db.tableRemark,
      }
      const table = db.children.filter(item => item.tableName === value[2])[0]
      this.checkTable.table = {
        tableName: table.tableName,
        tableComment: table.tableRemark
      }
      this.selectTable(this.checkTable.db.dbName, this.checkTable.table.tableName);
    },
    // 表字段查询
    selectTable(dbName, tableName) {
      selectDbTableColumnsByName(dbName, tableName).then(res => {
        this.fieldsOptions = res.data
      })
    },
    // 多选框选中数据
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.checkTable.fields = selection.map(item => {
        return {
          tableName: this.checkTable.tableName,
          fieldName: item.columnName,
          fieldType: item.columnType,
          fieldComment: item.columnComment
        };
      });
    },
    /** 保存修改按钮 */
    save() {
      const dispList = this.getMysqlDisp(
        this.checkTable.source,
        this.checkTable.db,
        this.checkTable.table,
        this.checkTable.fields
      )
      this.disp.formData = {
        db: {
          dbName: this.checkTable.db.dbName,
          tableName: this.checkTable.table.tableName,
          tableComment: this.checkTable.table.tableComment
        },
        fields: this.checkTable.fields,
      }
      batchAddUpd(dispList, this.node.id).then(res => {
        this.$message.success(res.msg)
        this.tableUpdFlag = false
      })
      console.log(dispList)
    },
    /** 类型转换 vue -> mysql*/
    getMysqlDisp(source, db, table, fields) {
      const dispList = []
      dispList.push({
        nodeCode: this.node.id,
        dispKey: 'source',
        dispLabel: source.tableRemark,
        dispValue: source.tableName,
        dispType: 'string',
        dispDesc: source.id
      },{
        nodeCode: this.node.id,
        dispKey: 'db',
        dispLabel: db.dbComment,
        dispValue: db.dbName,
        dispType: 'string',
        dispDesc: source.tableName
      },{
        nodeCode: this.node.id,
        dispKey: 'table',
        dispLabel: table.tableComment,
        dispValue: table.tableName,
        dispType: 'string',
        dispDesc: db.dbName
      })
      fields.forEach(field => {
        dispList.push({
          nodeCode: this.node.id,
          dispKey: 'fields',
          dispLabel: field.fieldComment,
          dispValue: field.fieldName,
          dispType: field.fieldType,
          dispDesc: db.dbName+"."+table.tableName
        })
      })
      return dispList;
    },

  }
}
</script>
<style scoped>

</style>
