<template>
  <div class="r-view pub-scroll-box">
    <div class="setting-top">
      <div class="search-input">
        <input type="text" v-model="searchTxt" placeholder="搜索群成员">
        <i class="el-icon-search"></i>
      </div>
      <!-- 没搜索 -->
      <ul v-if="!isSearch" class="user-list pub-scroll-box" ref="scrollWrap" :class="{'height-limit': limitHeight}">
        <li class="list-item" @click="$showInvite(2)" v-if="isAdmin || isCreator">
          <div class="avatar btn"><i class="el-icon-plus"></i></div>
          <span class="name">添加</span>
        </li>
        <li class="list-item" @click="$showInvite(3)" v-if="isAdmin || isCreator">
          <div class="avatar btn"><i class="el-icon-minus"></i></div>
          <span class="name">删除</span>
        </li>
        <template v-for="(item, index) in membersArray">
          <li class="list-item" :key="index" @click="$showOtherInfo(item.user_id)">
            <div class="avatar-box">
              <img class="avatar" v-if="item.cover_photo" :src="item.cover_photo" alt="">
              <div v-else class="user-avatar avatar"
              :class="'avatar_bg' + item.user_id % 9"
              :title="item.nick_name"
              :data-name="item && item.nick_name && item.nick_name.slice(0,2).toUpperCase()">
              </div>
              <i v-if="group.creator == item.user_id" class="creator-icon"></i>
              <i v-else-if="adminList.includes(Number(item.user_id))" class="admin-icon el-icon-star-on"></i>
            </div>
            <span class="name">{{item.nick_name}}</span>
          </li>
        </template>
      </ul>
      <ul v-else class="user-list pub-scroll-box">
        <template v-for="(item, index) in searchList">
          <li class="list-item" :key="index" @click="$showOtherInfo(item.user_id)">
            <img class="avatar" v-if="item.cover_photo" :src="item.cover_photo" alt="">
            <div v-else class="user-avatar avatar"
            :class="'avatar_bg' + item.user_id % 9"
            :title="item.nick_name"
            :data-name="item && item.nick_name && item.nick_name.slice(0,2).toUpperCase()"></div>
            <span class="name">{{item.nick_name}}</span>
          </li>
        </template>
      </ul>
      <div class="show-all-btn" v-if="group.userCounts > 6" @click="handleShowAll">
        {{limitHeight ? '展开全部' : '收起'}} <i :class="`el-icon-arrow-${limitHeight ? 'down' : 'up'}`"></i>
      </div>
    </div>
    <div class="setting-item" v-if="isAdmin || isCreator">
      <div class="title">群名</div>
      <input class="edit-full-input" type="text" v-model="newGroupName" v-focus v-if="isEdit" @blur="handleTitleBlur">
      <p class="text" v-else @click="handleTitleFocus">{{group.groupName}}<i class="el-icon-edit"></i></p>
    </div>
    <div class="setting-item" v-if="isAdmin || isCreator">
      <div class="title">设置群头像</div>
      <p class="text cursor" @click="$editGroupAvatar(group.coverPhoto)">
        <img v-if="group.coverPhoto" class="team-avatar" :src="group.coverPhoto" alt="">
        <span class="no-avatar" v-else>
          <i class="el-icon-plus"></i>
        </span>
        <i class="el-icon-arrow-right team-arrow-icon"></i>
      </p>
    </div>
    <div class="setting-item">
      <div class="title">群公告</div>
      <p class="text cursor" @click="handleOpenNotice" v-if="isAdmin || isCreator">{{group.groupNotice}}<i class="el-icon-edit"></i></p>
      <template v-else>
        <p class="text notice" v-if="group.groupNotice">
          {{group.groupNotice}}
        </p>
        <p class="text notice" v-else>
          暂无公告
        </p>
      </template>
    </div>
    <div class="setting-item">
      <div class="title">群邀请链接</div>
      <p class="text">
        <template v-if="!isEditLink">
          <a class="invite-link" href="javascript:" @click="copyLink(group.inviteUrl)">{{sharePath + shareName}}</a>
          <span class="invite-editBtn" v-if="isAdmin || isCreator" @click="handleLinkFocus">
            <i class="el-icon-edit"></i>
          </span>
          <!-- <span class="link-change" v-if="isAdmin || isCreator" @click="handleLinkFocus" >更改</span> -->
        </template>
        <template v-else>
          <em class="edit-name-path">{{sharePath}}</em>
          <input class="edit-name-input" v-model="editShareName" v-focus type="text" autofocus @blur="handleLinkBlur">
        </template>
      </p>
    </div>
    <div class="setting-item">
      <div class="title">消息免打扰</div>
      <p class="text">
        <el-switch
        v-model="sessionInfo.is_mute"
        @change="changeMute"
        :active-value="1"
        :inactive-value="0"
        active-color="#2298f0"
        inactive-color="#cbcbcb">
      </el-switch>
      </p>
    </div>
    <div class="setting-item">
      <div class="title">置顶聊天</div>
      <p class="text">
        <el-switch
        v-model="sessionInfo.is_pin"
        @change="changePin"
        :active-value="1"
        :inactive-value="0"
        active-color="#2298f0"
        inactive-color="#cbcbcb">
      </el-switch>
      </p>
    </div>
    <div class="setting-item ext-group-admin" v-if="isCreator" @click="handleGroudMgr">
      <div class="title">群管理<i class="el-icon-arrow-right team-arrow-icon"></i></div>
    </div>
    <div class="setting-bottom">
      <button class="delete-btn" @click="leaveGroup">退出群组</button>
    </div>
    <!-- 群公告 -->
    <transition name="msgbox-fade">
      <div class="pub-wrapper" v-if="editNotice">
        <div class="pub-mask"></div>
        <div class="pub-modal notice-modal">
          <div class="modal-hd">
            <div class="title">群公告</div>
            <i class="el-icon-close" @click="editNotice = false"></i>
          </div>
          <div class="modal-bd">
            <textarea v-focus placeholder="请输入你的群公告" v-model="newNotice"></textarea>
          </div>
          <div class="modal-fd">
            <el-button type="primary" @click="handleNotice">确认</el-button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import Vue from 'vue'
import { Switch, Button } from 'element-ui'
import API from '@/api'
import { mapState, mapActions } from 'vuex'
import { confirmPopup } from '@/util/util'

Vue.component(Button.name, Button)
Vue.component(Switch.name, Switch)

export default {
  name: 'chatSet',
  watch: {
    searchTxt (newVal, val) {
      if (newVal == '') {
        this.isSearch = false
      } else {
        this.isSearch = true
        this.searchUser()
      }
    }
  },
  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
    }
  },
  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: ''// 搜索内容
    }
  },
  methods: {
    ...mapActions([
      'updateSessionItem'
    ]),
    // 群标题
    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: 取消置顶}
     */
    changePin (val) {
      if (val == 1) {
        API.session.setPin({
          session_id: this.curGroupId
        }).then(() => {
          this.$store.commit('updatePin', val)

          // 更新侧边栏的顺序
          this.$store.commit('updateSessionListByPin', this.curGroupId)
        })
      } else {
        API.session.cancelPin({
          session_id: this.curGroupId
        }).then(() => {
          this.$store.commit('updatePin', val)

          // 更新侧边栏的顺序
          this.$store.commit('cancelSessionListByPin', this.curGroupId)
        })
      }
    },
    /**
     * @des 消息免打扰
     * @param {String} val 消息免打扰Flag开关{1: 免打扰, 0: 取消免打扰}
     */
    changeMute (val) {
      if (val == 1) {
        API.session.setMute({
          session_id: this.curGroupId
        }).then(() => {
          this.$store.commit('updateMute', val)
        })
      } else {
        API.session.cancelMute({
          session_id: this.curGroupId
        }).then(() => {
          this.$store.commit('updateMute', val)
        })
      }
    },
    // 退出群组
    leaveGroup () {
      confirmPopup('确认退出该群聊？').then(() => {
        API.group.leaveGroup({
          group_id: this.curGroupId
        }).then(() => {
          this.$store.commit('removeSessionListById', this.curGroupId)
          this.$store.dispatch('getGroupInfo')
          this.$showTips('已退出该群聊')
        })
      })
    },
    searchUser () {
      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
        })
      }
    }
  }
}
</script>

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