<!-- 创建群 -->
<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :show-close="false"
    class="create-dialog"
  >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body create-body">
                <form class="flex">
                    <div class="form-group small-width inline-block" style="padding-right:10px;">
                        <el-input prefix-icon="el-icon-search" size="small" class="form-control inline-block" v-model="filterText" style="margin-bottom:10px" placeholder="搜索医生"/>
                        <div style="line-height: 24px;height:24px;">
                            <el-checkbox style="margin-right: 5px;" class="ft-l smallCheckbox" :indeterminate="isIndeterminate" v-model="checkAll" @change="addAllPeopleChange">所有医生</el-checkbox>
                        </div>
                        <ul class="list-group" id="createPeopleList">
                            <div v-for="(item,key) in allUserList" :key="key">
                                <el-checkbox class="margin-tb-5" :indeterminate="item.isIndeterminate" v-model="item.checkAll" v-show="depBoxShow(item.users)" @change="depCheckAllChange(key,$event)">{{key}}</el-checkbox>
                                <el-checkbox-group v-model="item.checkList" @change="depCheckGroup(key,item.checkList)">
                                        <li class="list-group-item checkbox" v-for="(val,i) in item.users" :key="i" v-show="val.userName.indexOf(filterText)>-1">
                                            <el-checkbox :label="val" :disabled="val.id === myUserId">
                                                <img :src="val.avatarImageUrl ? val.avatarImageUrl : require('../../../static/avatar.jpg')"/>
                                                <span class="user-name">{{val.userName}}</span>
                                            </el-checkbox>
                                        </li>
                                </el-checkbox-group>
                            </div>
                        </ul>
                    </div>
                    <div class="form-group large-width inline-block float-r pd-10 bg-F7F8FA relative">
                        <div style="height: calc(100% - 46px);">
                            <div class="title">添加群成员：</div>
                            <div class="fs-12 color-86909c peopleNum">已选择{{checkList.length}}人</div>
                            <ul class="list-group" id="createAddPeopleList">
                                <div v-if="selfData">
                                    <li class="list-group-item flex" style="line-height: 45px;">
                                        <img :src="selfData.user.avatarImageUrl ? selfData.user.avatarImageUrl : require('../../../static/avatar.jpg')"/>
                                        <div class="text">
                                            <strong class="user-name">{{selfData.user.userName}}</strong>
                                        </div>
                                    </li>
                                </div>
                                <div v-for="(item,key) in allUserList" :key="key" v-if="item.checkList.length > 1 || (item.checkList.length === 1 && item.checkList[0].id !== myUserId) ">
                                    <div style="line-height: 24px;">
                                        <div class="fs-12 color-86909c">{{key}}</div>
                                    </div>
                                    <li class="list-group-item flex" style="line-height: 45px;" v-for="(val,index) in item.checkList" :key="index" v-if="val.id !== myUserId">
                                        <img :src="val.avatarImageUrl ? val.avatarImageUrl : '../../../static/avatar.jpg'"/>
                                        <div class="text">
                                            <strong class="user-name">{{val.userName}}</strong>
                                            <span class="iconfont icon-shanchu-fill cursor ft-r mr-5" @click="deleteChoose(key,val.id)"></span>
                                        </div>
                                    </li>
                                </div>
                            </ul>
                        </div>
                        <div class="create-roomName" v-if="peopleModalType === 'create'">
                            <label for="create-room-name">房间名：</label>
                            <el-input size="small" id="create-room-name" v-model="roomName" class="form-control inline-block" placeholder="请输入房间名称"/>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <span slot="footer" class="dialog-footer fl-r">
        <el-button size="small" type="primary" @click="saveCreate">确 定</el-button>
        <el-button size="small" @click="handleClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {createGroup, addPeopleToGroup} from '../../api/api.js'
export default {
  name: '',
  mixins: [],
  components: {},
  props: {
    createVisible: {
      Boolean,
      default: false
    },
    allUsers: {
      Array,
      default: () => []
    },
    myUserId: {
      String,
      default: ''
    },
    peopleModalType: {
      String,
      default: 'create'
    },
    pageType: {
      String,
      default: '1'
    },
    createParams: {
      Object,
      default: () => {}
    },
    clickItem: {
      Object,
      default: () => {}
    },
    groupPeopleData: {
      Array,
      default: () => []
    }
  },
  data () {
    return {
      dialogVisible: false,
      checkAll: false,
      isIndeterminate: false,
      checkList: [], // 选中的数据
      allUserList: {}, // 左侧展示的数据
      checkedUserData: {}, // 所有的选中人的数据
      roomName: '',
      filterText: '',
      selfData: null
    }
  },
  watch: {
    createParams (val) {
      this.roomName = val.groupName
    },
    createVisible (val) {
      this.dialogVisible = val
      if (val) {
        this.judgeType()
      } else {
        this.selfData = null
        this.checkList = []
      }
    },
    allUsers (val) {
      if (val && this.createVisible) {
        this.judgeType()
      }
    }
  },
  computed: {},
  created () {},
  mounted () {},
  methods: {
    depBoxShow (users) {
      for (const v of users) {
        if (v.userName.indexOf(this.filterText) > -1) {
          return true
        }
      }
      return false
    },
    handleClose () {
      this.roomName = ''
      this.filterText = ''
      this.$emit('update:createVisible', false)
    },
    saveCreate () {
      if (this.peopleModalType === 'create') {
        if (this.checkList.length < 2 || !this.roomName) {
          this.$message.error('请选择成员并填写群名称')
          return
        }
        let userIds = []
        this.checkList.forEach(v => {
          userIds.push(v.id)
        })
        let params = {
          groupId: this.pageType === '2' ? this.createParams.groupId : '',
          groupName: this.pageType === '2' ? this.createParams.groupName : this.roomName,
          createdUserId: this.myUserId,
          groupType: Number(this.pageType),
          groupStatus: 1,
          userIds: userIds
        }
        createGroup(params).then(data => {
          this.$message.success('创建群成功')
          this.$emit('update:createVisible', false)
        })
      } else {
        if (this.checkList.length === 0) {
          this.$message.error('请选择成员')
          return
        }
        let userIds = []
        this.checkList.forEach(v => {
          userIds.push(v.id)
        })
        let params = {
          groupId: this.clickItem.id,
          inviteUserId: this.myUserId,
          userIds: userIds
        }
        addPeopleToGroup(params).then(data => {
          this.$message.success('已成功邀请进群')
          this.$emit('update:createVisible', false)
        })
      }
    },
    judgeType () {
      this.allTrueUser = []
      if (this.peopleModalType === 'add') { // 添加
        for (const item of this.allUsers) {
          let flag = false
          for (const v of this.groupPeopleData) {
            if (item.user.id === v.id) {
              flag = true
            }
          }
          if (!flag) {
            this.allTrueUser.push(item)
          }
        }
      } else { // 创建
        this.allTrueUser = this.allUsers
        this.selfData = this.allUsers.find(res => {
          return res.user.id === this.myUserId
        })
      }
      this.dealAllUsers()
      if (this.peopleModalType === 'create') {
        // 默认选择自己，并判断全勾选还是半勾选
        this.checkMySelf()
      }
    },
    checkMySelf () {
      // 默认选择自己，并判断全勾选还是半勾选
      this.allUserList[this.selfData.user.dep].checkList = [this.selfData.user]
      this.depCheckGroup(this.selfData.user.dep, this.allUserList[this.selfData.user.dep].checkList)
    },
    addAllPeopleChange (val) { // 全部医生的checkbox改变
      this.isIndeterminate = false
      if (val) { // 全选
        for (const key in this.allUserList) {
          this.allUserList[key].checkList = this.allUserList[key].users
          this.allUserList[key].isIndeterminate = false
          this.allUserList[key].checkAll = true
        }
        this.checkList = this.allTrueUser// 全选就把数据都加进来
      } else { // 清空
        for (const key in this.allUserList) {
          this.allUserList[key].checkList = []
          this.allUserList[key].checkAll = false
        }
        if (this.peopleModalType === 'create') {
          this.checkMySelf()
        } else {
          this.checkList = []
        }
      }
      this.$forceUpdate()
    },
    dealAllUsers () { // 处理成处可展示的左侧列表数据
      this.allUserList = {}
      this.allTrueUser.forEach(v => {
        if (!this.filterText || v.user.userName.indexOf(this.filterText) > -1) { // 做名字过滤
          if (this.allUserList[v.user.dep]) {
            this.allUserList[v.user.dep].users.push(v.user)
          } else {
            let obj = {
              users: [v.user],
              isIndeterminate: false,
              checkAll: false,
              checkList: []
            }
            this.allUserList[v.user.dep] = obj
            this.$set(this.allUserList[v.user.dep], 'checkList', [])
          }
        }
      })
    },
    deleteChoose (key, id) { // 删除选择项
      let arr = []
      this.allUserList[key].checkList.forEach((v, i) => {
        if (v.id !== id) {
          arr.push(v)
        }
      })
      this.allUserList[key].checkList = arr
      this.depCheckGroup(key, this.allUserList[key].checkList)
      this.$forceUpdate()
    },
    depCheckAllChange (key, val) {
      this.allUserList[key].checkList = val ? this.allUserList[key].users : []
      this.allUserList[key].isIndeterminate = false
      if (!val && key === this.selfData.user.dep) {
        this.checkMySelf()
      }
      this.setCheckAll()
      this.$forceUpdate()
    },
    depCheckGroup (key, value) {
      // checkbox样式状态
      let checkedCount = value.length
      this.allUserList[key].checkAll = checkedCount === this.allUserList[key].users.length
      this.allUserList[key].isIndeterminate = checkedCount > 0 && checkedCount < this.allUserList[key].users.length
      this.setCheckAll()
      this.$forceUpdate()
    },
    setCheckAll () {
      // 所有医生的选择框状态判断和修改
      let checkAllNum = 0// 部门全选中的个数
      let num = 0// 部门个数
      this.checkList = []
      let indeterminateFlag = false
      for (const key in this.allUserList) {
        num++
        this.checkList = this.checkList.concat(this.allUserList[key].checkList)
        if (this.allUserList[key].checkAll) {
          checkAllNum++
        } else if (this.allUserList[key].isIndeterminate) {
          indeterminateFlag = true
        }
      }
      if (checkAllNum === 0 && !indeterminateFlag) {
        this.checkAll = false
        this.isIndeterminate = false
      } else if ((checkAllNum > 0 && checkAllNum < num) || indeterminateFlag) {
        this.checkAll = false
        this.isIndeterminate = true
      } else {
        this.checkAll = true
        this.isIndeterminate = false
      }
    }
  },
  beforeDestroy () {},
  destroyed () {},
  beforeUpdate () {},
  updated () {}
}
</script>
<style lang='scss' scoped>
.create-dialog{
    /deep/ .el-dialog{
        min-width:370px;
        max-width:600px;
    }
}
.create-body{
    height: 500px;
}
.create-body form{
    height: 100%;
}
.create-body img{
    margin-right: 5px;
}
.large-width{
    width:60%;
    height: 480px;
    border-left: 1px solid #ddd;
}
.list-group{
    margin-bottom: 0px;
}
.list-group input{
    margin-top:12px
}
.list-group-item{
    border: 0;
    padding: 10px 0px;
    .text{
        width: calc(100% - 50px);
        display: flex;
        justify-content: space-between;
    }
    .user-name{
        display: inline-block;
        min-width: 65px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
.list-group-item label{
    margin-bottom: 0;
}
.list-group .checkbox{
    margin-top:0px;
}
.create-roomName{
    position: absolute;
    bottom: 0;
    width: 94%;
}
img{
    width: 44px;
    height: 44px;
    margin-right: 5px;
    border-radius: 5px;
}
ul{
    padding:0px;
    margin-top: 0px;
    li{
        list-style-type: none;
        background-color: transparent;
    }
}
.title{
    font-size: 16px;
    margin-bottom: 10px;
    font-weight: 600;
}
.smallCheckbox >>>.el-checkbox__label{
    font-size: 12px;
}
.el-checkbox-group{
    max-height: calc(100% - 68px);
    overflow: auto;
    >>>.el-checkbox__input{
        float: left;
        margin-top: 15px;
    }
    >>>.el-checkbox__label{
        display: flex;
        align-items: center;
    }
}
#createAddPeopleList{
    height: calc(100% - 44px);
    overflow: auto;
}
.margin-tb-5{
    margin:5px 0;
}
#createPeopleList{
    height: 433px;
    overflow: auto;
}
</style>
