<template>
  <div>
    <el-button v-permission="'user:CreateMembership'"  type="primary" style="margin-bottom: 10px;" @click="toAddGroup">添加到用户组</el-button>
    <el-table
      key="addedGroupTable"
      :data="addedGroupList"
      class="table-height-auto"
    >
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column
        prop="groupName"
        label="用户组名"
        min-width="250">
      </el-table-column>
      <el-table-column
        prop="displayName"
        label="显示名称"
        min-width="180">
      </el-table-column>
      <el-table-column
        prop="agentNo"
        label="工号"
        min-width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        min-width="80">
        <template slot-scope="scope">
          <el-button v-permission="'user:DeleteMembership'" type="text" @click="removeGroup(scope.$index)" >移除该组</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加用户组 -->
    <el-dialog :append-to-body="true" style="min-height: 400px" title="添加用户组" :modal="true" top="100px" :close-on-click-modal="false" v-if="showAddGroup" :visible.sync="showAddGroup">
      <div slot="title" class="custom-el-dialog-header-title">
        <span>添加用户组</span>
        <div class="plain-button" @click="saveMembership">
          <i class="font_family icon-save plain-button-icon"></i><span class="plain-button-text">&nbsp;保存</span>
        </div>
      </div>
      <el-table
        ref="addGroupTable"
        :data="availableGroupList"
        class="table-height-auto"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column
          prop="groupName"
          label="用户组名"
          min-width="100">
        </el-table-column>
        <el-table-column
          prop="displayName"
          label="显示名称"
          min-width="100">
        </el-table-column>
        <el-table-column
          prop="comments"
          label="备注">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'UserGroupSelector',
  props: {
    userId: {
      required: true
    }
  },
  data () {
    return {
      showAddGroup: false,
      allGroupList: [],
      addedGroupList: []
    }
  },
  computed: {
    availableGroupList: function () {
      const groupSet = new Set(this.addedGroupList.map(u => u.id))
      return this.allGroupList.filter(g => !groupSet.has(g.id))
    }
  },
  created () {
  },
  mounted () {
    // 加载用户所在组
    this.loadUserGroup()
  },
  methods: {
    loadAllGroup () {
      this.$http.get(this.$apiUrl('listGroup'))
        .then(response => {
          this.allGroupList = response.data.data
        })
        .catch((error) => {
          this.$message.error(error.message)
        })
    },
    loadUserGroup () {
      // 加载指定用户的用户组信息
      if (typeof (this.userId) === 'string') {
        this.$http.get(this.$apiUrl('getUserGroupOfUser') + `?id=${this.userId}`).then((response) => {
          this.addedGroupList = response.data.data
        }).catch((response) => {
          console.log('获取用户组列表失败', response)
          this.$message.error(response.message)
        })
      }
    },
    emitChangeEvent () {
      this.$emit('change')
    },
    toAddGroup () {
      this.showAddGroup = true
      if (this.allGroupList.length === 0) {
        this.loadAllGroup()
      }
    },
    // 保存添加组
    saveMembership () {
      const selectionGroup = this.$refs.addGroupTable.selection
      const groupId = selectionGroup.map(group => group.id)
      if (groupId.length === 0) {
        return this.$message.warning('请选择用户组')
      }
      // this.$qs.stringify(this.userForm)
      // console.log('@@@@@@@@@@@', {userId: this.userId, groupId })
      this.$http.post(this.$apiUrl('createMembershipOfUser'), { userId: this.userId, groupId })
        .then(response => {
          this.$message.success('添加用户组成功')
          this.addedGroupList.push(...selectionGroup)
          this.showAddGroup = false
          console.log(this.addedGroupList)
          // 发布修改事件
          this.emitChangeEvent()
        })
        .catch(error => {
          this.$message.error(`创建失败! ${error.message}`)
        })
        .always(() => {
        })
      console.log(this.$refs.addGroupTable.selection)
    },
    removeGroup (index) {
      const groupId = [this.addedGroupList[index].id]
      const url = this.$apiUrl('deleteMembershipOfUser') + '?' + this.$qs.stringify({ userId: this.userId, groupId })
      this.$http.delete(url)
        .then(response => {
          this.$message.success('移除用户组成功')
          this.addedGroupList.splice(index, 1).map(group => group.id)
          console.log(this.addedGroupList)

          // 发布修改事件
          this.emitChangeEvent()
        })
        .catch(error => {
          this.$message.error(`移除用户组成功! ${error.message}`)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '../../style/mixin';
</style>
