<!--
 * @Description: 角色管理-新增、编辑
 * @Author: jiang.pengkai
 * @Date: 2022-04-12 22:34:42
 * @LastEditTime: 2022-08-24 17:06:02
-->
<template>
  <div>
    <div style="margin-top: 20px;">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input style="width: 300px;" v-model="form.roleName" maxlength="35" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input style="width: 400px;" v-model="form.roleKey"  maxlength="64" />
          <span slot="label">
            权限字符
            <el-popover placement="top" trigger="hover" theme="dark">
              <div>控制器中定义的权限字符，如：@SaCheckPermission('system:user:list')"</div>
              <i class="el-icon-question" slot="reference" style="color:#abaeb4"></i>
            </el-popover>
          </span>
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" :max="999999999" />
        </el-form-item>
        <el-form-item label="功能权限">
          <el-tree :data="list" :default-checked-keys="checkedKeys" show-checkbox ref="menu" node-key="id" empty-text="加载中，请稍后" :props="defaultProps" ></el-tree>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom">
      <el-button plain @click="cancelFn">取消</el-button>
      <el-button type="primary" @click="submitFn">确定</el-button>
    </div>
  </div>
</template>
<script>
import { addRole, editRole } from '@/api/organization'
export default {
  name: 'roles-add-edit',
  data() {
    let self = this;
    var validateRoleName = (rule, value, callback) => {
      //角色名判重
      for (let index = 0; index < self.allRoles.length; index++) {
        if (self.form.roleId != self.allRoles[index].roleId &&
          self.form.roleName == self.allRoles[index].roleName) {
          callback(new Error('角色名称已经存在'));
          break;
        }
      }
      callback();
    }
    return {
      form: {
        dataScope: '1',
        users: [],
        menuIds: [],
        depts: [],
        roleName: '',
        roleSort: 12,
        roleSort: 0,
        status: '0'
      },
      dialogVisibleSelectUser: false,
      dialogVisibleSelectDept: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
          { validator: validateRoleName, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      selectedUserList: [],
      selectedDeptList: []
    }
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    checkedKeys: {
      type: Array,
      default: () => []
    },
    status: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      defaultL: () => { }
    },
    allRoles: {
      type: Array,
      default: () => []
    },
  },
  mounted() {
    if (this.status === 'edit') {
      this.setData()
    }
  },
  created() {
    this.setDisabledTreeData(this.list)
  },
  methods: {
    setDisabledTreeData(data) {
      data.map((item) => {
        if (item.labelKey == 'roles') {
          this.$set(item, "disabled", true);
        }
        let isFatherNode = item.children && item.children.length > 0;
        isFatherNode && this.setDisabledTreeData(item.children);
      });
    },
    setData() {
      this.form = this.data
      if (this.form.users && this.form.users.length) {
        let arr = []
        this.selectedUserList = this.form.users.map(i => {
          arr.push(i.userId)
          return {
            name: i.userName,
            userId: i.userId
          }
        })
        this.form.users = arr
      }
      if (this.form.depts && this.form.depts.length) {
        let arr2 = []
        this.selectedDeptList = this.form.depts.map(i => {
          arr2.push(i.deptId)
          return {
            deptName: i.deptName,
            deptId: i.deptId
          }
        })
        this.form.deptIds = arr2
        delete this.form.depts
      }
      if (this.form.menus && this.form.menus.length) {
        let arr = this.form.menus.map(i => {
          return i.menuId
        })
        if (this.$refs.menu) {
          this.$refs.menu.setCheckedKeys(arr);
        }
      }
    },
    onSelectDept() {
      this.dialogVisibleSelectDept = true
    },
    onSelectUser() {
      this.dialogVisibleSelectUser = true
    },
    selectedUser(users) {
      this.selectedUserList = users
      let arr = users.map(i => {
        return i.userId
      })
      this.form.users = arr
    },
    selectedDept(depts) {
      this.selectedDeptList = depts
      if (depts && depts.length) {
        let arr = depts.map(i => {
          return i.deptId
        })
        this.form.deptIds = arr
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
      let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    submitFn() {
      if (this.status === 'add') {
        this.doAddRol()
      } else {
        this.doEditRol();
      }
    },
    doAddRol() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.menuIds = this.getMenuAllCheckedKeys()
          addRole(this.form).then(res => {
            this.$emit('update')
          })
        }
      })
    },
    doEditRol() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$confirm('是否确认修改当前角色？修改后即时生效。', "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            delete this.form.menus
            editRole(this.form).then(res => {
              this.$emit('update')
            })
          }).catch(function () { });
        }
      })
    },
    cancelFn() {
      this.$emit('cancel')
    }
  }
}
</script>
<style lang="scss" scoped>
.bottom {
  display: flex;
  justify-content: flex-end;
  border-radius: 5px;
  padding: 20px;
  background-color: #ffffff10;
}
</style>

