import LinkAPI from '../../api/restApis/LinkAPI'
import HelperUtil from '../../utils/HelperUtil'
import Vue from 'vue'

import {
  LINK_DOWNLOAD_FILE_NAME,
  DISABLED_STATUS_ENUM, DISCOVER_STATUS_ENUM, ENABLED_STATUS_ENUM,
  LINK_KEY
} from '../../utils/constantCollection'
import DeviceStateSocketApi from '../../api/websocketApis/DeviceStateSocketApi'

// 静态方法
let staticMethods = {
  // 获取所有链路
  getAllLinkCollection: function () {
    return LinkAPI.getLinkCollection().then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, LINK_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 批量删除链路
  batchLinkDelete: function (delLinkKeys) {
    return LinkAPI.deleteLink(delLinkKeys).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },

  // 根据告警原因更新链路状态
  updateLinkStatusByAlarmCause: function (links, devices, alarms, returnObject) {
    var startFlag = false
    var endFlag = false
    for (var deviceKey in devices) {
      if (returnObject.startDeviceKey === deviceKey) {
        // 在 linkList 中添加 startDeviceName 字段
        Vue.set(returnObject, 'startDeviceName', devices[deviceKey].displayName)
        startFlag = true
      }
      if (returnObject.endDeviceKey === deviceKey) {
        // 在 linkList 中添加 endDeviceName 字段
        Vue.set(returnObject, 'endDeviceName', devices[deviceKey].displayName)
        endFlag = true
      }
      if (startFlag && endFlag) {
        break
      }
    }
    // 添加 status 字段
    var startStatus = returnObject.status
    for (var alarmKey in alarms) {
      if ((alarms[alarmKey].elementKey === returnObject.linkKey) && alarms[alarmKey].alarmCode === 'A_LINK_ABNORMAL') {
        if (parseInt(startStatus) < alarms[alarmKey].alarmLevel) {
          startStatus = alarms[alarmKey].alarmLevel
        }
      }
    }
    if (startStatus === DISABLED_STATUS_ENUM || startStatus === ENABLED_STATUS_ENUM) {
      switch (returnObject.linkStatus) {
        case 0:
          Vue.set(returnObject, 'status', ENABLED_STATUS_ENUM)
          break
        case 1:
          Vue.set(returnObject, 'status', DISCOVER_STATUS_ENUM)
          break
        default:
      }
    } else {
      Vue.set(returnObject, 'status', startStatus)
    }
    Vue.set(links, returnObject.linkKey, returnObject)
  },
  // 添加链路
  addLink: function (link) {
    return LinkAPI.postLinkAdd(link).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  // ws 添加链路
  wsAddLink: function (links, devices, alarms, returnObject) {
    // 对link对象进行字段的补充
    for (var i = 0; i < returnObject.length; i++) {
      switch (returnObject[i].linkStatus) {
        case 0:
          Vue.set(returnObject[i], 'status', ENABLED_STATUS_ENUM)
          break
        case 1:
          Vue.set(returnObject[i], 'status', DISCOVER_STATUS_ENUM)
          break
        default:
      }
      staticMethods.updateLinkStatusByAlarmCause(links, devices, alarms, returnObject[i])
    }
  },
  // 修改链路
  modifyLink: function (link) {
    let linkTemp = HelperUtil.getNewLinkObject(link)
    return LinkAPI.putModifyLink(linkTemp).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  // 查询链路
  conditionQueryLink: function (conditionSet) {
    return LinkAPI.putConditionQueryLink(conditionSet).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, LINK_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @description   : 导入
   * @author        : ls
   * @date          : 2020/6/23 21:59
   * @param         :
   * @return        :
   **/
  uploadLinkFile: function (fileFormData) {
    return LinkAPI.postUploadLink(fileFormData).then(result => {
      if (result.data.result) {
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @description   : 导出
   * @author        : ls
   * @date          : 2020/6/23 21:58
   * @param         :
   * @return        :
   **/
  downloadLinkFile: function (conditionSet) {
    return LinkAPI.putDownloadLink(conditionSet).then(result => {
      return HelperUtil.downFile(result, LINK_DOWNLOAD_FILE_NAME)
    })
  },
  /**
   * @Description  : 分页查询
   * @author       : ls
   * @date         : 2020/6/24 9:58
   * @param        :
   * @return       :
   */
  queryLinkDataSplitNumber: function (beginItem, endItem, selectList) {
    return LinkAPI.putLinkQueryterms(beginItem, endItem, selectList).then(result => {
      if (result.data.result) {
        return HelperUtil.arrayToObject(result.data.returnValue, LINK_KEY)
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
  /**
   * @Description  : 查询总数
   * @author       : ls
   * @date         : 2020/6/24 9:58
   * @param        :
   * @return       :
   */
  queryLinkTotalNumber: function (selectList) {
    return LinkAPI.putLinkCounts(selectList).then(result => {
      if (result.data.result) {
        return result.data.returnValue
      } else {
        return HelperUtil.returnPromiseRejectObj(result)
      }
    })
  },
}

function LinkService (websocketService = null) {
  // 新建链路
  function subscribeAddLink (links, devices, alarms, mutator = (links) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.ADD_LINK, links, (returnObject) => {
      LinkService.wsAddLink(links, devices, alarms, returnObject)
      mutator(links)
    })
  }
  function unsubscribeAddLink (links) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.ADD_LINK, links)
  }

  // 删除链路
  function subscribeDeleteLink (links, mutator = (links) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.DELETE_LINK, links, (returnObject) => {
      for (var i = 0; i < returnObject.length; i++) {
        Vue.delete(links, returnObject[i])
      }
      mutator(links)
    })
  }
  function unsubscribeDeleteLink (links) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DELETE_LINK, links)
  }

  // 修改链路
  function subscribeModifyLink (links, devices, alarms, mutator = (links) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.MODIFY_LINK, links, (returnObject) => {
      for (var i = 0; i < returnObject.length; i++) {
        let linkKey = returnObject[i].linkKey
        links[linkKey].linkName = returnObject[i].linkName
        links[linkKey].startDeviceKey = returnObject[i].startDeviceKey
        links[linkKey].startPortName = returnObject[i].startPortName
        links[linkKey].endDeviceKey = returnObject[i].endDeviceKey
        links[linkKey].endPortName = returnObject[i].endPortName
        links[linkKey].linkType = returnObject[i].linkType
        links[linkKey].delFlag = returnObject[i].delFlag
        links[linkKey].modifyTime = returnObject[i].modifyTime
        links[linkKey].endGroupID = returnObject[i].endGroupID
        links[linkKey].startGroupID = returnObject[i].startGroupID
        links[linkKey].modifyTime = returnObject[i].modifyTime

        if (links[linkKey].linkStatus !== returnObject[i].linkStatus) {
          links[linkKey].linkStatus = returnObject[i].linkStatus
          switch (links[linkKey].linkStatus) {
            case 0:
              links[linkKey].status = ENABLED_STATUS_ENUM
              LinkService.updateLinkStatusByAlarmCause(links, devices, alarms, links[linkKey])
              break
            case 1:
              links[linkKey].status = DISCOVER_STATUS_ENUM
              break
            default:
          }
        }
      }
      mutator(links)
    })
  }
  function unsubscribeModifyLink (links) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.MODIFY_LINK, links)
  }

  // 发现链路
  function subscribeDiscoverLink (links, mutator = (links) => {}) {
    websocketService.subscribe(DeviceStateSocketApi.MsgType.DISCOVER_LINK, links, (returnObject) => {
      // if(!HelperUtil.isFindItemFromCollection(returnObject.linkKey,links)){
      //   // 对对象进行字段的补充
      //   Vue.set(returnObject,'status',DISCOVER_STATUS_ENUM);
      //   // 将该对象添加到 devices
      //   Vue.set(links,returnObject.linkKey,returnObject);
      // }
      mutator(links)
    })
  }
  function unsubscribeDiscoverLink (links) {
    websocketService.unsubscribe(DeviceStateSocketApi.MsgType.DISCOVER_LINK, links)
  }

  return Object.freeze(Object.assign(
    {
      // object methods comes here
      subscribeAddLink,
      unsubscribeAddLink,
      subscribeDeleteLink,
      unsubscribeDeleteLink,
      subscribeModifyLink,
      unsubscribeModifyLink,
      subscribeDiscoverLink,
      unsubscribeDiscoverLink
    },
    staticMethods
  ))
}
// inject static methods
Object.assign(LinkService, staticMethods)
export default LinkService
