<template>
  <div class="cqcy-content" style="margin: 0;height: calc(100% - 70px);">
    <breadcrumb-view :breadcrumbList="breadcrumbList" :show-index="false"></breadcrumb-view>
    <el-button type="primary" class="cy-nav-btn" icon="el-icon-circle-plus-outline" size="mini" @click="handleAdd">新增</el-button>
    <el-divider></el-divider>
    <div class="cy-main">
      <el-table :data="groupDataList" style="width: 100%" border :stripe="true"
                @sort-change="sortChange"
                :header-cell-style="{background: '#E8E8E8'}">
        <el-table-column label="用户组名称" sortable="custom" prop="userGroupName" align="center"></el-table-column>
        <el-table-column label="排序号" sortable="custom" prop="sortNum" width="120" align="center"></el-table-column>
        <el-table-column label="备注" prop="userGroupDescribe" align="center"></el-table-column>
        <el-table-column label="创建时间" sortable prop="createTime" width="160" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
<!--            <el-button size="mini" type="primary"-->
<!--                @click="handleDetail(scope.$index, scope.row)">详情</el-button>-->
            <el-button size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增用户组 -->
    <el-dialog
        :title="userGroupTitle"
        width="600px"
        top="10vh"
        center
        v-dialog-drag
        v-if="dialogAddUserGroup"
        :before-close="dialogClose"
        :visible.sync="dialogAddUserGroup"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form ref="userGroupForm" :model="userGroupForm" :rules="userGroupRules" label-width="110px">
        <el-form-item label="用户组名称" prop="userGroupName">
          <el-input v-model="userGroupForm.userGroupName" maxlength="50"
                    placeholder="请输入用户组名称" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="组人员" prop="groupUserList">
          <el-input :value="userGroupForm.userNameList.join(',')" placeholder="请选择用户"
                    readonly style="width: calc(100% - 100px); margin-right: 15px;"></el-input>
          <el-button size="mini" @click="chooseUserEvent">选择人员</el-button>
          <span v-if="userGroupForm.userIdList.length > 0"
                style="font-size: 12px; color: #8e8c8c;">已选择 {{ userGroupForm.userIdList.length }} 人</span>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input-number v-model="userGroupForm.sortNum" :min="1" :max="99999" label="请输入排序号"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="userGroupDescribe">
          <el-input type="textarea" v-model="userGroupForm.userGroupDescribe" maxlength="200"
                    placeholder="请输入备注" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <span slot='footer'>
        <el-button type="primary" @click="addUserGroup">确定</el-button>
        <el-button @click="dialogClose">取消</el-button>
      </span>
    </el-dialog>

    <!-- 用户树 -->
    <el-dialog
        title="请选择用户"
        width="80%"
        top="10vh"
        center
        v-dialog-drag
        v-if="dialogDepartmentTree"
        :before-close="handleDeptCancel"
        :visible.sync="dialogDepartmentTree"
        :close-on-click-modal="false"
        :append-to-body="true">
      <div style="display: flex;height: 50vh; overflow: auto;">
        <div style="width: calc(30% - 15px); margin-right: 15px;">
          <el-tree :data="departments" :default-expand-all="true" @node-click="handleNodeClick"></el-tree>
        </div>
        <div style="width: 70%; border-left: 1px solid #d8d6d6; padding-left: 20px;">
          <el-table :data="userDataList" border :stripe="true"
                    @sort-change="sortChange1"
                    :header-cell-style="{background: '#E8E8E8'}">
            <el-table-column label="用户名称" sortable="custom" prop="userName" align="center"></el-table-column>
            <el-table-column label="最后登录时间" sortable prop="lastLoginTime" width="160" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-link type="danger" :underline="false" icon="el-icon-delete"
                         v-if="scope.row.hasAdd"
                         @click="removeUserForm(scope.$index, scope.row)">移除</el-link>
                <el-link type="primary" :underline="false" icon="el-icon-circle-plus-outline"
                         v-else
                         @click="addUserForm(scope.$index, scope.row)">添加</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import BreadcrumbView from '@/components/BreadcrumbView'
import {customCompare, showAlertWin, showLoading} from "@/utils/cqcy";
import {
  addUserGroup,
  delUserGroupById,
  getAllUserGroup,
  getClientUserByDepartmentId,
  getDepartmentTree, getUserByGroupId,
  updateUserGroup
} from "@/api/user";

export default {
  name: 'index',
  components: {
    BreadcrumbView
  },
  data() {
    return {
      breadcrumbList: ['用户组'],
      dialogAddUserGroup: false,
      dialogDepartmentTree: false,
      userGroupTitle: '新增用户组',
      groupDataList: [],
      userDataList: [],
      departments: [],
      userGroupForm: {
        id: null,
        userGroupName: null,
        sortNum: 1,
        userGroupDescribe: null,
        userNameList: [],
        userIdList: []
      },
      userGroupRules: {
        userGroupName: [
          {required: true, trigger: "blur", message: "用户组名称不能为空"}
        ]
      }
    }
  },
  watch: {
  },
  beforeDestroy() {
  },
  created() {
    this.getAllUserGroup()
  },
  methods: {
    sortChange({ prop, order }) {
      this.groupDataList.sort(customCompare(prop, order))
    },
    sortChange1({ prop, order }) {
      this.userDataList.sort(customCompare(prop, order))
    },
    /** 新增 */
    handleAdd() {
      this.userGroupForm = {
        id: null,
        userGroupName: null,
        sortNum: 1,
        userGroupDescribe: null,
        userNameList: [],
        userIdList: []
      }
      this.userGroupTitle = '新增用户组'
      this.dialogAddUserGroup = true
    },
    /** 详情 */
    handleDetail(index, row) {
      console.log(row)
    },
    /** 编辑 */
    handleEdit(index, row) {
      this.userGroupTitle = '编辑用户组'
      this.userGroupForm = {
        id: row.id,
        userGroupName: row.userGroupName,
        sortNum: row.sortNum,
        userGroupDescribe: row.userGroupDescribe,
        userNameList: [],
        userIdList: []
      }
      getUserByGroupId(row.id).then(res => {
        let data = res.data
        for (let i = 0; i < data.length; i ++) {
          this.userGroupForm.userIdList.push(data[i].userId)
          this.userGroupForm.userNameList.push(data[i].userName)
        }
        this.dialogAddUserGroup = true
      }).catch((e) => {
        this.dialogAddUserGroup = true
        showAlertWin(this, e)
      })
    },
    /** 删除 */
    handleDelete(index, row) {
      this.$confirm('您确定要删除该用户组吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'close_confirm',
        closeOnClickModal: false
      }).then(() => {
        const loading = showLoading(this, '删除中，请稍候···')
        delUserGroupById(row.id).then(res => {
          loading.close()
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.getAllUserGroup()
        }).catch((e) => {
          loading.close()
          showAlertWin(this, e)
        })
      }).catch(() => {
      })
    },
    /** 修改选择用户信息 */
    updateChooseUserInfo(userId, flag) {
      for (let i = 0; i < this.userDataList.length; i ++) {
        if (this.userDataList[i].userId === userId) {
          this.$set(this.userDataList[i], 'hasAdd', flag)
          break
        }
      }
    },
    /** 添加用户 */
    addUserForm(index, row) {
      // 避免重复添加用户
      if (this.userGroupForm.userIdList.indexOf(row.userId) < 0) {
        this.userGroupForm.userIdList.push(row.userId)
        this.userGroupForm.userNameList.push(row.userName)
      }
      // 修改当前用户组数据
      this.updateChooseUserInfo(row.userId, true)
    },
    /** 移除用户 */
    removeUserForm(index, row) {
      // 判断用户是否存在
      let idx = this.userGroupForm.userIdList.indexOf(row.userId)
      if (idx < 0) {
        return
      }
      this.userGroupForm.userIdList.splice(idx, 1)
      this.userGroupForm.userNameList.splice(idx, 1)
      // 修改当前用户组数据
      this.updateChooseUserInfo(row.userId, false)
    },
    /** 组织树节点点击事件 */
    handleNodeClick(data, node, target) {
      getClientUserByDepartmentId(data.id).then(res => {
        if (!res.data) {
          return
        }
        this.userDataList = res.data
        let userIdList = this.userGroupForm.userIdList
        for (let i = 0; i < userIdList.length; i ++) {
          // 修改当前用户组数据
          this.updateChooseUserInfo(userIdList[i], true)
        }
      }).catch((e) => {
        showAlertWin(this, e)
      })
    },
    /** 选择用户事件 */
    chooseUserEvent() {
      this.userDataList = []
      this.loadDepartmentUser()
      this.dialogDepartmentTree = true
    },
    /** 用户树取消选择 */
    handleDeptCancel() {
      this.dialogDepartmentTree = false
    },
    /** 加载部门下客户端人员 */
    loadDepartmentUser() {
      getDepartmentTree().then(res => {
        if (!res.data) {
          return
        }
        this.departments = res.data
      }).catch((e) => {
        showAlertWin(this, e)
      })
    },
    /** 获取用户组 */
    getAllUserGroup() {
      getAllUserGroup().then(res => {
        if (!res || !res.data) {
          return
        }
        this.$nextTick(() => {
          this.groupDataList = res.data
        })
      }).catch((e) => {
        showAlertWin(this, e)
      })
    },
    /** 添加用户组 */
    addUserGroup() {
      this.$refs['userGroupForm'].validate((valid) => {
        if (valid) {
          const loading = showLoading(this, '保存中，请稍候···')
          if (this.userGroupForm.id) {
            updateUserGroup(this.userGroupForm).then(res => {
              loading.close()
              this.$message({
                message: '修改成功！',
                type: 'success'
              })
              this.dialogAddUserGroup = false
              this.userGroupForm.id = null
              this.$refs['userGroupForm'].resetFields()
              this.getAllUserGroup()
            }).catch((e) => {
              loading.close()
              showAlertWin(this, e)
            })
            return
          }
          addUserGroup(this.userGroupForm).then(res => {
            loading.close()
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            this.dialogAddUserGroup = false
            this.$refs['userGroupForm'].resetFields()
            this.getAllUserGroup()
          }).catch((e) => {
            loading.close()
            showAlertWin(this, e)
          })
        }
      })
    },
    /** 弹出层关闭事件 */
    dialogClose(done) {
      if (this.$refs['userGroupForm'])
        this.$refs['userGroupForm'].resetFields()
      if (typeof(done) === 'function') {
        done()
      } else {
        this.dialogAddUserGroup = false
      }
      this.getAllUserGroup()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.breadcrumb-content {
  padding-bottom: 0;
}

.cy-main {
  margin: 10px 20px;
  width: calc(100% - 40px);
  height: calc(100% - 100px);
}

.cy-nav-btn {
  float: right!important;
  margin-right: 20px!important;
  margin-top: -20px!important;
}
</style>