<template>
  <div class="demo-topology">
    <topology
      ref="topology"
      :graph-data="graphData"
      :node-app-config="nodeAppConfig"
      :edge-app-config="edgeAppConfig"
      :node-type-list="nodeTypeList"
      :relational-map="relationalMap"
      @doAutoRefresh="doAutoRefresh"
      @doManualRefresh="doManualRefresh"
      @doChangeMode="doChangeMode"
      @doSaveData="doSaveData"
      @doPreview="doPreview"
      @doOnLine="doOnLine"
    >

    </topology>
    <el-dialog :title="previewDate.title" width="1400px" :visible.sync="previewDate.open">
      <el-form ref="ucon" :inline="true" v-show="previewDate.showSearch" label-width="68px">
        <el-form-item v-for="item in previewDate.uconList"
                      :key="item.id"
                      :label="item.ucName"
        >

          <el-input v-if="item.type == 1" v-model="item.ucReal"
                    clearable
                    :placeholder="outPlaceholder(item)"
                    size="small"
                    @keyup.enter.native="handleQuery"
          />
          <div style="width: 200px" v-else-if="item.type == 2">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-input size="small" placeholder="开始值" v-model="item.ucReal.begin"></el-input>
              </el-col>
              <el-col :span="12">
                <el-input size="small" placeholder="结束值" v-model="item.ucReal.end"></el-input>
              </el-col>
            </el-row>
          </div>
          <el-date-picker
            v-else-if="item.type ==3"
            v-model="item.ucReal"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <el-date-picker v-else-if="item.type ==4"
                          v-model="item.ucReal"
                          size="small"
                          style="width: 240px"
                          value-format="yyyy-MM-dd"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['tool:query:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="previewDate.showSearch" @queryTable="handleQuery"></right-toolbar>
      </el-row>
      <el-table :data="previewDate.data">
        <el-table-column v-for="(item,index) in previewDate.header"
                         :label="item.label"
                         align="center"
                         :key="index"
                         :prop="item.prop"
        />
      </el-table>
      <pagination
        v-show="previewDate.total>0"
        :total="previewDate.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-dialog>

  </div>
</template>

<script>
/* 局部注册 */
import Topology from './packages/topology/src/topology'
import { deepClone } from './utils/index'
import { getQuery, getTables, updateQuery, preview } from '@/api/tool/top'
import { RealData } from '@/api/system/data'
import { exportReal } from '../../../api/system/data'

export default {
  name: 'DemoTopology',
  components: {
    'topology': Topology
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      baseData: null,
      previewDate: {
        open: false,
        title: '预览',
        data: [],
        header: [],
        total: 0,
        uconList: [],
        showSearch: false
      },
      graphData: {
        // "nodes":[{"id":"305bfbdd-31cc-4028-b2b1-2f504968356d","x":304.8223042174235,"y":131.0267312661499,"label":"客户端","table":"test_table","type":"dice-er-box","attrs":[{"key":"id","type":"number(6)","comment":"主键id","isUse":0},{"key":"key","type":"varchar(255)","comment":"关键字","isUse":1},{"key":"gender","type":"enum(M, F)","comment":"gender","isUse":1},{"key":"birthday","type":"date","comment":"生日","isUse":0},{"key":"hometown","type":"varchar(255)","comment":"家乡","isUse":0},{"key":"country","type":"varchar(255)","comment":"国家","isUse":1},{"key":"nation","type":"varchar(255)","comment":"nation","isUse":1},{"key":"jobId","type":"number(3)","comment":"工作id","isUse":1},{"key":"phone","type":"varchar(255)","comment":"电话","isUse":1}],"size":[55,55],"width":250,"height":316,"anchorPoints":[[0.5,0],[1,0.5],[0.5,1],[0,0.5]],"appState":{"alert":false},"labelCfg":{"position":"bottom"},"style":{"default":{"stroke":"#CED4D9","fill":"transparent","shadowBlur":10,"shadowColor":"rgba(13, 26, 38, 0.08)","lineWidth":1,"radius":4,"strokeOpacity":0.7},"selected":{"shadowColor":"#ff240b","shadowBlur":2},"unselected":{"shadowColor":""}},"selectedIndex":null,"appConfig":{},"depth":0},{"id":"be9b52e5-9c2f-4e5c-990a-afbf19dcfeed","x":-94.51187075489108,"y":127.35469287559994,"label":"防火墙","table":"test_table","type":"dice-er-box","attrs":[{"key":"id","type":"number(6)","comment":"主键id","isUse":0},{"key":"key","type":"varchar(255)","comment":"关键字","isUse":1},{"key":"gender","type":"enum(M, F)","comment":"gender","isUse":0},{"key":"birthday","type":"date","comment":"生日","isUse":1},{"key":"hometown","type":"varchar(255)","comment":"家乡","isUse":1},{"key":"country","type":"varchar(255)","comment":"国家","isUse":0},{"key":"nation","type":"varchar(255)","comment":"nation","isUse":1},{"key":"jobId","type":"number(3)","comment":"工作id","isUse":1},{"key":"phone","type":"varchar(255)","comment":"电话","isUse":1}],"size":[55,55],"width":250,"height":316,"anchorPoints":[[0.5,0],[1,0.5],[0.5,1],[0,0.5]],"appState":{"alert":false},"labelCfg":{"position":"bottom"},"style":{"default":{"stroke":"#CED4D9","fill":"transparent","shadowBlur":10,"shadowColor":"rgba(13, 26, 38, 0.08)","lineWidth":1,"radius":4,"strokeOpacity":0.7},"selected":{"shadowColor":"#ff240b","shadowBlur":2},"unselected":{"shadowColor":""}},"selectedIndex":null,"appConfig":{},"startIndex":0,"startX":0,"depth":0}],"edges":[{"id":"8bc0249e-ee5d-4dd7-84e0-e4e32c217f2a","source":"be9b52e5-9c2f-4e5c-990a-afbf19dcfeed","sourceColumn":[{"key":"id","type":"number(6)","comment":"主键id","isUse":1},{"key":"key","type":"varchar(255)","comment":"关键字","isUse":1},{"key":"gender","type":"enum(M, F)","comment":"gender","isUse":1},{"key":"birthday","type":"date","comment":"生日","isUse":1},{"key":"hometown","type":"varchar(255)","comment":"家乡","isUse":1},{"key":"country","type":"varchar(255)","comment":"国家","isUse":1},{"key":"nation","type":"varchar(255)","comment":"nation","isUse":1},{"key":"jobId","type":"number(3)","comment":"工作id","isUse":1},{"key":"phone","type":"varchar(255)","comment":"电话","isUse":1}],"sourceAnchor":1,"target":"305bfbdd-31cc-4028-b2b1-2f504968356d","type":"top-cubic","style":{"active":{"stroke":"rgb(95, 149, 255)","lineWidth":1},"selected":{"stroke":"rgb(95, 149, 255)","lineWidth":2,"shadowColor":"rgb(95, 149, 255)","shadowBlur":10,"text-shape":{"fontWeight":500}},"highlight":{"stroke":"rgb(95, 149, 255)","lineWidth":2,"text-shape":{"fontWeight":500}},"inactive":{"stroke":"rgb(234, 234, 234)","lineWidth":1},"disable":{"stroke":"rgb(245, 245, 245)","lineWidth":1},"edgeStyle":{"default":{"stroke":"#e2e2e2","lineWidth":3,"lineAppendWidth":10},"selected":{"shadowColor":"#626262","shadowBlur":3}},"stroke":"#A3B1BF","lineWidth":2,"strokeOpacity":0.92,"lineAppendWidth":10},"labelCfg":{"position":"center","autoRotate":false},"startPoint":{"x":155.98812924510892,"y":285.35469287559994,"anchorIndex":1},"endPoint":{"x":304.3223042174235,"y":289.0267312661499,"anchorIndex":3},"curveOffset":[-20,20],"curvePosition":[0.5,0.5],"targetAnchor":3,"targetColumn":[{"key":"id","type":"number(6)","comment":"主键id","isUse":1},{"key":"key","type":"varchar(255)","comment":"关键字","isUse":1},{"key":"gender","type":"enum(M, F)","comment":"gender","isUse":1},{"key":"birthday","type":"date","comment":"生日","isUse":1},{"key":"hometown","type":"varchar(255)","comment":"家乡","isUse":1},{"key":"country","type":"varchar(255)","comment":"国家","isUse":1},{"key":"nation","type":"varchar(255)","comment":"nation","isUse":1},{"key":"jobId","type":"number(3)","comment":"工作id","isUse":1},{"key":"phone","type":"varchar(255)","comment":"电话","isUse":1}],"depth":0}],"combos":[]},
      },
      nodeTypeList: [
        // { guid: "blue", label: "蓝色", imgSrc: require("../../assets/images/blue.svg") },
        // { guid: "green", label: "绿色", imgSrc: require("@/assets/images/green.svg") },
        // { guid: "purple", label: "紫色", imgSrc: require("@/assets/images/purple.svg") }
      ],
      // 关联关系验证数组
      relationalMap: [],
      // 节点配置
      nodeAppConfig: {
        // ip: '节点IP',
        // port: '节点端口',
        // sysName: '设备名称'
      },
      edgeAppConfig: {
        associated: '查询方式',
        tableComment: '主表字段',
        relComment: '关联字段'
      },
      autoRefreshTimer: null
    }
  },
  mounted() {
    this.topId = this.$route.params && this.$route.params.topId
    getQuery(this.topId).then(res => {
      this.baseData = res.data
      if (res.data.topJson) {
        this.graphData = JSON.parse(res.data.topJson)
      } else {
        this.graphData = {
          nodes: [],
          edges: []
        }
      }
      let graphData = deepClone(this.graphData)
      this.$refs.topology.initTopo(graphData)
      this.randomChange()
    })
    getTables().then(res => {
      this.nodeTypeList = res.data.tables
      this.relationalMap = res.data.relationalMap
    })
  },
  methods: {
    /**
     * 重置
     */
    resetQuery() {
      for (let i = 0; this.previewDate.uconList.length; i++) {
        this.previewDate.uconList[i].ucReal = null
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this
      this.$confirm('是否确认导出查询数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        let data = {
          id: that.topId,
          uniCons: that.previewDate.uconList
        }
        return exportReal(data)
      }).then(response => {
        this.download(response.msg)
      })
    },
    handleQuery() {
      let data = {
        id: this.topId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      data.uniCons = this.previewDate.uconList
      //todo 需要修改
      RealData(data).then(res => {
        this.previewDate.data = res.rows
        this.total = res.total
      })
    },
    outPlaceholder(item) {
      return '请输入' + item.ucName
    },
    doAutoRefresh(interval) {
      if (interval === -1) {
        clearInterval(this.autoRefreshTimer)
      } else {
        clearInterval(this.autoRefreshTimer)
        this.autoRefreshTimer = setInterval(() => {
          this.randomChange()
        }, interval)
        this.$once('hook:beforeDestroy', () => {
          clearInterval(this.autoRefreshTimer)
        })
      }
    },
    doChangeMode(graphMode) {
      clearInterval(this.autoRefreshTimer)
      let graphData = deepClone(this.graphData)
      this.$refs.topology.changeGraphMode(graphData, graphMode)
    },
    doManualRefresh() {
      this.randomChange()
    },
    doSaveData(graphData) {
      let data = {
        id: this.topId,
        topJson: JSON.stringify(graphData)
      }
      //todo 入库完成
      updateQuery(data).then(res => {
        this.msgSuccess(res.msg)
      })
    },
    doOnLine() {
      this.$confirm('请确认top图结构无误并预览结果无误后上线?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {

      })
    },
    //预览
    doPreview(graphData) {
      if (graphData.nodes && graphData.nodes.length > 0) {
        let nodeList = graphData.nodes
        let edgeList = graphData.edges
        let nodes = []
        nodeList.forEach(node => {
          nodes.push({
            id: node.id,
            label: node.label,
            table: node.table,
            columns: node.columns
          })
        })
        let edges = []
        edgeList.forEach(edge => {
          edges.push({
            id:edge.id,
            label: edge.label,
            source: edge.source,
            target: edge.target,
            appConfig: edge.appConfig
          })
        })

        let data = {
          jsonData: JSON.stringify({
            nodes: nodes,
            edges: edges
          }),
          id: this.topId
        }
        console.log({
          nodes: nodes,
          edges: edges
        })
        preview(data).then(res => {
          this.previewDate.data = res.rows
          this.previewDate.total = res.total
          this.previewDate.uconList = res.uconList
          if (this.previewDate.uconList.length > 0) {
            this.previewDate.showSearch = true
          }
          this.previewDate.header = []
          let infoList = res.infoList
          infoList.forEach( info=>{
            this.previewDate.header.push({
              key: info.prop,
              label: info.label,
              prop: info.prop
            })
          })

          this.previewDate.title = this.baseData.uqName + '数据预览'
          this.previewDate.open = true
        })
      } else {
        this.msgError('top数据有误,请再次检查')
      }
    },
    randomChange() {
      let graphData = deepClone(this.$refs.topology.getGraphData())
      let { nodes } = graphData
      this.$refs.topology.changeGraphData(graphData)
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-topology {
  width: 100%;
  height: 100%;
}
</style>

<style lang="scss">
html {
  overflow-x: hidden;
  overflow-y: hidden;
}
</style>
