<template>
  <transition name="msgbox-fade">
    <div class="pub-wrapper" v-if="visible">
      <div class="pub-mask"></div>
      <div class="pub-modal invite-modal">
        <div class="modal-hd">
          <!-- <div class="title">
            <i class="el-icon-close" @click="visible = false"></i>
          </div>-->
          <i class="el-icon-close" @click="visible = false"></i>
        </div>
        <div class="modal-bd clearfix">
          <div class="left">
            <div class="search-input">
              <input type="text" @input="searchUser($event, checkList)" placeholder="搜索联系人">
              <i class="el-icon-search"></i>
            </div>
            <div class="user-list select-list pub-scroll-box">
              <template v-if="!isSearchGroup">
                <template v-if="checkList.length>0">
                  <div
                    class="user-item"
                    v-for="(item, key) in checkList"
                    :key="key"
                    :class="{'checked': item.isChecked}"
                    @click="changeState(item.user_id)"
                  >
                    <img v-if="item.cover_photo" class="user-avatar" :src="item.cover_photo" alt>
                    <div
                      v-else
                      class="user-avatar"
                      :class="`avatar_bg${item.user_id % 9}`"
                      :data-name="item.nick_name.slice(0,2).toUpperCase()"
                    ></div>
                    <span class="name">{{item.nick_name}}</span>
                    <i v-if="item.isChoosed" class="el-icon-circle-check is-choosed"></i>
                    <div v-else-if="item.is_admin!=2">
                      <i v-if="item.isChecked" class="el-icon-circle-check"></i>
                      <i v-else class="el-icon-circle-uncheck"></i>
                    </div>
                  </div>
                </template>
                <div class="no-data" v-else>暂无联系人</div>
              </template>
              <template v-else>
                <template v-if="searchGroupList.length>0">
                  <div
                    class="user-item"
                    v-for="(item, key) in searchGroupList"
                    :key="key"
                    :class="{'checked': item.isChecked}"
                    @click="changeState(item.user_id)"
                  >
                    <img v-if="item.cover_photo" class="user-avatar" :src="item.cover_photo" alt>
                    <div
                      v-else
                      class="user-avatar"
                      :class="`avatar_bg${item.user_id % 9}`"
                      :data-name="item.nick_name.slice(0,2).toUpperCase()"
                    ></div>
                    <span class="name">{{item.nick_name}}</span>
                    <i v-if="item.isChoosed" class="el-icon-circle-check"></i>
                    <div v-if="item.is_admin!=2">
                      <i v-if="item.isChecked" class="el-icon-circle-check"></i>
                      <i v-else class="el-icon-circle-uncheck"></i>
                    </div>
                  </div>
                </template>
                <div class="no-data" v-else>暂无联系人</div>
              </template>
            </div>
          </div>
          <div class="right">
            <p class="tips" v-if="this.popInviteType==5">转让群主</p>
            <p class="tips" v-else-if="this.checkedNum">已选择了{{checkedNum}}位群成员</p>
            <p class="tips" v-else-if="this.popInviteType==3">请勾选需要删除的群成员</p>
            <p class="tips" v-else>请勾选需要添加的{{this.popInviteType==4?"管理员":"联系人"}}</p>

            <div class="group-name" v-if="this.popInviteType==1">
              <input v-focus v-model="groupName" type="text" placeholder="请输入群名称">
            </div>
            <div class="user-list pub-scroll-box">
              <template v-for="(item, key) in resultList">
                <div class="user-item" :key="key" v-if="item.isChecked">
                  <img v-if="item.cover_photo" class="user-avatar" :src="item.cover_photo" alt>
                  <div
                    v-else
                    class="user-avatar"
                    :class="`avatar_bg${item.user_id % 9}`"
                    :data-name="item.nick_name.slice(0,2).toUpperCase()"
                  ></div>
                  <span class="name">{{item.nick_name}}</span>
                  <i @click="changeState(item.user_id, false)" class="el-icon-circle-close"></i>
                </div>
              </template>
            </div>
            <div class="send-btn">
              <el-button @click="optSubmit" type="primary" :disabled="checkedNum<=0">确认</el-button>
              <el-button @click="visible = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import { Button, Message, MessageBox } from 'element-ui'
import Vue from 'vue'
import { mapActions, mapState } from 'vuex'
import API from '@/api'
import _ from 'lodash'
import { searchGroupUserMixin } from '@/mixins'

Vue.component(Button.name, Button)

export default {
  name: 'invitePopup',
  mixins: [searchGroupUserMixin],
  data () {
    return {
      curItemIndex: 0,
      checkList: [],
      groupName: ''
    }
  },
  computed: {
    checkedNum () {
      return this.resultList.length
    },
    ...mapState({
      userId: state => state.userId,
      popInviteType: state => state.chat.popInviteType,
      friendList: state => state.chat.friendList,
      groupId: state => state.group.groupId,
      members: state => state.group.members,
      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 () {
      let arr1 = this.checkList.filter(v => {
        return v.isChecked
      })

      let arr2 = this.searchGroupList.filter(v => {
        return v.isChecked
      })
      let arr = [...arr1, ...arr2]
      let res = []
      for (let i = 0; i < arr.length; i++) {
        let flag = true
        for (let j = 0; j < res.length; j++) {
          if (arr[i].user_id === res[j].user_id) flag = false
        }
        if (flag) {
          res.push(arr[i])
        }
      }
      return res
    },
    ...mapActions(['getGroupInfo'])
  },
  methods: {
    getItemByUid (uid) {
      if (this.isSearchGroup) {
        return this.searchGroupList.filter((item, index) => {
          if (item.user_id == uid) this.curItemIndex = index
          return item.user_id == uid
        })[0]
      } else {
        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.popInviteType == 4 &&
        flag &&
        this.adminList.length + this.checkedNum > 5
      ) {
        this.$showTips('管理员最多只能设置5个人哦')
        return
      }
      // 转让群主
      if (this.popInviteType == 5) {
        this.checkList.forEach(item => {
          item.isChecked = false
        })
      }

      item['isChecked'] = flag

      if (this.isSearchGroup) {
        this.$set(this.searchGroupList, this.curItemIndex, item)
      } else this.$set(this.checkList, this.curItemIndex, item)
    },
    async initList () {
      switch (this.popInviteType) {
        // 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.members
          break
      }

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

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

        return item.user_id != this.userId
      })
    },
    optSubmit () {
      switch (this.popInviteType) {
        // 建群
        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
      }
    },
    // 建群
    createGroup () {
      if (this.groupName) {
        API.group
          .createGroup({
            group_title: this.groupName,
            user_id_list: this.inviteList
          })
          .then(({ data }) => {
            this.$showTips('创建成功')
            this.$store.commit('addSessionItem', data.data)
            this.visible = false
          })
      } else {
        Message({
          message: '请输入群名',
          type: 'warning'
        })
      }
    },
    // 邀请成员加入
    invitesMember () {
      API.group
        .invites({
          user_ids: this.inviteList,
          group_id: this.groupId
        })
        .then(({ data }) => {
          this.visible = false
          this.$store.dispatch('getGroupInfo')
        })
    },
    // 删除成员
    removesMember () {
      API.group
        .removes({
          user_ids: this.inviteList,
          group_id: this.groupId
        })
        .then(({ data }) => {
          this.visible = false
          this.$store.dispatch('getGroupInfo')
        })
    },
    // 添加群管理
    addAdmin () {
      API.group
        .addAdmin({
          user_ids: this.inviteList,
          group_id: this.groupId
        })
        .then(({ data }) => {
          this.visible = false
          this.$store.dispatch('getGroupInfo')
        })
    },
    changeCreator () {
      if (this.checkedNum <= 0) return

      let curMember = this.isSearchGroup
        ? this.searchGroupList[this.curItemIndex]
        : this.checkList[this.curItemIndex]
      let username = curMember.nick_name || curMember.user_name
      MessageBox.confirm(`确定要把群主转让给${username}`)
        .then(() => {
          API.group
            .changeCreator({
              new_creator: this.inviteList,
              group_id: this.groupId
            })
            .then(({ data }) => {
              this.visible = false
              Message({
                message: `已转让群主给${username}`,
                type: 'warning'
              })
            })
        })
        .catch(e => {
          console.log(e)
        })
    }
  },
  created () {
    this.initList()
  },
  directives: {
    focus: {
      // 指令的定义
      inserted: function (el) {
        setTimeout(() => {
          el.focus()
        }, 200)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
