<!--
  @description: 系统设置->用户管理-设置角色
  @author: 肖文龙
  @routerPath:
  @date:  2020/09/13
-->
<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="设置角色"
      custom-class="el-dialog__body-p0"
      width="540px"
    >
      <div class="main mb10">
        <el-transfer
          v-model="userRoleIds"
          :filterable="true"
          :props="roleProp"
          :titles="['可选角色', '已有角色']"
          :button-texts="['撤回', '设置']"
          :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
          :data="roleList"
          @change="setRole"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* api */
import { findRoleList, delRole, setRole } from '@/api/common/user'
/* 混入 */
import { ListMixin } from '@/mixins/ListMixin'
/* 组件*/
import pagination from '@comp/common/pagination/pagination'// 分页

export default {
  components: {
    pagination
  },
  mixins: [ListMixin],
  data() {
    return {
      dialogVisible: false,
      // props
      roleProp: {
        key: 'id',
        label: 'roleName'
      },
      roleList: [], // 角色权限列表
      userRoleIds: [], // 已设置的角色权限id
      // 用户信息
      userData: {
        userId: '', // 用户id
        departId: ''// 机构id
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        // 初始化
        this.rowData = {}
      }
    }
  },
  methods: {
    // 打开弹框
    open(data) {
      this.dialogVisible = true
      this.userRoleIds = []
      this.userData = data
      this.loadData(data)// 获取数据
    },
    // 获取数据
    loadData(datas) {
      // 获取可用的角色列表
      const data = {
        departId: datas.departId, // 机构id
        userId: datas.userId// 用户id
      }
      findRoleList(data).then(response => {
        this.roleList = [...response.data.noList, ...response.data.isList] // 左边直接获取
        response.data.isList.forEach((info) => {
          // 右边遍历id
          this.userRoleIds.indexOf(info.id) < 0 && this.userRoleIds.push(info.id)
        })
      })
    },
    // 设置角色
    setRole(value, direction, movedKeys) {
      const data = {
        userId: this.userData.userId,
        departId: this.userData.departId,
        roleId: movedKeys
      }
      // 设置角色调用的方法
      if (direction === 'left') {
        this.recallRoleApi(data)
      } else {
        this.setRoleApi(data)
      }
    },
    // 撤回角色接口
    recallRoleApi(data) {
      delRole(data).then(() => {
        this.$message({
          message: '撤回成功',
          type: 'success'
        })
        this.$emit('call-back')
      })
    },
    // 设置角色接口
    setRoleApi(data) {
      setRole(data).then(() => {
        this.$message({
          message: '设置成功',
          type: 'success'
        })
        this.$emit('call-back')
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
