import api from '@/api'

// 搜索mixin
export const searchUserMixin = {
  data () {
    return {
      isSearch: false, // 搜索展示
      searchList: null // 搜索结果
    }
  },
  methods: {
    searchUser (e, originList) {
      let val = e.target.value
      if (!val) {
        this.isSearch = false
        return
      }

      this.searchList = originList.filter(item => {
        let inName, inNick
        if (item.name) {
          inName = item.name ? item.name.indexOf(val) > -1 : false
        } else {
          inName = item.user_name ? item.user_name.indexOf(val) > -1 : false
        }

        inNick = item.nick_name ? item.nick_name.indexOf(val) > -1 : false
        return inName || inNick
      })

      this.isSearch = true
    }
  }
}

// 群搜索mixin
export const searchGroupUserMixin = {
  data () {
    return {
      isSearchGroup: false, // 搜索展示
      searchGroupList: [] // 搜索结果
    }
  },
  methods: {
    searchUser (e, originList) {
      let val = e.target.value
      let inviteType = this.popInviteType
      if (!val) {
        this.isSearchGroup = false
        return
      }

      if (originList.length >= this.membersNum || inviteType == 1 || inviteType == 2) {
        this.searchGroupList = originList.filter(item => {
          let inName, inNick

          inName = item.user_name ? item.user_name.indexOf(val) > -1 : false
          inNick = item.nick_name ? item.nick_name.indexOf(val) > -1 : false
          return inName || inNick
        })
      } else {
        api.group.searchMember({
          group_id: this.group.groupId,
          keyword: this.searchTxt
        }).then(({ data }) => {
          this.searchGroupList = data.data
        })
      }

      this.isSearchGroup = true
    }
  }
}

// @人
export const chatAtMixin = {
  data () {
    return {
      atInd: 0 // @人索引
    }
  },
  methods: {
    atPerson (name) {
      let el = this.$refs.chatInput
      let selectionStart = el.selectionStart
      let realStart = selectionStart - this.keyAfterAt.length
      this.inputMsg = this.inputMsg.slice(0, realStart) + `${name} ` + this.inputMsg.slice(selectionStart)
      this.atInd = 0
      el.focus()
      this.$nextTick(() => {
        el.setSelectionRange(realStart + name.length + 1, realStart + name.length + 1)
      })

      this.$store.commit('updateIsNewAt', {
        isNewAt: this.group.isNewAt,
        isNewAtFound: true
      })
      this.$store.commit('updateGroupSearchList', [])
    },
    handleUp () {
      if (this.atInd > 0) {
        this.atInd--
      }
    },
    handleDown () {
      let membersLen = this.filterMembers.length
      this.atInd < membersLen - 1 ? this.atInd++ : this.atInd = 0
    }
  }
}

// 聊天输入框
export const chatInputMixin = {
  data () {
    return {
      selectionAfterAt: false, // 光标在@后面
      keyAfterAt: '', // 光标后的搜索字
      lastKeyAfterAt: ''
    }
  },
  mounted () {
    document.addEventListener('click', this.handleGlobalClick)
  },
  computed: {
    filterMembers () {
      if (!this.group.groupId) return []

      let members = this.group.membersArray
      let resArr = []
      if (this.keyAfterAt !== '') {
        resArr = this.group.searchList
      } else {
        for (let k = 0; k < members.length; k++) {
          if (members[k].user_id == this.userId) continue
          resArr.push(members[k])
        }
      }

      return resArr.slice(0, 100)
    },
    atShow () {
      this.atInd = 0
      return this.selectionAfterAt && this.filterMembers.length
    }
  },
  watch: {
    keyAfterAt (val) {
      if (!this.group.groupId || val == '') return
      if (this.group.isNewAtFound) return

      if (this.group.membersArray.length < this.group.membersNum) {
        api.group.searchMember({
          group_id: this.group.groupId,
          keyword: val
        }).then(({ data }) => {
          this.$store.commit('updateGroupSearchList', data.data)
        })
      } else {
        let searchList = this.group.membersArray.filter(item => {
          let inName, inNick

          inName = item.user_name ? item.user_name.indexOf(val) > -1 : false
          inNick = item.nick_name ? item.nick_name.indexOf(val) > -1 : false

          return inName || inNick
        })

        this.$store.commit('updateGroupSearchList', searchList)
      }
    },
    inputMsg (val, newval) {
      this.fixIOS()

      this.handleSelectionChange()
    }
  },
  methods: {
    getStrBeforeSelection () {
      let el = this.$refs.chatInput
      if (!el) return ''
      let selectionStart = el.selectionStart
      let prevStr = this.inputMsg.slice(0, selectionStart)
      return prevStr
    },
    getStrAfterSelection () {
      let el = this.$refs.chatInput
      if (!el) return ''
      let selectionStart = el.selectionStart
      let prevStr = this.inputMsg.slice(selectionStart)
      return prevStr
    },
    handleLeft (event) {
      let el = this.$refs.chatInput
      let selectionStart = el.selectionStart
      if (selectionStart === 0) return
      let prevStr = this.getStrBeforeSelection()
      let members = this.group.members

      for (let k in members) {
        let name = members[k].user_name
        let reg = new RegExp(`@${name} $`)
        if (reg.test(prevStr)) {
          event.preventDefault()
          el.setSelectionRange(selectionStart - name.length - 2, selectionStart - name.length - 2)
          return
        }
      }
    },
    handleRight (event) {
      let el = this.$refs.chatInput
      let selectionStart = el.selectionStart
      let afterStr = this.getStrAfterSelection()
      let members = this.group.members

      for (let k in members) {
        let name = members[k].user_name
        let reg = new RegExp(`^@${name} `)
        if (reg.test(afterStr)) {
          event.preventDefault()
          el.setSelectionRange(selectionStart + name.length + 2, selectionStart + name.length + 2)
          return
        }
      }
    },
    handleDel (event) {
      let el = this.$refs.chatInput
      let selectionStart = el.selectionStart
      if (selectionStart === 0) return
      let prevStr = this.getStrBeforeSelection()
      let members = this.group.members

      for (let k in members) {
        let name = members[k].user_name
        let reg = new RegExp(`@${name} $`)
        if (reg.test(prevStr)) {
          event.preventDefault()
          this.inputMsg = this.inputMsg.slice(0, selectionStart - name.length - 2) + this.inputMsg.slice(selectionStart)
          this.$nextTick(() => {
            el.setSelectionRange(selectionStart - name.length - 2, selectionStart - name.length - 2)
          })
          return
        }
      }
    },
    handleKeyDown (event) {
      if (this.atShow) {
        event.preventDefault()
        let item = this.filterMembers[this.atInd]
        this.atPerson(item.user_name)
        return
      }

      if (event.altKey || event.ctrlKey) {
        // 单纯换行
        this.inputMsg = this.inputMsg + '\n'
      } else {
        event.returnValue = false
        this.handleSend(event)
      }

      return false
    },
    handleFocus () {
      this.fixIOS()
      document.addEventListener('selectionchange', this.handleSelectionChange)
    },
    handleBlur () {
      this.fixIOS(false)

      document.removeEventListener('selectionchange', this.handleSelectionChange)
      this.updateChatInputFocus(false)
    },
    handleEsc () {
      this.selectionAfterAt = false
    },
    /**
     * 监听全局点击事件
    */
    handleGlobalClick () {
      this.selectionAfterAt = false
    },
    /**
     * 监听光标位置
     */
    handleSelectionChange () {
      let el = this.$refs.chatInput
      if (!el) return
      let selectionStart = el.selectionStart
      let selectionEnd = this.$refs.chatInput.selectionEnd
      if (selectionStart !== selectionEnd) return

      let prevStr = this.getStrBeforeSelection()
      this.selectionAfterAt = /@/.test(prevStr)
      if (this.selectionAfterAt) {
        this.keyAfterAt = prevStr.slice(prevStr.lastIndexOf('@') + 1)
        let isNewAt = this.keyAfterAt.indexOf(this.lastKeyAfterAt) < 0

        this.$store.commit('updateIsNewAt', {
          isNewAt: isNewAt,
          isNewAtFound: isNewAt ? false : this.group.isNewAtFound
        })
        if (isNewAt) this.$store.commit('updateGroupSearchList', [])

        this.lastKeyAfterAt = this.keyAfterAt
      }
    },
    /**
     * @des 处理ios系统下窗体闪烁的bug
     * @param {boolean} flag {true: 激活修复状态, false: 恢复原始状态}
     */
    fixIOS (flag = true) {
      var u = navigator.userAgent
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      if (isIOS) {
        let el = this.$refs.scrollWrap
        if (!el) return
        if (flag) {
          el.style.overflowY = 'hidden'
        } else {
          el.style.overflowY = 'scroll'
        }
      }
    }
  }
}
