import { MessageBox } from 'element-ui'
import TWEEN from '@tweenjs/tween.js'

const timestampInterval = 1e3 * 60 * 3 // 3分钟的间隔时间
const cryptoKey = 'dqWt6twz6JyEy3EZ'

// 错误弹窗
export function showError (msg, title = 'Error') {
  MessageBox.confirm(msg, title, {
    center: true,
    showCancelButton: false,
    showConfirmButton: false,
    callback () {}
  })
}

// 确认操作弹窗
export function confirmPopup (msg, title = '提示') {
  return new Promise((resolve, reject) => {
    MessageBox.confirm(msg, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        resolve()
      })
      .catch(() => {})
  })
}

/**
 * 判断系统||浏览器中英文
 * 对于不支持的浏览器 一律默认为 中文
 */
export function getLanguage () {
  var language = (navigator.language || navigator.browserLanguage).toLowerCase()
  var locale = 'zh'
  if (language.indexOf('en') > -1) {
    locale = 'en'
  } else {
    locale = 'zh'
  }
  return locale
}

/**
 * 获取Url上指定参数
 * @param {String} name 参数名
 */
export function getUrlParam (name) {
  var reg = new RegExp('[?&]' + name + '=([^&#?]*)(&|#|$)')
  var r = window.location.href.match(reg)
  return r ? r[1] : null
}

export var Cookie = {
  setCookie (name, value) {
    var Days = 7
    var exp = new Date()
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
    exp.setTime(exp.getTime() + 60 * 1000)
    if (
      window.location.port === '8080' ||
      /^test-|\.webdev2\./.test(window.location.host)
    ) {
      document.cookie =
        name + '=' + escape(value) + ';expires=' + exp.toGMTString()
    } else {
      document.cookie =
        name +
        '=' +
        escape(value) +
        ';domain=.mee.chat;path=/;expires=' +
        exp.toGMTString()
    }
  },
  getCookie (name) {
    var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    var arr = document.cookie.match(reg)
    if (arr) {
      return unescape(arr[2])
    } else {
      return null
    }
  },
  delCookie (name) {
    var str1 = name + '=;domain=.mee.chat;path=/'
    str1 += ';expires=' + new Date(0).toGMTString()
    document.cookie = str1

    var str2 = name + '=;path=/'
    str2 += ';expires=' + new Date(0).toGMTString()
    document.cookie = str2
  }
}
/**
 * 获取聊天区域高度
 * @param {String} msg
 */
export function getResizeHeight () {
  let clientHeight = document.documentElement.clientHeight
  let clientWidth = document.documentElement.clientWidth
  let topHeight = 61
  let botHeight = 181
  var chatBoxHeight
  if (clientHeight < 600) {
    chatBoxHeight = 600 - topHeight - botHeight
  }
  if (clientHeight < 800 || clientWidth < 1000) {
    chatBoxHeight = clientHeight - topHeight - botHeight
  } else {
    chatBoxHeight = clientHeight * 0.8 - topHeight - botHeight
  }
  return chatBoxHeight
}

function rc4 (str, key) {
  var s = []
  var j = 0
  var x
  var res = ''
  for (var i = 0; i < 256; i++) {
    s[i] = i
  }
  for (i = 0; i < 256; i++) {
    j = (j + s[i] + key.charCodeAt(i % key.length)) % 256
    x = s[i]
    s[i] = s[j]
    s[j] = x
  }
  i = 0
  j = 0
  for (var y = 0; y < str.length; y++) {
    i = (i + 1) % 256
    j = (j + s[i]) % 256
    x = s[i]
    s[i] = s[j]
    s[j] = x
    res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256])
  }
  return res
}

/**
 * 加密信息
 * @param {String} msg
 */
export function cryptoMsg (msg) {
  let result
  try {
    result = btoa(rc4(encodeURIComponent(msg), cryptoKey))
  } catch {
    return msg
  }
  return result
}

/**
 * 解密信息
 * @param {String} msg
 */
export function decryptoMsg (msg) {
  let result
  try {
    result = decodeURIComponent(rc4(atob(msg), cryptoKey))
  } catch {
    return msg
  }
  return result
}

/**
 * 向数组添加数据
 * @param {Array} data
 */
export function addSomeInArray (data) {
  let lastTime = null
  let linkRule = new RegExp(
    '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
  )
  let queLink = /(['"])(?:(?!\1).)*?\1/

  data.forEach(item => {
    // 添加timeMsg tag
    if (lastTime === null) {
      item.timeMsg = false
    } else {
      item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
    }
    lastTime = parseInt(item.timestamp)

    // 添加链接标识 msg_type = 10
    if (item.content && typeof item.content == 'string' && !item.content.match(queLink) &&
      item.content.match(linkRule) && item.msg_type == 0) {
      item.msg_type = 10
      item.content = item.content.replace(linkRule, a => {
        return `<a href="${a}" class="link text" target="_blank">${a}</a>`
      })
    }
  })
}

/**
 * 单个添加timeMsg tag
 * @param {Array} data
 */
export function addTimeMsgInItem (item, arr) {
  if (arr.length === 0) {
    item.timeMsg = true
  } else {
    let lastTime = parseInt(arr[arr.length - 1].timestamp)
    item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
  }
}

/**
 * 判断是否是移动端
 */
export function isMobile () {
  return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)
}

/*
 * 单个添加链接 msg_type = 10
 * @param {Array} data
 */
export function addLinkItem (item) {
  var linkRule = new RegExp(
    '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
  )
  var queLink = /(['"])(?:(?!\1).)*?\1/
  if (item.content.match(linkRule) && item.msg_type == 0 && !item.content.match(queLink)) {
    item.msg_type = 10
    item.content = item.content.replace(linkRule, a => {
      return `<a href="${a}" class="link text" target="_blank">${a}</a>`
    })
  }
}

/**
 * 移除arr2中满足callback的arr1数组元素
 * @param {Array} arr1 [{hash:1}]
 * @param {Array} arr2 [{hash:1},{hash:2}]
 * @result             arr1 => []
 */
export function removeItemIfEixt (arr1, arr2, callback) {
  arr1.forEach((item, index) => {
    if (arr2.some(item2 => callback(item2) == callback(item))) {
      arr1.splice(index, 1)
    }
  })
}

/**
 * 格式化置顶消息
 */
export function formatPinMsg (pinMsg, userId) {
  pinMsg.name = pinMsg.nick_name
  pinMsg.content = decryptoMsg(pinMsg.msg)
  pinMsg.type = pinMsg.from == userId ? 'me' : 'you'
  pinMsg.avatar = pinMsg.cover_photo || ''
  pinMsg.userId = userId
}

/**
 * @param {store} state
 * @param {Number} createTime
 */
export function dealErrorMsg (state, createTime) {
  state.chatList.forEach(item => {
    if (item.createTime == createTime) {
      item.fail = true
      item.loading = false
    }
  })
}

/**
 * 如果含有at他人的信息，格式化
 * @param {String} msg @heitan@aben 123
 * @param {Array} members
 * @result => {@start[10,9]end}@heitan@aben 123
 */
export function encryptAtMsg (msg, members) {
  let ats = []

  members.forEach(user => {
    let reg = new RegExp(`@${user.nick_name}`)
    if (reg.test(msg)) {
      ats.push(user.user_id)
    }
  })

  if (ats.length) {
    msg = `{@start[${ats.toString()}]end}${msg}`
  }

  return msg
}

/**
 *
 * @param {String} msg
 * @return {Array|Null}
 */
export function decryptAtMsg (msg) {
  let reg = /^{@start\[(.*)\]end}/
  let ret = reg.exec(msg)
  if (ret) {
    return ret[0].split(',')
  }
}
/**
 *判断是否是at我的信息
 */
export function checkAtMe (msg, username) {
  if (!username) return false
  let reg = new RegExp(`@${username}`)
  return reg.test(msg)
}

export function scrollIntoView (node, offsetTop) {
  let distance = Math.abs(offsetTop - node.scrollTop)
  let time = distance > 500 ? 1000 : distance * 2
  let tw = new TWEEN.Tween(node)
    .to({ scrollTop: offsetTop }, time)
    .easing(TWEEN.Easing.Quadratic.Out)
  return tw.start()
}

export function scrollMsgIntoView (node, offsetTop, targetNode) {
  scrollIntoView(node, offsetTop)
    .onComplete(() => {
      targetNode.classList.toggle('active')
    })

  setTimeout(() => {
    targetNode.classList.toggle('active')
  }, 3000)
}

export var noticeManager = {
  askPermission () {
    return new Promise((resolve, reject) => {
      if (!('Notification' in window)) {
        reject(new Error('This browser does not support desktop notification'))
      } else if (Notification.permission === 'granted') {
        resolve()
      } else if (Notification.permission === 'default ') {
        Notification.requestPermission(function (permission) {
          // 如果用户同意，就可以向他们发送通知
          if (permission === 'granted') {
            resolve()
          } else {
            reject(new Error())
          }
        })
      }
    })
  },
  showNotification (data) {
    this.askPermission().then(() => {
      let notification = new Notification(data.name, {
        body: '你收到了一条消息',
        icon: `${process.env.BASE_URL}icon_192.png`
      })

      // 打开页面
      let path
      if (data.group_id) {
        path = `/group/${data.group_id}`
      } else {
        let sessionId = +data.to > +data.from ? `${data.from}-${data.to}` : `${data.to}-${data.from}`
        path = `/pm/${sessionId}`
      }
      notification.onclick = () => {
        window.$router.push({ path })
        notification.close()
        window.focus()
      }

      setTimeout(() => {
        notification.close()
      }, 3500)
    })
  },
  changeTitle () {
    if (document.hidden) {
      document.title = 'MeeChat (你有新消息)'
    }
  }
}
