<!-- 角色编辑弹窗 -->
<template>
  <ele-modal
    width="460px"
    :visible="visible"
    :close-on-click-modal="false"
    :title="isUpdate ? '修改角色' : '添加角色'"
    @update:visible="updateVisible"
    :maxable="true"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-form-item label="角色名称:" prop="name">
        <el-input
          clearable
          :maxlength="20"
          v-model="form.name"
          placeholder="请输入角色名称"
        />
      </el-form-item>
      <el-form-item label="编码:" prop="code">
        <el-input placeholder=" " v-model="form.code" />
      </el-form-item>
      <el-form-item label="启用状态:" prop="enable">
        <el-switch
          v-model="form.enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="密级:" prop="secretLevel">
        <el-select v-model="form.secretLevel" style="width: 100%">
          <el-option
            v-for="item in secretLevelList()"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限范围" prop="dataScope">
        <DictSelection
          dictName="角色数据权限字典"
          clearable
          v-model="form.dataScope"
        >
        </DictSelection>
      </el-form-item>
      <el-form-item prop="dataScope">
        <el-scrollbar
          v-if="form.dataScope == '2'"
          v-loading="authLoading"
          style="height: 40vh"
          wrap-style="overflow-x: hidden;"
        >
          <el-tree
            ref="tree"
            :data="deptData"
            :check-strictly="true"
            highlight-current
            node-key="id"
            :props="{ label: 'name' }"
            :expand-on-click-node="false"
            show-checkbox
            :default-expand-all="true"
            :default-checked-keys="checkedKeys"
          />
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import { addRole, putRoles } from '@/api/system/role';
  import { listOrganizations } from '@/api/system/organization';
  import { secretLevelList } from '@/enum/dict';
  export default {
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object
    },
    created() {
      this.getListOrganizations();
    },
    data() {
      const defaultForm = {
        name: '',
        groupId: '',
        enable: 1,
        dataScope: '',
        dataScopeDeptIds: '',
        secretLevel: 1,code:''
      };
      return {
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          name: [
            {
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            }
          ],
          groupId: [
            {
              required: true,
              message: '请输入组织ID',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        authLoading: false,

        organizationList: []
      };
    },
    methods: {
      secretLevelList() {
        return secretLevelList;
      },

      query() {
        this.loading = true;
        listOrganizations()
          .then((list) => {
            this.loading = false;
            this.organizationList = this.$util.toTreeData({
              data: list,
              idField: 'id',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {
            this.loading = false;
          });
      },
      getListOrganizations() {
        this.authLoading = true;
        listOrganizations()
          .then((list) => {
            let _list = list.filter((i) => i.name != '超级管理员');
            this.authLoading = false;
            this.deptData = this.$util.toTreeData({
              data: _list,
              idField: 'id',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {
            this.loading = false;
            // this.$message.error(e.message);
          });
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          if (this.form.dataScope == '2') {
            const ids = this.$refs.tree
              .getCheckedKeys()
              .concat(this.$refs.tree.getHalfCheckedKeys());
            this.form.dataScopeDeptIds = ids.join(',');
          }
          const saveOrUpdate = this.isUpdate ? putRoles : addRole;
          saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(this.isUpdate ? '修改' : '增加' + msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              // this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          this.query();
          if (this.data != null) {
            // this.$util.assignObject(this.form, this.data);
            // this.form = this.data;
            this.form = Object.assign(this.data);
            this.form.dataScope = this.form.dataScope + '';
            this.$nextTick(() => {
              if (this.form.dataScope == '2') {
                this.$refs.tree.setCheckedKeys(
                  this.form.dataScopeDeptIds.split(',')
                );
              }
            });
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
