
import API from '@/api'
import { mapState, mapActions, mapMutations } from 'vuex'
import { confirmPopup, getMeechatType, getAvatarBgColor } from '@/util/util'
import { Message, MessageBox } from 'element-ui'
import { searchGroupUserMixin } from '@/mixins'
import _ from 'lodash'

export const groupSetMixins = {
  computed: {
    ...mapState({
      myId: state => state.userId,
      group: state => state.group,
      curGroupId: state => state.curSession,
      members: state => state.group.members,
      sessionInfo: state => state.group.sessionInfo,
      shareName: state => state.group.shareName,
      adminList: state => state.group.adminList,
      membersArray: state => state.group.membersArray
    }),
    isAdmin () {
      return this.members && this.members[this.myId] && this.members[this.myId].is_admin == 1
    },
    isCreator () {
      return this.group.creator == this.myId
    },
    isPrivate () {
      return this.$store.getters.isPrivate
    }
  },
  mounted () {
    let groupId = this.$route.params.id
    this.changeSessionId(groupId)

    if (!this.isPrivate && !this.group.groupId) {
      this.initGroup({
        userId: this.myId,
        groupId: groupId,
        useCache: false
      })
      this.getGroupInfo()
    }
    document.addEventListener('click', () => {
      if (!this.$refs.chatSet) return

      let classNames = this.$refs.chatSet.getAttribute('class')

      if (classNames.indexOf('move-left') > -1) {
        this.$emit('showCharSet', 0)
      }
    })
  },
  data () {
    return {
      msgPush: false, // 消失免打扰
      msgTop: false, // 置顶聊天
      limitHeight: true, // 展开全部
      isEdit: false, // 编辑群名
      newGroupName: '', // 群名
      newLink: '', // 新连接
      newNotice: '', // 新群名
      isEditLink: false, // 编辑链接
      editNotice: false,
      editShareName: '',
      sharePath: `${location.origin}/s/`,
      isSearch: false,
      searchList: [], // 搜索结果列表
      searchTxt: '', // 搜索内容
      meechatType: getMeechatType()// meechat版本
    }
  },
  methods: {
    ...mapMutations(['initGroup', 'changeSessionId', 'changeHotGroupStatus', 'removeSessionListById']),
    ...mapActions([
      'updateSessionItem',
      'getGroupInfo'
    ]),
    // 群标题
    handleTitleBlur () {
      this.isEdit = false
      if (this.newGroupName.length) {
        API.group.changeTitle({
          group_id: this.curGroupId,
          title: this.newGroupName
        }).then(({ data }) => {
          // 更新侧边栏
          this.updateSessionItem({
            sessionId: this.curGroupId,
            data: {
              name: this.newGroupName
            }
          })

          // 更新群组数据
          this.$store.commit('updateGroup', {
            key: 'groupName',
            data: this.newGroupName
          })
        })
      }
    },
    handleTitleFocus () {
      this.isEdit = true
      this.newGroupName = this.group.groupName
    },
    handleShowAll () {
      if (!this.limitHeight) {
        this.$refs.scrollWrap.scrollTop = 0
      }
      this.limitHeight = !this.limitHeight
    },
    // 群链接
    async handleLinkBlur () {
      this.isEditLink = false
      if (this.editShareName.match(/^\d{1,}$/)) {
        this.$showTips('分享链接不能是纯数字')
        return
      }

      if (!this.editShareName.match(/^(\w|.){1,}$/)) {
        this.$showTips('分享链接只能是英文字母，数字和 . 的组合')
        return
      }

      await confirmPopup(`分享链接只能被修改一次，确认修改为：${this.sharePath + this.editShareName}`, '提示')
        .catch(e => {})

      API.group.changeName({
        group_id: this.curGroupId,
        name: this.editShareName
      }).then(() => {
        this.$store.commit('updateGroup', {
          key: 'shareName',
          data: this.editShareName
        })
      })
    },
    handleLinkFocus () {
      this.isEditLink = true
      this.editShareName = this.shareName
      // this.newLink = this.group.inviteUrl
    },
    // 群公告
    handleNotice () {
      API.group.changeNotice({
        group_id: this.curGroupId,
        notice: this.newNotice
      }).then(() => {
        this.$showTips('修改成功')
        this.editNotice = false

        this.$store.commit('updateGroup', {
          key: 'groupNotice',
          data: this.newNotice
        })
      })
    },
    // 群管理
    handleGroudMgr () {
      this.$emit('handleShowGroudMgr', 1)
    },
    handleOpenNotice () {
      this.editNotice = true
      this.newNotice = this.group.groupNotice
    },
    copyLink (link) {
      let url = document.location.protocol + link
      this.$copyText(url).then((e) => {
        this.$showTips('复制成功')
      })
    },
    /**
     * @des 置顶聊天相关操作
     * @param {String} val 置顶操作Flag开关{1: 置顶, 0: 取消置顶}
     */
    async changePin (val) {
      let opt = val == 1 ? 'setPin' : 'cancelPin'
      let optRes = val == 1 ? 'updateSessionListByPin' : 'cancelSessionListByPin'

      let res = await API.session[opt]({
        session_id: this.curGroupId
      })

      let data = res.data.data
      this.$store.commit('updatePin', val)

      // 更新侧边栏的顺序
      this.$store.commit(optRes, {
        session_id: this.curGroupId,
        is_pin: data.is_pin,
        pin_time_int: data.pin_time_int
      })
    },
    /**
     * @des 消息免打扰
     * @param {String} val 消息免打扰Flag开关{1: 免打扰, 0: 取消免打扰}
     */
    async changeMute (val) {
      let opt = val == 1 ? 'setMute' : 'cancelMute'
      let optRes = val == 1 ? 'updateSessionListByMute' : 'cancelSessionListByMute'

      await API.session[opt]({
        session_id: this.curGroupId
      })

      this.$store.commit('updateMute', val)

      // 更新侧边栏的顺序
      this.$store.commit(optRes, this.curGroupId)
    },
    // 退出群组
    leaveGroup () {
      confirmPopup(this.$t('group.leaveComfirm')).then(() => {
        this.$emit('showLoadingRoom', true)
        API.group.leaveGroup({
          group_id: this.curGroupId
        }).then(() => {
          this.changeHotGroupStatus({
            groupId: this.curGroupId,
            isJoin: 0
          })

          this.removeSessionListById(this.curGroupId)
          this.$showTips(this.$t('group.leaveTip'))
          this.$emit('showLoadingRoom', false)
          this.$store.commit('updateJoin', false)

          if (this.meechatType == 'h5') this.$router.go(-2)
        }).catch(() => {
          this.$emit('showLoadingRoom', false)
        })
      })
    },
    searchUser () {
      if (!this.searchTxt.trim()) return
      if (this.membersArray.length < this.group.membersNum) {
        API.group.searchMember({
          group_id: this.group.groupId,
          keyword: this.searchTxt
        }).then(({ data }) => {
          this.searchList = data.data
        })
      } else {
        let val = this.searchTxt
        this.searchList = this.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
        })
      }
    }
  }
}

export const groupInviteMixins = {
  mixins: [searchGroupUserMixin],
  data () {
    return {
      curItemIndex: 0,
      checkList: [],
      groupName: '',
      isLoading: false,
      showNum: 0,
      meechatType: getMeechatType()// meechat版本
    }
  },
  computed: {
    checkedNum () {
      return (this.checkList.filter(v => {
        return v.isChecked
      })).length
    },
    ...mapState({
      userId: state => state.userId,
      friendList: state => state.chat.friendList,
      groupId: state => state.group.groupId,
      group: state => state.group,
      members: state => state.group.members,
      membersArray: state => state.group.membersArray,
      membersNum: state => state.group.membersNum,
      adminList: state => state.group.adminList
    }),
    inviteList () {
      return this.checkList.filter(v => {
        return v.isChecked
      }).map(v => v.user_id).join(',')
    },
    resultList () {
      return (this.checkList && this.checkList.filter(v => {
        return v.isChecked
      })) || []
    }
  },
  methods: {
    ...mapActions(['getGroupInfo']),
    ...mapMutations([
      'initGroup',
      'changeSessionId'
    ]),
    getItemByUid (uid) {
      return this.checkList.filter((item, index) => {
        if (item.user_id == uid) this.curItemIndex = index
        return item.user_id == uid
      })[0]
    },
    changeState (uid, flag = true) {
      let item = this.getItemByUid(uid)

      if (item.isChoosed) return

      // 群管理设限
      if (
        this.inviteType == 4 &&
        flag &&
        this.adminList.length + this.checkedNum > 5
      ) {
        this.$showTips(this.$t('group.groupMgrMostTips'))
        return
      }
      // 转让群主
      if (this.inviteType == 5) {
        this.checkList.forEach(item => {
          item.isChecked = false
        })
      }

      item['isChecked'] = flag

      this.$set(this.checkList, this.curItemIndex, item)
    },
    changeStateForH5 (uid) {
      let item = this.getItemByUid(uid)
      let flag = !item.isChecked

      // 群管理设限
      if (this.inviteType == 4 && flag && this.adminList.length + this.checkedNum > 5) {
        this.$showTips(this.$t('group.groupMgrMostTips'))
        return
      }
      // 转让群主
      if (this.inviteType == 5) {
        this.checkList.forEach(item => {
          item.isChecked = false
        })
      }

      item['isChecked'] = flag

      this.$set(this.checkList, this.curItemIndex, item)
    },
    async initList () {
      switch (this.inviteType) {
        // 1建群/2邀请好友进群
        case 1:
          await this.$store.dispatch('getFriendList')
          this.checkList = this.friendList
          break
        case 2:
          await this.$store.dispatch('getFriendList')
          this.checkList = _.filter(this.friendList, item => {
            return !this.members[item.user_id]
          })
          break
        // 3删除群成员/4添加群管理/5转让群主
        case 3:
        case 4:
        case 5:
          this.checkList = this.membersArray
          break
      }

      this.checkList = _.filter(this.checkList, item => {
        item.isChecked = false
        item.isChoosed = false
        item.isShow = true

        // 群管理特殊处理
        if (this.inviteType == 4 && item.is_admin == 1) {
          item.isChoosed = true
        }

        return item.user_id != this.userId
      })
      this.showNum = this.checkList.length
    },
    optSubmit () {
      switch (this.inviteType) {
        // 建群
        case 1:
          this.createGroup()
          break
        // 邀请好友进群
        case 2:
          this.invitesMember()
          break
        // 删除群成员
        case 3:
          this.removesMember()
          break
        // 添加群管理
        case 4:
          this.addAdmin()
          break
        // 群主转让
        case 5:
          this.changeCreator()
          break
        // 创建新群并且同步telegram
        case 6:
          this.createGroup()
          break
      }
    },
    // 建群
    createGroup () {
      if (this.groupName.length > 16) {
        this.$showTips(this.$t('group.groupNameLengthTips'))
        return
      }

      if (this.groupName) {
        this.isLoading = true

        API.group
          .createGroup({
            group_title: this.groupName,
            user_id_list: this.inviteList
          })
          .then(({ data }) => {
            let groupId = data.data.session_id
            this.$showTips(this.$t('group.createSuccess'))
            this.$store.commit('addSessionItem', data.data)

            if (this.ext && this.ext.tgGroupId) {
              // 同步tele
              this.doSyncTelegram(groupId)
            } else {
              this.$router.push(`/group/${groupId}`)
            }

            if (this.meechatType != 'h5') this.hidePopup()
          })
      } else {
        Message({
          message: this.$t('group.groupNameTips'),
          type: 'warning'
        })
      }
    },
    // 同步tele
    doSyncTelegram (groupId) {
      API.tg.doSync({
        group_id: groupId,
        tg_group_id: this.ext.tgGroupId
      }).then(() => {
        this.$router.replace(`/group/${groupId}`)
      }).catch(error => {
        console.log(error)
        if (this.meechatType == 'h5') this.$router.replace('/')
      })
    },
    // 邀请成员加入
    async invitesMember () {
      this.isLoading = true
      await API.group.invites({
        user_ids: this.inviteList,
        group_id: this.groupId
      })

      await this.getGroupInfo()

      if (this.meechatType == 'h5') this.$router.go(-1)
      else this.hidePopup()
    },
    // 删除成员
    async removesMember () {
      this.isLoading = true
      await API.group.removes({
        user_ids: this.inviteList,
        group_id: this.groupId
      })

      await this.getGroupInfo()

      if (this.meechatType == 'h5') this.$router.go(-1)
      else this.hidePopup()
    },
    // 添加群管理
    addAdmin () {
      this.isLoading = true
      API.group
        .addAdmin({
          user_ids: this.inviteList,
          group_id: this.groupId
        })
        .then(({ data }) => {
          this.getGroupInfo()

          if (this.meechatType == 'h5') this.$router.go(-1)
          else this.hidePopup()
        })
    },
    changeCreator () {
      if (this.checkedNum <= 0) return

      let curMember = this.checkList[this.curItemIndex]
      let username = curMember.nick_name || curMember.user_name
      MessageBox.confirm(`${this.$t('group.groupMgrComfime')} ${username}`)
        .then(() => {
          this.isLoading = true
          API.group
            .changeCreator({
              new_creator: this.inviteList,
              group_id: this.groupId
            })
            .then(({ data }) => {
              if (this.meechatType == 'h5') this.$router.go(-1)
              else this.hidePopup()

              this.$store.dispatch('getGroupInfo')
              Message({
                message: `${this.$t('group.groupMgrResult')} ${username}`,
                type: 'warning'
              })
            })
        })
        .catch(e => {
          console.log(e)
        })
    }
  },
  mounted () {
    this.initList()
  }
}

export const groupHotMixins = {
  props: {
    searchTxt: String
  },
  data () {
    return {
    }
  },
  components: {},
  computed: {
    ...mapState(['hotList']),
    ...mapActions(['getHotList']),
    showHotList () {
      let val = this.searchTxt && this.searchTxt.trim()
      if (!val) return this.hotList

      let arr = this.hotList.filter((item) => {
        let title = (item.group_title && item.group_title.toLocaleLowerCase()) || ''
        return title.match(val)
      })

      return arr
    }
  },
  methods: {
    ...mapMutations(['changeHotGroupStatus']),
    bgColorNum (str) {
      return getAvatarBgColor(str, this.userId)
    },
    /**
     *  @des 加入群聊
     * @param {type} 1已加入0未加入
     * */
    joinGroup (groupId, type) {
      if (type == 1) {
        this.$router.push(`/group/${groupId}`)
      } else {
        API.group.joinGroup({
          group_id: groupId
        }).then(() => {
          this.changeHotGroupStatus({
            groupId: groupId,
            isJoin: 1
          })
          this.$router.push(`/group/${groupId}`)
        })
      }
    }
  },
  mounted () {
    this.$store.commit('changeSessionId', '0')
    this.$store.dispatch('getHotList')
  }
}
