<template>
  <div id="main" style="margin: 0px;padding: 0px; height: 100%">
    <!-- 内容页 -->
    <el-container class="page-main adapt-height-box h-all">

      <!-- 顶部菜单栏 -->
      <el-header height="auto">
        <div class="header-button-box">
          <el-button icon="el-icon-s-home" size = 'mini' type="primary" @click="showGlobalView" v-show="doubleClickSubnetId!==''">{{ $t('TopologicalGraphShow.returnGlobal') }}</el-button>
          <el-button icon="el-icon-circle-plus-outline" size = 'mini' type="primary" @click="createDeviceInit" v-show="doubleClickSubnetId!==''">{{ $t('TopologicalGraphShow.addDevice') }}</el-button>
          <el-button icon="el-icon-circle-plus-outline" size = 'mini' type="primary" v-show="createLinkCommand.visible && doubleClickSubnetId!==''"  @click="createLinkInit">{{ $t('TopologicalGraphShow.addLink') }}</el-button>
          <el-button icon="el-icon-tickets" size = 'mini' type="primary" @click="saveTopologicalGraph" >{{ $t('TopologicalGraphShow.saveTopology') }}</el-button>
          <el-button icon="el-icon-refresh" size = 'mini' type="primary" @click="syncSystemData" >{{ $t('TopologicalGraphShow.syncTopology') }}</el-button>
          <el-button icon="el-icon-download" size = 'mini' type="primary" @click="saveSvgToPng" >{{ $t('TopologicalGraphShow.saveImage') }}</el-button>
          <el-button icon="el-icon-zoom-in" size = 'mini' type="primary" @click="zoomIn" >放大</el-button>
          <el-button icon="el-icon-zoom-out" size = 'mini' type="primary" @click="zoomOut" >缩小</el-button>
          <el-button icon="el-icon-refresh-left" size = 'mini' type="primary" @click="reset" >还原</el-button>
          <el-button icon="el-icon-full-screen" size = 'mini' type="primary" @click="fullScreen" >全屏</el-button>
        </div>
        <div class="header-button-box header-right">
          <div class="icon-circle" :style="{backgroundColor:my_alarmLevelConfig[-1].alarmColor}"></div><label>{{ alarmTotalNumnberMessage }}</label>
          <div class="icon-circle" :style="{backgroundColor:my_alarmLevelConfig[2].alarmColor}"></div><label>{{ TwoAlarmNumberMessage }}</label>
          <div class="icon-circle" :style="{backgroundColor:my_alarmLevelConfig[1].alarmColor}"></div><label>{{ OneAlarmNumberMessage }}</label>
          <div class="icon-circle" :style="{backgroundColor:my_alarmLevelConfig[0].alarmColor}" ></div><label>{{ ZeroAlarmNumberMessage }}</label>
        </div>
      </el-header>
      <div id="TopologyBox" class="adapt-height adapt-height-box">
        <div id="TopologyTop" >
          <!--拓扑视图,引用拓扑视图子组件-->
          <DrawTopologyComponent
            ref="DrawTopologyComponent"
            class="adapt-height h-all"
            style="margin:0px; padding:0px;overflow: hidden;"
            :topologyCollection="my_topologyCollection"
            :linkCollection="my_linkCollection"
            :alarmLevelConfig="my_alarmLevelConfig"
            :subnetCollection="my_subnetCollection"
            :drawGraphSizeConfig="drawGraphSizeConfig"
            :curClickSubnetId="my_curClickSubnetId"
            :commands="commandContext"
            :curClickDeviceId.sync="my_curClickDeviceId"
            :deviceCollection="my_deviceCollection"
            :doubleClickSubnetId.sync="doubleClickSubnetId"
            :alarmCollection="my_alarmCollection">
          </DrawTopologyComponent>
        </div>
        <div id="TopologyResize"></div>
        <div id="TopologyDown" style="border-top: 1px solid #b5b9a9; " class="adapt-height">
          <!-- 底部显示区,引用告警状态栏子组件 -->
          <el-footer style="margin: 0px;padding: 0px;" width="auto" height="100%">
            <AlarmDisplay
              ref="AlarmDisplay"
              :alarmCollection="my_alarmCollection"
              :deviceCollection = 'my_deviceCollection'
              :curClickDeviceId.sync = 'my_curClickDeviceId'
              :alarmLevelConfig="my_alarmLevelConfig"
              :configFileDifferenceCollection="my_configFileDifferenceCollection">
            </AlarmDisplay>
          </el-footer>
        </div>
      </div>
    </el-container>
    <CommandExecuteContext v-bind:commands="commandContext"></CommandExecuteContext>
  </div>
</template>

<script>
// 引入拓扑视图、底部告警栏子组件
import DrawTopologyComponent from './DrawTopologyComponent'
import AlarmDisplay from './AlarmDisplay'
import CommandExecuteContext from '../../commands/CommandExecuteContext.vue'
import DeviceCommands from '../../commands/DeviceCommands'
import saveSvg from 'save-svg-as-png'
import TopologyManager from '../../domain/models/TopologyManager'
import AlarmManager from '../../domain/models/AlarmManager'
import TopologyService from '../../domain/services/TopologyService'
import { EventBus } from '../../domain/EventBus'
import HelperUtil from '../../utils/HelperUtil'
import store from '@/store.js'

export default {
  name: 'TopologicalGraphShow',

  // 接收顶层组件的传参
  props: {
    alarmCollection: null, // 告警列表，传递给底部告警状态栏子组件
    alarmLevelConfig: null, // 告警的颜色配置
    topologyCollection: null, // 带status的设备集合
    linkCollection: null, // 带status的链路集合
    subnetCollection: null, // 子网集合
    curClickSubnetId: null, // 当前点击的子网ID
    curClickDeviceId: null, // 当前点击的设备ID
    deviceCollection: null, // 设备列表
    configFileDifferenceCollection: null // 配置文件差异性信息列表
  },

  // 引用子组件
  components: {
    CommandExecuteContext,
    DrawTopologyComponent, // 拓扑图显示组件
    AlarmDisplay // 底部告警状态栏组件
  },

  data: function () {
    return {
      // 将props传进来的进行缓存
      my_deviceCollection: this.deviceCollection,
      my_subnetCollection: this.subnetCollection,
      my_alarmCollection: this.alarmCollection,
      my_linkCollection: this.linkCollection,
      my_topologyCollection: this.topologyCollection,
      my_alarmLevelConfig: this.alarmLevelConfig,
      my_curClickSubnetId: this.curClickSubnetId,
      my_curClickDeviceId: this.curClickDeviceId,
      my_configFileDifferenceCollection: this.configFileDifferenceCollection,
      // my_serverCollection: this.serverCollection,

      commandContext: {},
      createAndCopyTitle: '',
      createAndCopyInitList: '',
      // 本地真实数据，传递给画图子组件，一些画图的基本参数
      drawGraphSizeConfig: {
        svgWidth: '100%',
        svgHeight: '100%',
        imageWidth: 32,
        imageHeight: 32,
        textSize: 14
      },
      // footer标签页 默认显示告警信息（无用）
      activeName: 'first',
      // test event-bus
      syncAllDataFlag: false,

      // 告警总数
      alarmTotalNumnber: 0,
      alarmTotalNumnberMessage: '',
      // 紧急告警条数
      TwoAlarmList: {},
      TwoAlarmNumber: 0,
      TwoAlarmNumberMessage: '',
      // 严重告警条数
      OneAlarmNumber: 0,
      OneAlarmList: {},
      OneAlarmNumberMessage: '',
      // 警告告警条数
      ZeroAlarmNumber: 0,
      ZeroAlarmList: {},
      ZeroAlarmNumberMessage: '',

      UnConfirmedAlarmList: {},
      ConfirmedAlarmList: {},
      ClearedAlarmList: {},

      createLinkTitle: '', // 创建链路的标题
      createLinkInitList: [], // 创建链路的初始化列表
      // createAndCopyDeviceDisable: 'true',
      // createAndCopyLinkDisable: 'true',
      doubleClickSubnetId: ''
    }
  },

  methods: {
    /**
     * @Description  ：上下拖动改变控制器div大小
     * @param        :
     * @return       :
     * @exception    :
     * @date         : 2019/05/28
     */
    dragControllerDiv: function () {
      let _this = this
      $(document).ready(function () {
        var h = window.screen.height
        var svgResize = document.getElementById('TopologyResize')
        var svgTop = document.getElementById('TopologyTop')
        var svgDown = document.getElementById('TopologyDown')
        var svgBox = document.getElementById('TopologyBox')
        // svgBox.style.height = h * 0.5 + "px";

        if (svgResize) {
          svgResize.onmousedown = function (e) {
            var startY = e.clientY
            svgResize.top = svgResize.offsetTop
            document.onmousemove = function (e) {
              var endY = e.clientY
              var moveLen = svgResize.top + (endY - startY)
              var maxT = svgBox.clientHeight - svgResize.offsetHeight
              if (moveLen < 50) moveLen = 50
              if (moveLen > maxT - 50) moveLen = maxT - 50
              svgResize.style.top = moveLen
              svgTop.style.height = moveLen + 'px'
              svgDown.style.height = (svgBox.clientHeight - moveLen - 5) + 'px'
              // 触发告警列表高度的计算
              EventBus.$emit('cal-table-height')
            }
            document.onmouseup = function (evt) {
              document.onmousemove = null
              document.onmouseup = null
              svgResize.releaseCapture && svgResize.releaseCapture()
            }
            svgResize.setCapture && svgResize.setCapture()
            return false
          }
        }
      }
      )
    },

    /**
     * @Description  ：链路添加的初始化
     * @author       : yzj
     * @param        :
     * @return       :
     * @exception    :
     * @date         : 2019/04/28
     */
    createLinkInit: function () {
      this.createLinkTitle = this.$t('LinkConfigurationManagement.createLinkInfo')
      this.createLinkInitList = {
        'linkKey': '',
        'linkName': '',
        'startDeviceKey': '',
        'startPortName': '',
        'endDeviceKey': '',
        'endPortName': '',
        'startGroupID': '',
        'endGroupID': '',
        'linkStatus': 0,
        'linkType': 0,
        'delFlag': 0,
        'modifyTime': '',
        'belongSubnet': this.doubleClickSubnetId
      }
      this.createLinkCommand.execute()
    },
    /**
     * @Description  ：设备添加的初始化
     * @author       : yzj
     * @param        :
     * @return       :
     * @exception    :
     * @date         : 2019/04/28
     */
    createDeviceInit () {
      this.createAndCopyTitle = this.$t('DeviceConfigurationManagement.createDeviceInfo')
      this.createAndCopyInitList = {
        'deviceKey': '',
        'uuid': '',
        'hostName': '',
        'displayName': '',
        'deviceTypeKey': '',
        'deviceModel': '',
        'subnetKey': this.doubleClickSubnetId,
        'ipAddress': '',
        'bussIpAddress': '',
        'mac': '',
        'manageType': 0,
        'bussManageType': 0,
        'snmpVersion': 1,
        'snmpPort': 161,
        'trapPort': 162,
        'snmpGroup': 'publicCrscd',
        'ipmiUserName': '',
        'ipmiPassword': '',
        'deviceStatus': 0,
        'deviceVersion': '',
        'deviceDesc': '',
        'startTime': '',
        'firmwareKey': '',
        'firmwareFileName': '',
        'station': '',
        'locationName': '',
        'brand': '',
        'manufacturerLiaison': '',
        'manufacturerPhone': '',
        'manager': '',
        'managerPhone': '',
        'delFlag': 0,
        'modifyTime': ''
      }

      this.createAndCopyCommand.execute()
    },

    /**
     * @Description  ：点击同步按钮，获取最新数据并同步。
     * @author       : yjz
     * @param        :
     * @return       :
     * @exception    :
     * @date         :
     */
    syncSystemData () {
      this.syncAllDataFlag = true
      EventBus.$emit('i-got-syncFlag', this.syncAllDataFlag)
    },

    /**
     * @Description  ：对按钮 导出图片 的点击事件响应函数
     * @author       : yjz
     * @param        :
     * @return       :
     * @exception    :
     * @date         : 2019/4/29
     */
    saveSvgToPng: function () {
      let svg = document.getElementById('svgWrapper')
      let gRect = document.getElementById('viewGroup').getBoundingClientRect()
      let svgRect = svg.getBoundingClientRect()
      saveSvg.saveSvgAsPng(svg, 'topology.png', {backgroundColor: '#ffffff', width: gRect.width + 100, height: gRect.height + 100, left: gRect.left - svgRect.left - 50, top: gRect.top - svgRect.top - 50})
    },
    /**
     * @Description  ：保存拓扑图的信息
     * @author       : yjz
     * @param        :
     * @return       :
     * @exception    :
     * @date         :
     */
    saveTopologicalGraph () {
      let _this = this

      // 获得拓扑图最新的拓扑集合
      let topologySaveList = this.$refs.DrawTopologyComponent.getLocalNewestTopologyCollection()

      // 拼接topologyNode对象
      let topologyManager = TopologyManager(topologySaveList)
      let topologyNodeListStr = topologyManager.handleTopologyToSave()
      // 调用service
      let loadingInstance = _this.Loading.openLoading()
      TopologyService.saveTopologyCollection(topologyNodeListStr).then(result => {
        // 成功
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.successTip(_this, HelperUtil.getStatusCodeObjectByCode(_this.successCode.OTHERS_CODE))
      }).catch(err => {
        // 失败
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    // 缩小
    zoomOut () {
      this.$refs.DrawTopologyComponent.zoomOutFuc()
    },
    // 放大
    zoomIn () {
      this.$refs.DrawTopologyComponent.zoomInFuc()
    },
    // 还原
    reset () {
      this.$refs.DrawTopologyComponent.reset()
    },
    fullScreen () {
      this.$refs.DrawTopologyComponent.fullScreenIn()
    },
    /**
     * ----------拓扑图告警统计信息显示----------------
     */

    // 告警统计总数
    getAlarmTotalNumber: function () {
      let alarmManager = AlarmManager(this.alarmCollection)
      this.UnConfirmedAlarmList = alarmManager.getUnConfirmedAlarmList()
      this.ConfirmedAlarmList = alarmManager.getConfirmedAlarmList()
      this.ClearedAlarmList = alarmManager.getClearedAlarmList()
      this.alarmTotalNumber = this.UnConfirmedAlarmList.length + this.ConfirmedAlarmList.length + this.ClearedAlarmList.length
      this.alarmTotalNumnberMessage = this.$t('TopologicalGraphShow.AllAlarmsNum') + this.alarmTotalNumber
      this.getTwoAlarmNumber()
      this.getOneAlarmNumber()
      this.getZeroAlarmNumber()
    },

    // 紧急告警统计总数 2
    getTwoAlarmNumber: function () {
      let UnConfirmedAlarmNo = this.getNumberByAlarmLevel(this.UnConfirmedAlarmList, 2)
      let ConfirmedAlarmNo = this.getNumberByAlarmLevel(this.ConfirmedAlarmList, 2)
      let ClearedAlarmNo = this.getNumberByAlarmLevel(this.ClearedAlarmList, 2)
      this.TwoAlarmNumber = UnConfirmedAlarmNo + ConfirmedAlarmNo + ClearedAlarmNo
      this.TwoAlarmNumberMessage = this.$t('TopologicalGraphShow.CriticalAlarmsNum') + this.TwoAlarmNumber
    },

    // 严重告警统计总数 1
    getOneAlarmNumber: function () {
      let UnConfirmedAlarmNo = this.getNumberByAlarmLevel(this.UnConfirmedAlarmList, 1)
      let ConfirmedAlarmNo = this.getNumberByAlarmLevel(this.ConfirmedAlarmList, 1)
      let ClearedAlarmNo = this.getNumberByAlarmLevel(this.ClearedAlarmList, 1)
      this.OneAlarmNumber = UnConfirmedAlarmNo + ConfirmedAlarmNo + ClearedAlarmNo
      this.OneAlarmNumberMessage = this.$t('TopologicalGraphShow.MajorAlarmsNum') + this.OneAlarmNumber
    },

    // 警告告警统计总数 0
    getZeroAlarmNumber: function () {
      let UnConfirmedAlarmNo = this.getNumberByAlarmLevel(this.UnConfirmedAlarmList, 0)
      let ConfirmedAlarmNo = this.getNumberByAlarmLevel(this.ConfirmedAlarmList, 0)
      let ClearedAlarmNo = this.getNumberByAlarmLevel(this.ClearedAlarmList, 0)
      this.ZeroAlarmNumber = UnConfirmedAlarmNo + ConfirmedAlarmNo + ClearedAlarmNo
      this.ZeroAlarmNumberMessage = this.$t('TopologicalGraphShow.MinorAlarmsNum') + this.ZeroAlarmNumber
    },

    // 根据告警等级统计数字
    getNumberByAlarmLevel: function (alarmList, alarmLevel) {
      let total = 0
      for (let i = 0; i < alarmList.length; i++) {
        if (alarmList[i].alarmLevel === alarmLevel) {
          total += 1
        }
      }
      return total
    },
    showGlobalView () {
      this.$refs.DrawTopologyComponent.showGlobalView()
    }
  },
  beforeCreate () {
  },
  created () {
    this.getAlarmTotalNumber()
  },
  computed: {
    createAndCopyCommand () {
      return DeviceCommands.createAndCopyDeviceCommand(this.createAndCopyTitle, this.createAndCopyInitList, this.commandContext)
    },
    createLinkCommand () {
      return DeviceCommands.createAndCopyLinkCommand(this.createLinkTitle, this.createLinkInitList, this.commandContext)
    },
    alarmNumber () { // 计算国际化信息
      this.alarmTotalNumnberMessage = this.$t('TopologicalGraphShow.AllAlarmsNum') + this.alarmTotalNumber
      this.TwoAlarmNumberMessage = this.$t('TopologicalGraphShow.CriticalAlarmsNum') + this.TwoAlarmNumber
      this.OneAlarmNumberMessage = this.$t('TopologicalGraphShow.MajorAlarmsNum') + this.OneAlarmNumber
      this.ZeroAlarmNumberMessage = this.$t('TopologicalGraphShow.MinorAlarmsNum') + this.ZeroAlarmNumber
    }
  },
  watch: {
    // 监听国际化的切换
    '$i18n.locale' () {
      this.alarmNumber()
    },
    // 监听prop，更新本地缓存数据
    deviceCollection: {
      handler (newVal, OldVal) {
        this.my_deviceCollection = newVal
      },
      deep: true
    },
    configFileDifferenceCollection: {
      handler (newVal, OldVal) {
        this.my_configFileDifferenceCollection = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_deviceCollection: {
      handler (newVal, OldVal) {
        this.my_deviceCollection = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    subnetCollection: {
      handler (newVal, OldVal) {
        this.my_subnetCollection = newVal
        this.getAlarmTotalNumber()
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_subnetCollection: {
      handler (newVal, OldVal) {
        this.my_subnetCollection = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    alarmCollection: {
      handler (newVal, OldVal) {
        this.getAlarmTotalNumber()
        this.my_alarmCollection = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_alarmCollection: {
      handler (newVal, OldVal) {
        this.my_alarmCollection = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    linkCollection: {
      handler (newVal, OldVal) {
        this.my_linkCollection = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_linkCollection: {
      handler (newVal, OldVal) {
        this.my_linkCollection = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    topologyCollection: {
      handler (newVal, OldVal) {
        let time = new Date()
        console.log('3数据刚来============' + time.getMinutes() + 'm' + time.getSeconds() + 's' + time.getMilliseconds() + 'ms')
        console.log('props topology data !!!')
        this.my_topologyCollection = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_topologyCollection: {
      handler (newVal, OldVal) {
      },
      deep: true
    },

    // 监听prop，更新本地缓存数据
    alarmLevelConfig: {
      handler (newVal, OldVal) {
        this.my_alarmLevelConfig = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_alarmLevelConfig: {
      handler (newVal, OldVal) {
        this.my_alarmLevelConfig = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    curClickDeviceId: {
      handler (newVal, OldVal) {
        this.my_curClickDeviceId = newVal
      },
      deep: true
    },
    // 监听本地数据，发生变化向外传输
    my_curClickDeviceId: {
      handler (newVal, OldVal) {
        this.my_curClickDeviceId = newVal
      },
      deep: true
    },
    // 监听prop，更新本地缓存数据
    curClickSubnetId: {
      handler (newVal, OldVal) {
        this.my_curClickSubnetId = newVal
      },
      deep: true
    }

    // 监听prop，更新本地缓存数据
    // serverCollection: {
    //   handler(newVal,OldVal) {
    //     this.my_serverCollection = newVal;
    //   },
    //   deep: true
    // },
    // 监听本地数据，发生变化向外传输
    // my_serverCollection: {
    //   handler(newVal,OldVal) {
    //     this.my_serverCollection = newVal;
    //   },
    //   deep: true
    // },
  },
  beforeUpdate () {
    this.dragControllerDiv()
  },
  mounted () {
    this.dragControllerDiv()
  }
}
</script>

<style scoped>
  /*!* 外层布局容器样式 *!*/
  .el-footer {
    background-color: #f9fafc;
    color: #333;
  }
  #linkAddBtn{
    margin-left: 383px;
  }
  /* D3 控件样式 */
  #TopologyBox{
    width:100%;
    height: 100%;
    position: relative;
    overflow:hidden;
  }
  #TopologyTop{
    height:calc(70% - 5px);
    width:100%;
    float:left;
    overflow: hidden;
  }

  #TopologyResize{
    position: relative;
    height:5px;
    width:100%;
    cursor: s-resize;
    float:left;
  }

  #TopologyDown{
    height:auto;
    width:100%;
    float:left;
    overflow: hidden;
  }

  /deep/ .node-image {
  }

  /deep/ .node-text {

  }
  /deep/ .path-data {

  }
  /deep/ .path-text {

  }

  /deep/ .el-column-padding{
    padding-bottom: 10px!important;
    padding-top: 0px!important;
  }
  /deep/ .caret-wrapper{
    height: 22px!important;
  }
  /deep/ .sort-caret.ascending{
    border-top-width: 5px!important;
    top: 0px!important;
  }
  /deep/ .sort-caret.descending{
    border-top-width: 5px!important;
    top: 12px!important;
  }

  /deep/ .col-new{
    padding-left: 0px !important;
    padding-right: 0px !important;
  }

  /deep/ .el-container is-vertical{
    height: 100%!important;
  }
  /deep/ .el-tabs__content{
    padding: 0px!important;
  }
  /deep/ .el-main{
    padding-bottom: 0px!important;
    padding-top: 0px!important;
    padding-left: 0px!important;
    padding-right: 0px!important;
  }
  /deep/ .el-tag{
    Color: #000000!important;
  }
</style>
