import DeviceAPI from '../../api/restApis/DeviceAPI'
import HelperUtil from '../../utils/HelperUtil'
import LinkService from './LinkService'
import DeviceStateSocketApi from '../../api/websocketApis/DeviceStateSocketApi'
import {
  DEVICE_KEY,
  DEVICE_MODEL_KEY,
  DEVICE_TYPE_KEY,
  DISCOVER_STATUS_ENUM,
  ENABLED_STATUS_ENUM,
  DEVICE_DOWNLOAD_FILE_NAME,
  HISTORY_CONFIG_KEY,
  DEVICE_LOG_DOWNLOAD_FILE_NAME,
  DISABLED_STATUS_ENUM,
  UUID, DEVICE_BOOK_DOWNLOAD_FILE_NAME
} from '../../utils/constantCollection'
import Vue from 'vue'
import TopologyManager from '../models/TopologyManager'
import PortListService from './PortListService'
import AlarmManagerService from './AlarmManagerService'
import AlarmService from './AlarmService'

let helperMethods = {

  setTopologyInitLocation: function (topologys) {
    var count = 0
    var ycount = 0
    for (var topologyKey in topologys) {
      if (topologys[topologyKey].xAxis === 0 && topologys[topologyKey].yAxis === 0) {
        topologys[topologyKey].xAxis = ycount + count * 50
        topologys[topologyKey].yAxis = 0
        Vue.set(topologys, topologyKey, topologys[topologyKey])
        count++
        if (count === 20) {
          ycount++
          count = 0
        }
      }
    }
  },

  // 查询该设备是否在其对应的子网对象中的deviceList 中
  isFindDevice: function (subnets, device) {
    var temp = false
    let deviceList = null
    if (device.subnetKey === '') {
      deviceList = subnets['0'].deviceList
    } else {
      deviceList = subnets[device.subnetKey].deviceList
    }
    for (var deviceKey in deviceList) {
      if (deviceKey === device.deviceKey) {
        temp = true
        break
      }
    }
    return temp
  },

  // 查询该设备是否在其对应的 devices 中
  isFindDeviceWithDevices: function (devices, device) {
    var temp = false
    for (var deviceKey in devices) {
      if (deviceKey === device.deviceKey) {
        temp = true
        break
      }
    }
    return temp
  },

  // 将设备从子网集合中删除
  deleteDeviceFromSubnets: function (subnets, _deviceKey) {
    let subnetId = ''
    var flag = false
    for (var subnetKey in subnets) {
      for (var deviceKey in subnets[subnetKey].deviceList) {
        if (deviceKey === _deviceKey) {
          flag = true
          subnetId = subnetKey
          Vue.delete(subnets[subnetKey].deviceList, deviceKey)
          break
        }
      }
      if (flag) {
        break
      }
    }
    return subnetId
  },

  // 对设备状态进行更新
  updateDeviceAndTopologyStatus: function (alarms, devices, topologyNode, returnObject) {
    for (let alarmKey in alarms) {
      var isLink = alarms[alarmKey].isLink
      var deviceKeyTemp = alarms[alarmKey].elementKey
      // device
      if (isLink === 0 && deviceKeyTemp === returnObject.deviceKey) {
        // 更新对应设备结点的信息
        var a = parseInt(alarms[alarmKey].alarmLevel)
        var b = parseInt(devices[deviceKeyTemp].status)
        if (a > b && returnObject.deviceStatus === 0) {
          Vue.set(returnObject, 'status', alarms[alarmKey].alarmLevel)
          Vue.set(topologyNode, 'status', alarms[alarmKey].alarmLevel)
        }
      }
    }
  },

  // 设备添加ws更新devices
  wsAddDevcie: function (devices, alarms, topologys, returnObject) {
    // 对拓扑节点 进行维护
    for (var i = 0; i < returnObject.length; i++) {
      var topologyNode = {}
      // topologyNode.topologyKey = returnObject[i].deviceKey;
      topologyNode.elementKey = returnObject[i].deviceKey
      topologyNode.horizontalAxis = 0.0
      topologyNode.verticalAxis = 0.0
      topologyNode.belongSubnet = returnObject[i].subnetKey
      topologyNode.nodeType = 0
      topologyNode.topologyName = returnObject[i].displayName
      topologyNode.new = true

      // 对设备对象进行字段的补充
      switch (returnObject[i].deviceStatus) {
        case 0:
          Vue.set(returnObject[i], 'status', ENABLED_STATUS_ENUM)
          Vue.set(topologyNode, 'status', ENABLED_STATUS_ENUM)
          break
        case 1:
          Vue.set(returnObject[i], 'status', DISABLED_STATUS_ENUM)
          Vue.set(topologyNode, 'status', DISABLED_STATUS_ENUM)
          break
        case 2:
          Vue.set(returnObject[i], 'status', DISCOVER_STATUS_ENUM)
          Vue.set(topologyNode, 'status', DISCOVER_STATUS_ENUM)
          break
        default:
      }
      // helperMethods.updateDeviceAndTopologyStatus(alarms, devices, topologyNode, returnObject[i])
      Vue.set(devices, returnObject[i].deviceKey, returnObject[i])
      Vue.set(topologys[topologyNode.belongSubnet].deviceList, topologyNode.elementKey, topologyNode)
    }
  },

  // 设备添加ws更新subnets
  wsAddDeviceOnSubnets: function (subnets, returnObject) {
    for (var i = 0; i < returnObject.length; i++) {
      if (returnObject[i].subnetKey === null) {
        console.log('添加的设备的 subnetKey 不能为 null, 请检查后台代码！')
        return
      }
      if (returnObject[i].subnetKey === '') {
        Vue.set(subnets['0'].deviceList, returnObject[i].deviceKey, returnObject[i])
      } else {
        Vue.set(subnets[returnObject[i].subnetKey].deviceList, returnObject[i].deviceKey, returnObject[i])
      }
    }
  },

}

// 静态方法
let staticMethods = {
  /**
   * @Description  : putDataQuery
   * @author       : ls
   * @date         : 2020/11/19 9:45
   * @param        :
   * @return       :
   */
  putDataQuery: function (val) {
    return DeviceAPI.putDataQueryAPI(val).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  // 获取所有设备
  getAllDeviceCollection: function () {
    return DeviceAPI.getDeviceCollection().then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @Description  : 分页查询service
   * @author       : ls
   * @date         : 2020/5/6 15:48
   * @param        :
   * @return       :
   */
  queryDeviceDataSplitNumber: function (beginItem, endItem, selectList) {
    return DeviceAPI.putDeviceQueryterms(beginItem, endItem, selectList).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @Description  : 查询总数
   * @author       : ls
   * @date         : 2020/5/6 15:58
   * @param        :
   * @return       :
   */
  queryDeviceTotalNumber: function (selectList) {
    return DeviceAPI.putDeviceCounts(selectList).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  getAllDeviceTypeCollection: function () {
    return DeviceAPI.getDeviceTypeCollection().then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_TYPE_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }

    })
  },
  /**
   * @Description  : wangyuanxinghaoService
   * @author       : ls
   * @date         : 2020/4/26 18:32
   * @param        :
   * @return       :
   */
  getAllDeviceModelCollection: function () {
    return DeviceAPI.getDeviceModelCollection().then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_MODEL_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  getDevicePortNum: function (deviceKey) {
    return DeviceAPI.getDevicePortNum(deviceKey).then(result => {
      if (result.data.result) {
        // return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_TYPE_KEY)
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 导入设备 1499
  uploadDeviceFile: function (fileFormData) {
    return DeviceAPI.postUploadDevice(fileFormData).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 导出设备 1595
  downloadDeviceFile: function (conditionSet) {
    return DeviceAPI.putDownloadDevice(conditionSet).then(result => {
      return HelperUtil.downFile(result, DEVICE_DOWNLOAD_FILE_NAME)
    })
  },
  /**
   * @Description  : 网元台账service
   * @author       : ls
   * @date         : 2020/6/9 9:59
   * @param        :
   * @return       :
   */
  downloadDeviceBook: function (conditionSet) {
    return DeviceAPI.putDownloadDeviceBook(conditionSet).then(result => {
      return HelperUtil.downFile(result, DEVICE_BOOK_DOWNLOAD_FILE_NAME)
    })
  },
  // 查询某一设备的所有历史配置 3965
  getDeviceHistoryConfig: function (conditionSet) {
    return DeviceAPI.putDeviceHistoryConfig(conditionSet).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, HISTORY_CONFIG_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 手动获取设备信息 1737
  getDeviceInfoByManual: function (ipAddress) {
    return DeviceAPI.getDeviceInfoByManual(ipAddress).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 设备的条件查询 2939
  conditionQueryDevice: function (conditionSet) {
    return DeviceAPI.putConditionQueryDevice(conditionSet).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  queryDevice: function (conditionSet) {
    return DeviceAPI.putQueryDevice(conditionSet).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, DEVICE_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 设备的修改 2561
  modifyDevice: function (device) {
    // let deviceTemp = HelperUtil.getNewDeviceObject(device)
    return DeviceAPI.putModifyDevice(device).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 批量修改设备
  batchModifyDevice: function (deviceList) {
    let request = []
    deviceList.forEach(device => {
      request.push(DeviceService.modifyDevice(device))
    })
    return Promise.all(request)
  },

  // 设备的新建、复制 1898
  addDevice: function (device) {
    return DeviceAPI.postAddDevice(device).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 设备的批量删除
  batchDeleteDevice: function (deviceKeyList) {
    return DeviceAPI.batchDeleteDevice(deviceKeyList).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 设备删除，级联删除其相关链路
  deleteDeviceAndLinks: function (deviceKeyList, devices, links, ports) {
    let requestSet = []
    requestSet.push(DeviceService.batchDeleteDevice(deviceKeyList))
    let delLinkList = []
    for (let i = 0; i < links.length; i++) {
      let startDeviceKey = links[i].startDeviceKey
      let endDeviceKey = links[i].endDeviceKey
      for (let j = 0; j < deviceKeyList.length; j++) {
        if (deviceKeyList[j] === startDeviceKey || deviceKeyList[j] === endDeviceKey) {
          delLinkList.push(links[i].linkKey)
        }
      }
    }
    if (delLinkList.length > 0) {
      requestSet.push(LinkService.batchLinkDelete(delLinkList))
    }
    let delPortList = []
    for (let k = 0; k < ports.length; k++) {
      let deviceKey = ports[k].deviceKey
      for (let m = 0; m < deviceKeyList.length; m++) {
        if (deviceKeyList[m] === deviceKey && devices[deviceKey].deviceType === 0) {
          delPortList.push(ports[k].portKey)
        }
      }
    }
    if (delPortList.length > 0) {
      requestSet.push(PortListService.batchDeletePortList(delPortList))
    }
    return Promise.all(requestSet).then((post) => {})
  },

  // 下载设备日志 1408
  downloadDeviceLog: function (deviceKey) {
    return DeviceAPI.putDownloadDeviceLog(deviceKey).then(result => {
      var a = DEVICE_LOG_DOWNLOAD_FILE_NAME + HelperUtil.getCurrentTime(1).substring(0, HelperUtil.getCurrentTime(1).indexOf('.'))
      return HelperUtil.downFile(result, a)
    })
  },

  // 设备加入规划 与 修改接口 一致

  // 实现查询对应网段内的设备
  discoverTraditionalDevices: function (ipGroup) {
    return DeviceAPI.putDiscoverTraditionalDevices(ipGroup).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, UUID)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 查看设备历史配置文件   关闭任务

  // 获取设备型号Key
  getDeviceTypeKey: function (conditionSet) {
    return DeviceAPI.putDeviceTypeKey(conditionSet).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 获取设备各端口状态
  getDevicePortStatus: function (panelsDeviceKey) {
    return DeviceAPI.getDevicePortStatus(panelsDeviceKey).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @Description  : 获取端口状态
   * @author       : ls
   * @date         : 2020/11/4 17:01
   * @param        :
   * @return       :
   */
  getDevicePortService: function (deviceKey) {
    return DeviceAPI.getDevicePortAPI(deviceKey).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 获取设备端口配置
  getDevicePortConfig: function (conditionSet) {
    return DeviceAPI.putDevicePortConfig(conditionSet).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 获取指定设备信息
  postDeviceInfo: function (deviceInfo) {
    return DeviceAPI.postDeviceInfo(deviceInfo).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 获取设备端口光功率
  getDeviceLuminousPower: function (portName, device) {
    return DeviceAPI.putDeviceLuminousPower(portName, device).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 批量添加设备
  batchAddDevice: function (deviceList) {
    return DeviceAPI.putBatchAddDevice(deviceList).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // ls设备发现
  searchDevice: function (searchCondition) {
    return DeviceAPI.postSearchDevice(searchCondition).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, UUID)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  }

}

function DeviceService (websocketService = null) {
  // 新建设备
  function subscribeAddDevice (devices, addDevice, subnets, topologys, alarms, mutator = (devices, addDevice, subnets, topologys) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.ADD_DEVICE, devices, (returnObject) => {
      addDevice = []
      helperMethods.wsAddDevcie(devices, alarms, topologys, returnObject)
      for (let length = 0; length < returnObject.length; length++) {
        addDevice.push(JSON.parse(JSON.stringify(devices[returnObject[length].deviceKey])))
      }
      mutator(devices, addDevice, subnets, topologys)
    })
    websocketService.subscribe(DeviceStateSocketApi.MsgType.ADD_DEVICE, subnets, (returnObject) => {
      helperMethods.wsAddDeviceOnSubnets(subnets, returnObject)
      mutator(devices, addDevice, subnets, topologys)
    })
  }
  function unsubscribeAddDevice (devices, subnets, topologys) {
    if (websocketService) {
      websocketService.unsubscribe(DeviceStateSocketApi.MsgType.ADD_DEVICE, devices)
      websocketService.unsubscribe(DeviceStateSocketApi.MsgType.ADD_DEVICE, subnets)
    }
  }

  // 删除设备
  function subscribeDeleteDevice (devices, deleteDevice, subnets, links, topologys, mutator = (devices, deleteDevice, subnets, links, topologys) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, subnets, (returnObject) => {
      console.log('删除设备')
      deleteDevice = []
      for (let i = 0; i < returnObject.length; i++) {
        console.log(returnObject[i].device)
        let devicekey = returnObject[i].deviceKey
        if (devices[devicekey].subnetKey === '') {
          Vue.delete(subnets['0'].deviceList, devicekey)
        } else {
          Vue.delete(subnets[devices[devicekey].subnetKey].deviceList, devicekey)
        }
        deleteDevice.push(devices[returnObject[i].deviceKey])
      }
      window.sessionStorage.setItem('del', '1')
      mutator(devices, deleteDevice, subnets, links, topologys)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, links, (returnObject) => {
      mutator(devices, deleteDevice, subnets, links, topologys)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, topologys, (returnObject) => {
      for (var i = 0; i < returnObject.length; i++) {
        var elementKey = returnObject[i].deviceKey
        for (var elementKeyTemp in topologys) {
          for (var devicekey in topologys[elementKeyTemp].deviceList) {
            if (elementKey === devicekey) {
              // 更新拓扑集合
              Vue.delete(topologys[elementKeyTemp].deviceList, elementKey)
              break
            }
          }
        }
      }
      mutator(devices, deleteDevice, subnets, links, topologys)
    })
    websocketService.subscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, devices, (returnObject) => {
      for (let i = 0; i < returnObject.length; i++) {
        let devicekey = returnObject[i].deviceKey
        Vue.delete(devices, devicekey)
      }
      mutator(devices, deleteDevice, subnets, links, topologys)
    })
  }
  function unsubscribeDeleteDevice (devices, subnets, links, topologys) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, devices)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, subnets)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, links)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DELETE_DEVICE, topologys)
  }

  // 修改设备
  function subscribeModifyDevice (devices, modifyDevice, subnets, topologys, alarms, links, mutator = (devices, modifyDevice, subnets, topologys, alarms, links) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, subnets, async (returnObject) => {
      // 如果设备不存在，则添加该设备
      console.log('修改设备')
      for (var i = 0; i < returnObject.length; i++) {
        console.log(returnObject[i].device)
        if (!helperMethods.isFindDeviceWithDevices(devices, returnObject[i].device)) {
          helperMethods.wsAddDevcie(devices, alarms, topologys, returnObject[i].device)
          // helperMethods.wsAddDeviceOnTopology(devices,topologys,returnObject);
          // 调用有条件查询链路接口，查询设备相关所有链路，绘制设备及链路
          let startDeviceQueryList = [
            {quaryAttribute: 'startDeviceKey', compareSymbol: '==', compareValue: returnObject[i].device.deviceKey}
          ]
          let endDeviceQueryList = [
            {quaryAttribute: 'endDeviceKey', compareSymbol: '==', compareValue: returnObject[i].device.deviceKey}
          ]
          let alarmQueryList = [
            {quaryAttribute: 'deviceKey', compareSymbol: '==', compareValue: returnObject[i].device.deviceKey},
            {quaryAttribute: 'deviceTypeKey', compareSymbol: '==', compareValue: 0}
          // {quaryAttribute: "nodeType", compareSymbol: "==", compareValue: 0},
          ]
          // 调用有条件查询告警接口，查询设备相关告警，放入对应的实时告警列表中
          let alarmAdd = AlarmManagerService.queryAlarmPaging(-1, -1, alarmQueryList).then(result => {
            for (let alarmKey in result) {
              // 将 新增对象 中添加 deviceName 字段名
              Vue.set(returnObject[i], 'deviceName', devices[returnObject[i].device.deviceKey].displayName)
              Vue.set(alarms, alarmKey, result[alarmKey])
            }
          })
          await alarmAdd
          HelperUtil.matchStatus(devices, topologys)
          // helperMethods.updateDeviceAndTopologyStatus(alarms, devices, topologys[returnObject[i].device.deviceKey], returnObject[i].device,subnets)
          LinkService.conditionQueryLink(startDeviceQueryList).then(result => {
            for (let linkKey in result) {
              LinkService.wsAddLink(links, devices, alarms, result[linkKey])
            }
          })
          LinkService.conditionQueryLink(endDeviceQueryList).then(result => {
            for (let linkKey in result) {
              LinkService.wsAddLink(links, devices, alarms, result[linkKey])
            }
          })
        }
        // NOTE:可以修改设备子网
        // 若修改了设备子网，则需要将之前子网中的该设备删除，然后再添加/修改
        if (!helperMethods.isFindDevice(subnets, returnObject[i].device)) {
          helperMethods.deleteDeviceFromSubnets(subnets, returnObject[i].device.deviceKey)
        }
      }
      mutator(devices, modifyDevice, subnets, topologys, alarms, links)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, alarms, (returnObject) => {
      for (var alarmKey in alarms) {
        for (var j = 0; j < returnObject.length; j++) {
          if (alarms[alarmKey].elementKey === returnObject[j].device.deviceKey) {
          // 更新拓扑集合
            alarms[alarmKey].elementName = returnObject[j].device.displayName
            Vue.set(alarms, alarmKey, alarms[alarmKey])
            break
          }
        }
      }
      mutator(devices, modifyDevice, subnets, topologys, alarms, links)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, links, (returnObject) => {
      for (var linkKey in links) {
        for (var j = 0; j < returnObject.length; j++) {
          if (links[linkKey].startDeviceKey === returnObject[j].device.deviceKey) {
            links[linkKey].startDeviceName = returnObject[j].device.displayName
            Vue.set(links, linkKey, links[linkKey])
          } else if (links[linkKey].endDeviceKey === returnObject[j].device.deviceKey) {
            links[linkKey].endDeviceName = returnObject[j].device.displayName
            Vue.set(links, linkKey, links[linkKey])
          }
        }
      }
      mutator(devices, modifyDevice, subnets, topologys, alarms, links)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, devices, (returnObject) => {
      modifyDevice = []
      for (var i = 0; i < returnObject.length; i++) {
      // 更新设备集合
        devices[returnObject[i].device.deviceKey].uuid = returnObject[i].device.uuid
        devices[returnObject[i].device.deviceKey].displayName = returnObject[i].device.displayName
        devices[returnObject[i].device.deviceKey].hostName = returnObject[i].device.hostName
        devices[returnObject[i].device.deviceKey].deviceTypeKey = returnObject[i].device.deviceTypeKey
        devices[returnObject[i].device.deviceKey].deviceModel = returnObject[i].device.deviceModel
        devices[returnObject[i].device.deviceKey].deviceVersion = returnObject[i].device.deviceVersion
        devices[returnObject[i].device.deviceKey].deviceDesc = returnObject[i].device.deviceDesc
        devices[returnObject[i].device.deviceKey].subnetKey = returnObject[i].device.subnetKey
        devices[returnObject[i].device.deviceKey].ipAddress = returnObject[i].device.ipAddress
        devices[returnObject[i].device.deviceKey].bussIpAddress = returnObject[i].device.bussIpAddress
        devices[returnObject[i].device.deviceKey].mac = returnObject[i].device.mac
        devices[returnObject[i].device.deviceKey].snmpVersion = returnObject[i].device.snmpVersion
        devices[returnObject[i].device.deviceKey].snmpPort = returnObject[i].device.snmpPort
        devices[returnObject[i].device.deviceKey].trapPort = returnObject[i].device.trapPort
        devices[returnObject[i].device.deviceKey].snmpGroup = returnObject[i].device.snmpGroup
        devices[returnObject[i].device.deviceKey].startTime = returnObject[i].device.startTime
        devices[returnObject[i].device.deviceKey].delFlag = returnObject[i].device.delFlag
        devices[returnObject[i].device.deviceKey].firmwareKey = returnObject[i].device.firmwareKey
        devices[returnObject[i].device.deviceKey].firmwareFileName = returnObject[i].device.firmwareFileName
        devices[returnObject[i].device.deviceKey].configFileKey = returnObject[i].device.configFileKey
        devices[returnObject[i].device.deviceKey].configFileName = returnObject[i].device.configFileName
        devices[returnObject[i].device.deviceKey].locationName = returnObject[i].device.locationName
        devices[returnObject[i].device.deviceKey].station = returnObject[i].device.station
        devices[returnObject[i].device.deviceKey].manageType = returnObject[i].device.manageType
        devices[returnObject[i].device.deviceKey].bussManageType = returnObject[i].device.bussManageType
        devices[returnObject[i].device.deviceKey].brand = returnObject[i].device.brand
        devices[returnObject[i].device.deviceKey].manufacturerLiaison = returnObject[i].device.manufacturerLiaison
        devices[returnObject[i].device.deviceKey].manufacturerPhone = returnObject[i].device.manufacturerPhone
        devices[returnObject[i].device.deviceKey].manager = returnObject[i].device.manager
        devices[returnObject[i].device.deviceKey].managerPhone = returnObject[i].device.managerPhone
        if (devices[returnObject[i].device.deviceKey].deviceStatus !== returnObject[i].device.deviceStatus) {
          devices[returnObject[i].device.deviceKey].deviceStatus = returnObject[i].device.deviceStatus
          switch (returnObject[i].device.deviceStatus) {
            case 2:
              devices[returnObject[i].device.deviceKey].status = DISCOVER_STATUS_ENUM
              break
            case 1:
              devices[returnObject[i].device.deviceKey].status = DISABLED_STATUS_ENUM
              break
            case 0:
              devices[returnObject[i].device.deviceKey].status = ENABLED_STATUS_ENUM
              break
            default:
          }
        }
        let subnetKeyInTopology = returnObject[i].device.subnetKey
        let deviceKey = returnObject[i].device.deviceKey
        if (returnObject[i].newSubnetKey === returnObject[i].preSubnetKey) {
          topologys[subnetKeyInTopology].deviceList[deviceKey].status = devices[deviceKey].status
          topologys[subnetKeyInTopology].deviceList[deviceKey].topologyName = devices[deviceKey].topologyName
        } else {
          //设备移出子网导致的修改
          Vue.set(topologys[returnObject[i].newSubnetKey].deviceList, deviceKey, topologys[returnObject[i].preSubnetKey].deviceList[deviceKey])
          Vue.delete(topologys[returnObject[i].preSubnetKey].deviceList, deviceKey)
        }


        // topologys[returnObject[i].device.deviceKey].status = devices[returnObject[i].device.deviceKey].status
        // 更新拓扑集合
        topologys[returnObject[i].newSubnetKey].deviceList[returnObject[i].device.deviceKey].topologyName = returnObject[i].device.displayName
        Vue.set(subnets[returnObject[i].device.subnetKey].deviceList, returnObject[i].device.deviceKey, devices[returnObject[i].device.deviceKey])
        modifyDevice.push(devices[returnObject[i].device.deviceKey])
        // helperMethods.updateDeviceAndTopologyStatus(alarms, devices, topologys[returnObject[i].device.deviceKey], returnObject[i].device,subnets)
      }
      AlarmService.updateDeviceAndTopologyAndServerStatus(alarms, devices, topologys,subnets)
      mutator(devices, modifyDevice, subnets, topologys, alarms, links)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, topologys, (returnObject) => {
      mutator(devices, modifyDevice, subnets, topologys, alarms, links)
    })
  }
  function unsubscribeModifyDevice (devices, subnets, topologys, alarms, links) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, devices)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, subnets)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, topologys)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, alarms)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_DEVICE, links)
  }

  // 发现设备
  function subscribeDiscoverDevice (devices, subnets, topologys, mutator = (devices, subnets, topologys) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, devices, (returnObject) => {
      // if(!HelperUtil.isFindItemFromCollection(returnObject.deviceKey,devices)){
      //   // 对网元对象进行字段的补充
      //   Vue.set(returnObject,'status',DISCOVER_STATUS_ENUM);
      //   // 将该对象添加到 devices
      //   Vue.set(devices,returnObject.deviceKey,returnObject);
      // }
      mutator(devices, subnets, topologys)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, subnets, (returnObject) => {
      // if(returnObject.subnetKey === ''){
      //   if(!HelperUtil.isFindItemFromCollection(returnObject.deviceKey,subnets['0'].deviceList)){
      //     Vue.set(subnets['0'].deviceList,returnObject.deviceKey,returnObject);
      //   }
      // }else{
      //   if(!HelperUtil.isFindItemFromCollection(returnObject.deviceKey,subnets[returnObject.subnetKey].deviceList)){
      //     Vue.set(subnets[returnObject.subnetKey].deviceList,returnObject.deviceKey,returnObject);
      //   }
      // }
      mutator(devices, subnets, topologys)
    })

    websocketService.subscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, topologys, (returnObject) => {
      // if(!HelperUtil.isFindItemFromCollection(returnObject.deviceKey,topologys)){
      //   // 对拓扑节点 进行维护
      //   var topologyNode = {};
      //   topologyNode.topologyKey = returnObject.deviceKey;
      //   topologyNode.xAxis = 0.0;
      //   topologyNode.yAxis = 0.0;
      //   // 对拓扑对象进行字段的补充
      //   //在topologyNodeList中添加topologyName 字段
      //   Vue.set(topologyNode, 'topologyName', devices[topologyNode.topologyKey].deviceName)
      //   // 将最新的拓扑图元信息与当前设备状态进行匹配
      //   Vue.set(topologyNode, 'status', devices[topologyNode.topologyKey].status)
      //   // 将该对象添加到topologys
      //   Vue.set(topologys,topologyNode.topologyKey,topologyNode);
      //   //处理网元位置为（0，0）的默认位置，按照一行排开
      //   helperMethods.setTopologyInitLocation(topologys);
      // }
      mutator(devices, subnets, topologys)
    })
  }
  function unsubscribeDiscoverDevice (devices, subnets, topologys) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, devices)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, subnets)
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DISCOVER_DEVICE, topologys)
  }

  // 设备移出子网
  function subscribeMoveDeviceFromSubnet (devices, subnets, topologys, links, alarms, mutator = (devices, subnets, topologys, links, alarms) => {}) {
    let moveDeviceFromSubnet = 'MOVE_DEVICE_FROM_SUBNET'
    websocketService.subscribe(DeviceStateSocketApi.MsgType.MOVE_DEVICE_FROM_SUBNET, moveDeviceFromSubnet, (returnObject) => {
      Vue.delete(devices, returnObject)
      // 将设备从子网中进行删除
      let subnetId = helperMethods.deleteDeviceFromSubnets(subnets, returnObject)
      if (subnetId !== '') {
        Vue.delete(topologys[subnetId].deviceList, returnObject)
      }
      // 把设备、设备相关链路、设备相关告警从前台移除
      let startDeviceQueryList = [
        {quaryAttribute: 'startDeviceKey', compareSymbol: '==', compareValue: returnObject}
      ]
      let endDeviceQueryList = [
        {quaryAttribute: 'endDeviceKey', compareSymbol: '==', compareValue: returnObject}
      ]
      let alarmQueryList = [
        {quaryAttribute: 'deviceKey', compareSymbol: '==', compareValue: returnObject},
        {quaryAttribute: 'nodeType', compareSymbol: '==', compareValue: 0}
      ]
      LinkService.conditionQueryLink(startDeviceQueryList).then(result => {
        for (let linkKey in result) {
          Vue.delete(links, linkKey)
        }
      })
      LinkService.conditionQueryLink(endDeviceQueryList).then(result => {
        for (let linkKey in result) {
          Vue.delete(links, linkKey)
        }
      })
      AlarmManagerService.queryAlarmPaging(-1, -1, alarmQueryList).then(result => {
        for (let alarmKey in result) {
          Vue.delete(alarms, alarmKey)
        }
      })
      mutator(devices, subnets, topologys, links, alarms)
    })
  }
  function unsubscribeMoveDeviceFromSubnet () {
    let moveDeviceFromSubnet = 'MOVE_DEVICE_FROM_SUBNET'
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MOVE_DEVICE_FROM_SUBNET, moveDeviceFromSubnet)
  }

  return Object.freeze(Object.assign(
    {
      // object methods comes here
      subscribeAddDevice,
      unsubscribeAddDevice,
      subscribeDeleteDevice,
      unsubscribeDeleteDevice,
      subscribeModifyDevice,
      unsubscribeModifyDevice,
      subscribeDiscoverDevice,
      unsubscribeDiscoverDevice,
      subscribeMoveDeviceFromSubnet,
      unsubscribeMoveDeviceFromSubnet
    },
    staticMethods
  ))
}
// inject static methods
Object.assign(DeviceService, staticMethods)
export default DeviceService
