// 搜索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 name = item.name || item.nick_name
        return name.indexOf(val) > -1
      })
      this.isSearch = true
    }
  }
}

// @人
export const chatAtMixin = {
  data () {
    return {
      atInd: 0 // @人索引
    }
  },
  methods: {
    atPerson (name) {
      let el = this.$refs.chatInput
      let selectionStart = el.selectionStart
      this.inputMsg = this.inputMsg.slice(0, selectionStart) + `${name} ` + this.inputMsg.slice(selectionStart)
      this.atInd = 0
      el.focus()
      this.$nextTick(() => {
        el.setSelectionRange(selectionStart + name.length + 1, selectionStart + name.length + 1)
      })
    },
    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// 光标在@后面
    }
  },
  computed: {
    filterMembers () {
      let val = this.inputMsg.replace('@', '')
      let members = this.group.members
      let resArr = []
      for (let k in members) {
        if (k == this.userId) continue
        if (val.indexOf(members[k].user_name) === -1) {
          resArr.push(members[k])
        }
      }
      return resArr
    },
    atShow () {
      return this.selectionAfterAt && this.filterMembers.length
    }
  },
  watch: {
    inputMsg (val, newval) {
      this.handleSelectionChange()
    }
  },
  methods: {
    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 () {
      document.addEventListener('selectionchange', this.handleSelectionChange)
    },
    handleBlur () {
      document.removeEventListener('selectionchange', this.handleSelectionChange)
      this.updateChatInputFocus(false)
    },
    /**
     * 监听光标位置
     */
    handleSelectionChange () {
      let selectionStart = this.$refs.chatInput.selectionStart
      let prevStr = this.inputMsg.slice(0, selectionStart)
      this.selectionAfterAt = /@$/.test(prevStr)
    }
  }
}
