import {
  CONFIG_DATE_URL, FILE_ERROR_CODE, LANGUAGE_CHINESE, LANGUAGE_ENGLISH, LANGUAGE_LOCALSTORAGE,
  SERVER_CODE, USER_NAME, LOCKED
} from './constantCollection'
import Vue from 'vue'
import {STATUS_CODE_ZH_CN} from './StatusCode_zh_cn'
import {STATUS_CODE_EN} from './StatusCode_en'
import router from '../router'
import store from '../store.js'
import {LEGITIMACY_CHECK_STATUS_CODE_ZH_CN} from './LegitimacyCheckStatusCode_zh_cn'
import {LEGITIMACY_CHECK_STATUS_CODE_EN} from './LegitimacyCheckStatusCode_en'
import Echart from 'echarts'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

// 静态方法
let staticMethods = {
  /**
   * @Description  : handleDisa
   * @author       : ls
   * @date         : 2021/3/25 15:09
   * @param        :
   * @return       :
   */
  handleDisa: function (val, device, alarmCollection) {
    let alarmList = []
    alarmList = Object.values(alarmCollection)
    for (var i = 0; i < alarmList.length; i++) {
      if (alarmList[i].elementKey === device.deviceKey && alarmList[i].alarmCode === 'A_DEVICE_STATUS') {
        val = 1
        break
      }
    }
    return val
  },
  /**
   * @Description  : v1: deviceModelList0 v2:deviceType v3 deviceList0
   * @author       : ls
   * @date         : 2020/11/23 10:57
   * @param        :
   * @return       :
   */
  deviceTypeCha: function (v1, v2, v3) {
    var deviceModelList = []
    var deviceList = []
    var ret = []
    for (let j in v1) {
      if (v2.length === 0) {
        deviceModelList.push(v1[j])
      }
      for (let key1 in v2) {
        if (v2[key1] === v1[j]['key']) {
          deviceModelList.push(v1[j])
        }
      }
    }
    for (let i in v3) {
      if (v2.length === 0) {
        deviceList.push(v3[i])
      }
      for (let key in v2) {
        if (v2[key] === v3[i]['deviceTypeKey']) {
          deviceList.push(v3[i])
        }
      }
    }
    ret.push(deviceModelList)
    ret.push(deviceList)
    return ret
  },
  /**
   * @Description  : v1 deviceList0 v2 deviceType v3 deviceModel
   * @author       : ls
   * @date         : 2020/11/23 11:16
   * @param        :
   * @return       :
   */
  deviceModelCha: function (v1, v2, v3) {
    var deviceList = []
    for (let k in v1) {
      if (v3.length === 0) {
        if (v2.length === 0) {
          deviceList.push(v1[k])
        } else {
          for (let t in v2) {
            if (v1[k].deviceTypeKey === v2[t]) {
              deviceList.push(v1[k])
            }
          }
        }
      }
      for (let key in v3) {
        if (v3[key] === v1[k]['deviceModel']) {
          if (v2.length === 0) {
            deviceList.push(v1[k])
          } else {
            for (let key1 in v2) {
              if (v2[key1] === v1[k]['deviceTypeKey']) {
                deviceList.push(v1[k])
              }
            }
          }
        }
      }
    }
    return deviceList
  },
  // 对象数组去重
  unique (array) {
    return Array.from(new Set(array))
  },

  // 将对象转换成Array数组
  objectAsArray: function (object) {
    return Object.values(object)
  },

  // 将数组转换成对象形式，将数组中元素的Key作为对象的字段名
  arrayToObject: function (collection, keyName) {
    var returnObj = {}
    if (collection === null) {
      collection = []
    }
    for (let i = 0; i < collection.length; i++) {
      returnObj[collection[i][keyName]] = collection[i]
    }
    return returnObj
  },

  arrayToObject1: function (collection, keyName) {
    var returnObj = {}
    if (collection === null) {
      collection = []
    }
    for (let i = 0; i < collection.length; i++) {
      collection[i]['number'] = i
      returnObj[collection[i][keyName]] = collection[i]
    }
    return returnObj
  },

  // 在集合中是否能找到该元素
  isFindItemFromCollection: function (key, collection) {
    var flag = false
    for (var keyTemp in collection) {
      if (keyTemp === key) {
        flag = true
        break
      }
    }
    return flag
  },

  // 导出文件通用模板
  downFile: function (result, fileName) {
    if (result.data.byteLength === 0) {
      let fileNoteFind_code = HelperUtil.getStatusCodeObjectByCode(FILE_ERROR_CODE)
      return HelperUtil.returnPromiseRejectObj(
        {
          data: {
            faultCode: fileNoteFind_code.code,
            faultCause: null
          }
        }
      )
    }
    if (!result) {
      let server_code = HelperUtil.getStatusCodeObjectByCode(SERVER_CODE)
      return HelperUtil.returnPromiseRejectObj(
        {
          data: {
            faultCode: server_code.code,
            faultCause: null
          }
        }
      )
    }
    let url = window.URL.createObjectURL(new Blob([result.data], { type: 'application/x-xls' }))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    window.URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
    return null
  },

  viewFile(result){
    let blob = new Blob([result.data], { type: 'application/x-xls' })
    return blob
    // var fr = new FileReader();
    // fr.addEventListener("load", function(ev) {
    //   console.log(ev.target.result);//会输出字符：a
    //   let content = ev.target.result;
    //   return content
    // });
    // fr.readAsText(blob);
  },

  // ip转数字
  ipToInt (ipString) {
    let num = 0
    ipString = ipString.split('.')
    num = Number(ipString[0]) * 256 * 256 * 256 + Number(ipString[1]) * 256 * 256 + Number(ipString[2]) * 256 + Number(ipString[3])
    num = num >>> 0
    return num
  },

  // 数字转ip
  intToIp (num) {
    let str
    let ipNumber = new Array()
    ipNumber[0] = (num >>> 24) >>> 0
    ipNumber[1] = ((num << 8) >>> 24) >>> 0
    ipNumber[2] = (num << 16) >>> 24
    ipNumber[3] = (num << 24) >>> 24
    str = String(ipNumber[0]) + '.' + String(ipNumber[1]) + '.' + String(ipNumber[2]) + '.' + String(ipNumber[3])
    return str
  },
  /**
   * @Description  : 格式化时间
   * @author       : ls
   * @date         : 2020/5/22 11:00
   * @param        :
   * @return       :
   */
  formatFirstDate: function (val) {
    var showDate
    var arr
    if (val !== '') {
      arr = val.split('.')
      showDate = '' + arr[0].substring(0, 4) + '-' + arr[0].substring(4, 6) + '-' + arr[0].substring(6, 8) + ' '
      showDate = showDate + arr[1].substring(0, 2) + ':' + arr[1].substring(2, 4) + ':' + arr[1].substring(4, 6) + '.' + arr[2]
    } else {
      showDate = ''
    }
    return showDate
  },
  /**
   * @Description  : 默认时间
   * @author       : ls
   * @date         : 2020/5/25 10:41
   * @param        :
   * @return       :
   */
  setDefaultDateTime: function () {
    var arr = []
    const start = new Date()
    const end = new Date()
    start.setTime(start.getTime() - 3600 * 1000)
    arr.push(start)
    arr.push(end)
    return arr
  },
  /**
   * @Description  : 获取时间
   * @author       : ls
   * @date         : 2020/4/29 15:39
   * @param        :
   * @return       :
   */
  getTimeInit: function (val) {
    var year
    var month
    var day
    var hours
    var minutes
    if (val !== '' && val !== null) {
      year = '' + val.getFullYear()
      month = '' + (val.getMonth() + 1)
      day = '' + val.getDate()
      hours = '' + val.getHours()
      minutes = '' + val.getMinutes()
      if (month.length === 1) {
        month = '0' + month
      }
      if (day.length === 1) {
        day = '0' + day
      }
      if (hours.length === 1) {
        hours = '0' + hours
      }
      if (minutes.length === 1) {
        minutes = '0' + minutes
      }
      return '' + year + month + day + '.' + hours + minutes
    } else {
      return ''
    }
  },
  /**
   * @Description  : 日期转字符串
   * @author       : ls
   * @date         : 2020/5/26 11:18
   * @param        :
   * @return       :
   */
  dateToString: function (date) {
    let timeString = ''
    let year
    let month
    let day
    let hours
    let minutes
    let seconds
    if (date !== '' && date !== null) {
      year = '' + date.getFullYear()
      month = '' + (date.getMonth() + 1)
      day = '' + date.getDate()
      hours = '' + date.getHours()
      minutes = '' + date.getMinutes()
      seconds = '' + date.getSeconds()
      if (month.length === 1) {
        month = '0' + month
      }
      if (day.length === 1) {
        day = '0' + day
      }
      if (hours.length === 1) {
        hours = '0' + hours
      }
      if (minutes.length === 1) {
        minutes = '0' + minutes
      }
      if (seconds.length === 1) {
        seconds = '0' + seconds
      }
      timeString = '' + year + month + day + '.' + hours + minutes + seconds
      return timeString
    } else {
      return ''
    }
  },
  /**
   * @Description  : 字符串转日期
   * @author       : ls
   * @date         : 2020/5/26 11:20
   * @param        :
   * @return       :
   */
  stringToDate: function (str) {
    let date = ''
    if (str !== '' && str !== null) {
      if (str.length !== 15) {
      } else {
        let timeList = str.split('.')
        let time = timeList[0].substring(0, 4) + '-' + timeList[0].substring(4, 6) + '-' + timeList[0].substring(6, 8) + ' '
        time = time + timeList[1].substring(0, 2) + ':' + timeList[1].substring(2, 4) + ':' + timeList[1].substring(4, 6)
        date = new Date(time)
      }
    }
    return date
  },
  /**
   * @Description  : 获取时分秒时间
   * @author       : ls
   * @date         : 2020/5/26 9:56
   * @param        :
   * @return       :
   */
  getTimeSecondsInit: function (val) {
    var year
    var month
    var day
    var hours
    var minutes
    var seconds
    if (val !== '' && val !== null) {
      year = '' + val.getFullYear()
      month = '' + (val.getMonth() + 1)
      day = '' + val.getDate()
      hours = '' + val.getHours()
      minutes = '' + val.getMinutes()
      seconds = '' + val.getSeconds()
      seconds = seconds < 10 ? ('0' + seconds) : seconds
      if (month.length === 1) {
        month = '0' + month
      }
      if (day.length === 1) {
        day = '0' + day
      }
      if (hours.length === 1) {
        hours = '0' + hours
      }
      if (minutes.length === 1) {
        minutes = '0' + minutes
      }
      return '' + year + month + day + '.' + hours + minutes + seconds
    } else {
      return ''
    }
  },
  /**
   * @Description  : 获取周
   * @author       : ls
   * @date         : 2020/6/4 12:59
   * @param        :
   * @return       :
   */
  getWeekNumber: function (dt) {
    let d1 = new Date(dt)
    let d2 = new Date(dt)
    d2.setMonth(0)
    d2.setDate(1)
    let rq = d1 - d2
    let days = Math.ceil(rq / (24 * 60 * 60 * 1000)) + 1
    let num = Math.ceil(days / 7)
    return num
  },
  /**
   * @Description  : TimeTran
   * @author       : ls
   * @date         : 2020/5/9 10:02
   * @param        :
   * @return       :
   */
  timePass: function (time, flag, begin, end) {
    var a = []
    var addTime
    var hours
    var day
    var week
    var month
    switch (flag) {
      case 1:
        month = '' + (time.getMonth() + 1)
        day = '' + time.getDate()
        if (month.length === 1) {
          month = '0' + month
        }
        if (day.length === 1) {
          day = '0' + day
        }
        hours = '' + time.getHours()
        if (hours.length === 1) {
          addTime = '' + time.getFullYear() + '-' + month + '-' + day + ' ' + '0' + hours + ':00'
        } else {
          addTime = '' + time.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':00'
        }
        break
      case 2:
        addTime = '' + time.getFullYear()
        month = '' + (time.getMonth() + 1)
        day = '' + time.getDate()
        if (month.length === 1) {
          month = '0' + month
        }
        if (day.length === 1) {
          day = '0' + day
        }
        addTime = addTime + '-' + month + '-' + day
        break
      case 3:
        addTime = '' + time.getFullYear()
        month = '' + (time.getMonth() + 1)
        day = '' + time.getDate()
        week = HelperUtil.getWeekNumber(addTime + '-' + month + '-' + day)
        addTime = addTime + '-' + week
        break
      case 4:
        var yearFlag
        var monthFlag
        yearFlag = begin.getFullYear()
        monthFlag = begin.getMonth()
        while (yearFlag < end.getFullYear() || (yearFlag === end.getFullYear() && monthFlag <= end.getMonth())) {
          month = '' + (monthFlag + 1)
          if (month.length === 1) {
            addTime = '' + yearFlag + '-0' + month
          } else {
            addTime = '' + yearFlag + '-' + month
          }
          a.push(addTime)
          monthFlag++
          if (monthFlag > 11) {
            monthFlag = 0
            yearFlag++
          }
        }
        break
    }
    if (a.length !== 0) {
      return a
    }
    return addTime
  },
  /**
   * @Description  : IP合法性校验
   * @author       : ls
   * @date         : 2020/4/23 14:26
   * @param        :
   * @return       :
   */
  ipCheck1: function (ip1, ip2) {
    var reg = /^([1-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))(.([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3}$/

    var re = new RegExp(reg)
    if (ip1 === '' || ip2 === '') {
      return false
    }
    if ((!re.test(ip1)) || (!re.test(ip2))) {
      this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.IPCHECK_CODE), this.$t('DeviceConfigurationManagement.ipAddress'))
      return false
    } else {
      return true
    }
  },
  checkIpOrder: function (ip1, ip2) {
    let ipOne = this.ipToInt(ip1)
    let ipTwo = this.ipToInt(ip2)
    if (ipOne < ipTwo) {
      return true
    } else {
      return false
    }
  },

  checkIpIntervalLength: function (ip1, ip2) {
    let ipFlag1 = ip1.substring(0, ip1.lastIndexOf('.'))
    let ipFlag2 = ip2.substring(0, ip2.lastIndexOf('.'))
    if (ipFlag1 === ipFlag2) {
      return true
    } else {
      return false
    }
  },

  // IP网段分组
  ipToGroup: function (ip1, ip2) {
    let ipList = []
    let ipListByGroup = []
    let ipInt1 = this.ipToInt(ip1)
    let ipInt2 = this.ipToInt(ip2)

    // 将所有ip写进一个list
    for (var i = ipInt1; i <= ipInt2; i++) {
      ipList.push(this.intToIp(i))
    }

    // 将ip十个人一组划分写进List
    let partOfGroup = parseInt(ipList.length / 10)
    let remainIp = ipList.length % 10
    if (partOfGroup === 0) {
      let ipPart = []
      for (var n = 0; n < ipList.length; n++) {
        ipPart.push(ipList[n])
      }
      ipListByGroup.push(ipPart)
      return ipListByGroup
    }
    for (let group = 0; group < partOfGroup; group++) {
      let partOfList = []
      for (let j = 0; j < 10; j++) {
        partOfList.push(ipList[group * 10 + j])
      }
      ipListByGroup.push(partOfList)
    }

    // 将最后不够十个ip写进一个list放入Group
    let remainIpList = []
    if (remainIp > 0) {
      for (let m = 0; m < remainIp; m++) {
        remainIpList.push(ipList[partOfGroup * 10 + m])
      }
      ipListByGroup.push(remainIpList)
    }
    return ipListByGroup
  },

  // 获取新的设备对象
  getNewDeviceObject: function (device) {
    let deviceTemp = {}
    deviceTemp.deviceKey = device.deviceKey
    deviceTemp.uuid = device.uuid
    deviceTemp.displayName = device.displayName
    deviceTemp.deviceTypeKey = device.deviceTypeKey
    deviceTemp.configFileKey = device.configFileKey
    deviceTemp.configFileName = device.configFileName
    deviceTemp.deviceModel = device.deviceModel
    deviceTemp.station = device.station
    deviceTemp.locationName = device.locationName
    deviceTemp.subnetKey = device.subnetKey
    deviceTemp.ipAddress = device.ipAddress
    deviceTemp.bussIpAddress = device.bussIpAddress
    deviceTemp.deviceStatus = device.deviceStatus
    deviceTemp.deviceVersion = device.deviceVersion
    deviceTemp.startTime = device.startTime
    deviceTemp.deviceDesc = device.deviceDesc
    deviceTemp.manageType = device.manageType
    deviceTemp.delFlag = device.delFlag
    deviceTemp.modifyTime = device.modifyTime
    deviceTemp.brand = device.brand
    deviceTemp.manufacturerLiaison = device.manufacturerLiaison
    deviceTemp.manufacturerPhone = device.manufacturerPhone
    deviceTemp.manager = device.manager
    deviceTemp.managerPhone = device.managerPhone
    if (device.manageType === 2) {
      deviceTemp.ipmiUserName = device.ipmiUserName
      deviceTemp.ipmiPassword = device.ipmiPassword
    }
    if (device.manageType === 0) {
      deviceTemp.snmpVersion = device.deviceSNMP
      deviceTemp.snmpPort = device.snmpPort
      deviceTemp.trapPort = device.trapPort
      deviceTemp.snmpGroup = device.snmpGroupName
    }
    return deviceTemp
  },

  // 获取新的链路对象
  getNewLinkObject: function (link) {
    let linkTemp = {}
    linkTemp.linkKey = link.linkKey
    linkTemp.linkName = link.linkName
    linkTemp.startDeviceKey = link.startDeviceKey
    linkTemp.startPortName = link.startPortName
    linkTemp.endDeviceKey = link.endDeviceKey
    linkTemp.endPortName = link.endPortName
    linkTemp.linkStatus = link.linkStatus
    linkTemp.linkType = link.linkType
    linkTemp.delFlag = link.delFlag
    linkTemp.modifyTime = link.modifyTime
    return linkTemp
  },

  // 获取新的Code对象
  getNewCodeObject: function (code) {
    let codeTemp = {}
    codeTemp.code = code.code
    codeTemp.message = code.message
    return codeTemp
  },

  // 获取状态码的对象
  getStatusCodeObject: function () {
    let language = window.localStorage.getItem(LANGUAGE_LOCALSTORAGE)
    let statusCode = null
    let checkStatusCode = null
    switch (language) {
      case LANGUAGE_CHINESE:
        statusCode = STATUS_CODE_ZH_CN
        checkStatusCode = LEGITIMACY_CHECK_STATUS_CODE_ZH_CN
        break
      case LANGUAGE_ENGLISH:
        statusCode = STATUS_CODE_EN
        checkStatusCode = LEGITIMACY_CHECK_STATUS_CODE_EN
        break
      default:
        statusCode = STATUS_CODE_ZH_CN
        checkStatusCode = LEGITIMACY_CHECK_STATUS_CODE_ZH_CN
    }
    return {
      statusCode: statusCode,
      checkStatusCode: checkStatusCode
    }
  },

  // 按照code去获取对应的StatusCode
  getStatusCodeObjectByCode: function (code) {
    let statusCode = HelperUtil.getStatusCodeObject().statusCode
    return statusCode[code]
  },

  // 按照code去获取对应的StatusCode
  getCheckStatusCodeObjectByCode: function (code) {
    let checkStatusCode = HelperUtil.getStatusCodeObject().checkStatusCode
    return checkStatusCode[code]
  },

  // 返回Promise 的Reject 对象
  returnPromiseRejectObj: function (result) {
    let statusCode = HelperUtil.getStatusCodeObject().statusCode
    if (statusCode[result.data.faultCode] !== undefined) {
      // 5.16新需求： 若 faultCause 不为空，则将 faultCause 拼接到 message 后面
      if (result.data.faultCause !== null) {
        let flag = HelperUtil.getNewCodeObject(statusCode[result.data.faultCode])
        flag.message += ':' + result.data.faultCause
        return Promise.reject(flag)
      }
      return Promise.reject(statusCode[result.data.faultCode])
    } else {
      // return Promise.reject({errorCode:result.data.faultCode,errorCause:result.data.faultCause});
      return Promise.reject(statusCode['undefined'])
    }
  },
  /**
   * @Description  : 导出
   * @author       : ls
   * @date         : 2020/5/12 18:59
   * @param        :
   * @return       :
   */
  downloadImage () {
    var myChart = Echart.getInstanceByDom(document.getElementById('staticId'))
    var url = myChart.getConnectedDataURL({
      pixelRatio: 5,
      backgroundColor: '#fff',
      excludeComponents: [
        'toolbox'
      ],
      type: 'png'
    })
    var $a = document.createElement('a')
    var type = 'png'
    $a.download = myChart.getOption().title[0].text + '.' + type
    $a.target = '_blank'
    $a.href = url
    if (typeof MouseEvent === 'function') {
      var evt = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: false
      })
      $a.dispatchEvent(evt)
    } else {
      var html = ''

      '<body style="margin:0;">'
      '![](' + url + ')'
      '</body>'
      var tab = window.open()
      tab.document.write(html)
    }
  },
  /**
   * @Description  : daochubiaoge
   * @author       : ls
   * @date         : 2020/5/12 19:11
   * @param        :
   * @return       :
   */
  downloadExcel (val) {
    var wb = XLSX.utils.table_to_book(document.querySelector('#myTable'), {raw: true})
    var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
    try {
      FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), val)
    } catch (e) {
      if (typeof console !== 'undefined') console.log(e, wbout)
    }
    return wbout
  },
  // 获取系统配置参数
  getSystemParams: function (param) {
    var returnResult = ''
    $.ajax({
      url: CONFIG_DATE_URL, // url路径
      type: 'GET', // GET
      async: false, // 或false,是否异步
      timeout: 5000, // 超时时间
      dataType: 'json', // 返回的数据格式：
      success: function (data, textStatus, jqXHR) {
        returnResult = data[param]
      },
      error: function (xhr, textStatus) {
        console.log('全局参数配置失败！')
      }
    })
    return returnResult
  },

  // 获取请求根路径
  getRequestRootURL: function () {
    return HelperUtil.getSystemParams('rootUrl')
  },

  // 获取websocket请求路径
  getWebSocketRequestURL: function () {
    return HelperUtil.getSystemParams('webSocketUrl')
  },

  // 获取交换机配置url以及用户名、密码配置
  getInterchangeRequestConfig: function () {
    return HelperUtil.getSystemParams('interchangeData')
  },

  // 获取系统模式
  getSystemMode: function () {
    /*
        TRAD ：传统模式
        SDNC ：SDNC模式
     */
    return HelperUtil.getSystemParams('systemMode')
  },

  /**
   * @Description  : 获取当前时间
   * @author       : ls
   * @date         : 2020/4/24 14:56
   * @param        :
   * @return       :
   */
  getCurrentTime: function (val) {
    var date = new Date()
    var seperator1 = '-'
    var seperator2 = ':'
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    var hour = date.getHours() + ''
    if (hour.length < 2) {
      hour = '0' + hour
    }
    var minu = date.getMinutes() + ''
    if (minu.length < 2) {
      minu = '0' + minu
    }
    var sec = date.getSeconds() + ''
    if (sec.length < 2) {
      sec = '0' + sec
    }
    var ms = date.getMilliseconds() + ''
    if (ms.length == 1) {
      ms = '00' + ms
    } else if (ms.length == 2) {
      ms = '0' + ms
    }
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    var currentdate
    if (val !== undefined) {
      currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + seperator2 + minu + seperator2 + sec + '.' + ms
    } else {
      currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + seperator2 + minu + seperator2 + sec
    }

    return currentdate
  },
  /**
   * @Description  : deviceTypeChangeDevice
   * @author       : ls
   * @date         : 2021/3/3 16:20
   * @param        :
   * @return       :
   */
  deviceTypeChangeDevice: function (v1, v2, v3, v4) {
    var ret = []
    var ret1 = []
    var ret2 = []
    if (v2 === '*' || v2 === null || v2 === '') {
      ret.push(v1)
    } else {
      ret1 = v1.filter(item => {
        return item.deviceTypeKey === v2
      })
      ret.push(ret1)
    }
    v3 = ''
    ret.push(v3)
    for (let i in v4) {
      if (v2 === null || v2 === '*' || v2 === '') {
        ret2.push(v4[i])
      }
      if (v2 === v4[i]['deviceTypeKey']) {
        ret2.push(v4[i])
      }
    }
    ret.push(ret2)
    return ret
  },
  /**
   * @Description  : deviceTypeChangeCURD
   * @author       : ls
   * @date         : 2021/3/8 10:15
   * @param        :
   * @return       :
   */
  deviceTypeChangeCURD: function (v1, v2, v3, v4) {
    var ret = []
    var ret1 = []
    var ret2 = []
    if (v2.length !== 0) {
      var flag = v2.some(item => {
        return item === '*'
      })
      if (flag) {
        ret.push(v1)
      } else {
        var a = []
        for (let j = 0; j < v1.length; j++) {
          for (let t = 0; t < v2.length; t++) {
            if (v2[t] === v1[j].deviceTypeKey) {
              a.push(v1[j])
            }
          }
        }
        ret.push(a)
      }
    } else {
      ret.push(v1)
      ret.push(v4)
    }
    // ret.push('')
    for (let m = 0; m < v4.length; m++) {
      if (v2.length !== 0) {
        var f = v2.some(item => {
          return item === '*'
        })
        if (f) {
          ret2.push(v4[m])
        } else {
          for (let n = 0; n < v2.length; n++) {
            if (v4[m].deviceTypeKey === v2[n]) {
              ret2.push(v4[m])
            }
          }
        }
      ret.push(ret2)
      } else {
        ret.push(v4)
      }
    }
    // ret.push(ret2)
    return ret
  },
  /**
   * @Description  : deviceModelChange
   * @author       : ls
   * @date         : 2021/3/8 15:02
   * @param        :
   * @return       :
   */
  deviceModelChangeCURD: function (v1, v2, v3) {
    var a = []
    for (let k in v3) {
      if (v2.length === 0) {
        if (v1.length === 0) {
          a.push(v3[k])
        } else {
          var f = v1.some(item => {
            return item === '*'
          })
          if (f) {
            a = v3
          } else {
            for (let t in v1) {
              if (v3[k].deviceTypeKey === v1[t]) {
                a.push(v3[k])
              }
            }
          }
        }
      }
      for (let key in v2) {
        if (v2[key] === v3[k]['deviceModel']) {
          if (v1.length === 0) {
            a.push(v3[k])
          } else {
            var flag = v1.some(item => {
              return item === '*'
            })
            if (flag) {
              if (v2[key] === v3[k]['deviceModel']) {
                a.push(v3[k])
              }
            } else {
              for (let key1 in v1) {
                if (v1[key1] === v3[k]['deviceTypeKey']) {
                  a.push(v3[k])
                }
              }
            }
          }
        }
      }
    }
    return a
  },
  /**
   * @Description  : deviceModelChange
   * @author       : ls
   * @date         : 2021/3/8 16:04
   * @param        :
   * @return       :
   */

  deviceModelChange: function (v1, v2, v3) {
    var a = []
    for (let i = 0; i < v3.length; i++) {
      if (v2 === '' || v2 === null) {
        if (v1 === '') {
          a.push(v3[i])
        } else {
          if (v1 === v3[i].deviceTypeKey) {
            a.push(v3[i])
          }
        }
      } else {
        if (v2 === v3[i].deviceModel) {
          a.push(v3[i])
        }
      }
    }
    return a
  },
  /**
   * @Description  : typeChange
   * @author       : ls
   * @date         : 2020/11/11 11:28
   * @param        :
   * @return       :
   */
  deviceTypeChange: function (v1, v2, v3) {
    var ret = []
    var ret1 = []
    if (v2 === '*') {
      ret.push(v1)
    } else {
      ret1 = v1.filter(item => {
        return item.deviceTypeKey === v2
      })
      ret.push(ret1)
    }
    v3 = ''
    ret.push(v3)
    return ret
  },
  /**
   * @Description  : changeDeviceType
   * @author       : ls
   * @date         : 2021/3/1 15:22
   * @param        :
   * @return       :
   */
  changeDeviceType: function (v1, v2) {
    var a = []
    if (v2.length !== 0) {
      var flag = v2.some(item => {
        return item === '*'
      })
      if (flag) {
        a = v1
      } else {
        for (let j = 0; j < v1.length; j++) {
          for (let t = 0; t < v2.length; t++) {
            if (v2[t] === v1[j].deviceTypeKey) {
              a.push(v1[j])
            }
          }
        }
      }
    } else {
      a = v1
    }
    return a
  },

  // 时间合法性转换
  timeLigalTransform: function (timeString) {
    timeString = timeString.replace(/-/g, '')
    timeString = timeString.replace(/T/g, '.')
    timeString = timeString.replace(/:/g, '')
    timeString = timeString.replace(/Z/g, '')
    return timeString
  },
  timeTran: function (timeString) {
    if (timeString === null || timeString === '') {
      return ''
    } else {
      var time = ''
      var year = timeString.substring(0, 4)
      var month = timeString.substring(4, 6)
      var day = timeString.substring(6, 8)
      var hour = timeString.substring(9, 11)
      var minute = timeString.substring(11, 13)
      var second = timeString.substring(13, 15)
      // var millisecond = timeString.substring(16,19)
      time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      return time
    }
  },
  // 重定向到登录页面
  toLoginPage: function () {
    window.sessionStorage.clear()
    window.localStorage.clear()
    store.commit('set_tabs', [])
    store.commit('set_keepAliveRouter', [])
    router.replace({
      path: '/'
    })
  },

  matchStatus: function (devices, topologys) {
    for (let deviceKey in devices) {
      Vue.set(topologys[devices[deviceKey].subnetKey].deviceList[deviceKey], 'status', devices[deviceKey].status)
    }
  },
  obtainLanguage: function () {
    const lang = localStorage.getItem('user-language') || 'zh-cn'
    return lang
  },
  // 同域名或同一父级域名下，设置共享cookie
  setCookie (c_name, value, domain) {
    // 存活10s
    let exdate = new Date(new Date().getTime() + 1000 * 20)
    document.cookie = c_name + '=' + escape(value) +
      ';expires=' + exdate.toUTCString() +
      ';path=/' +
      ';domain=' + domain
  },
  // 获取cookie
  getDesCookie (matchcookie) {
    let strcookie = document.cookie.trim()
    let getMatchCookie = ''
    let arrCookie = strcookie.split(';')
    for (let i = 0; i < arrCookie.length; i++) {
      let arr = arrCookie[i].trim().split('=')
      if (matchcookie === arr[0]) {
        getMatchCookie = arr[1]
        break
      }
    }
    return getMatchCookie
  },
  getRequest () {
    let url = location.search // 获取url中"?"符后的字串
    // let url = location.hash // 获取url中"?"符后的字串
    let theRequest = new Object()
    if (url.indexOf('?') !== -1) {
      let str = url.substr(1)
      let strs = str.split('&')
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
      }
      // var ind = url.lastIndexOf('?')
      // var str = url.substring(ind + 1)
      // let strs = str.split('&')
      // for (let i = 0; i < strs.length; i++) {
      //   theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
      // }
    }
    return theRequest
  }
}

function HelperUtil () {
  return Object.freeze(Object.assign(staticMethods))
}
// inject static methods
Object.assign(HelperUtil, staticMethods)
export default HelperUtil
