<template>
  <Popup ref="popup" title="角色信息" @closed="dialogClosed">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px">
      <el-form-item label="角色名称" prop="roleName" placeholder="请输入角色名称">
        <el-input v-model="form.roleName" :maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="角色ID" prop="roleId">
        <el-input v-model="form.roleId" disabled placeholder="系统将自动生成"></el-input>
      </el-form-item>
      <el-form-item label="角色状态" prop="status" required>
        <el-switch
          :value="form.status === RULE_STATUS.getValueByName('enabled')"
          @change="form.status = $event ? RULE_STATUS.getValueByName('enabled') : RULE_STATUS.getValueByName('disabled')"
        />
      </el-form-item>
      <el-form-item label="角色权限" prop="menuIdList">
        <div class="tree-menus">
          <el-tree
            ref="tree"
            v-model="form.menuIdList"
            :data="treeData"
            show-checkbox
            node-key="id"
            @check="handleSelectMenuChange"
            :props="{ children: 'children', label: 'menuName', isLeaf: true }"
            default-expand-all
          ></el-tree>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </Popup>
</template>

<script>
import Popup from "@/components/Popup";
import { geMenuTreeList, getRoleMenuList, saveRole } from "@/api/admin";
import { RULE_STATUS } from '@/enums/index';
export default {
  components: {
    Popup,
  },
  data() {
    return {
      RULE_STATUS,
      loading: false,
      form: this.getFormDefaultValue(),
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        menuIdList: [{ required: true, message: "请选择角色权限", trigger: "change" }],
      },
      treeData: [],
    };
  },
  created() {
    this.loadAllMenuList();
  },
  methods: {
    loadAllMenuList() {
      return geMenuTreeList().then((res) => {
        this.treeData = res.data;
      });
    },
    loadMenuIdList(roleId) {
      return getRoleMenuList({ roleId }).then((res) => {
        this.form.menuIdList = res.data.map((item) => item.menuId);
      });
    },
    handleSelectMenuChange(_, { checkedKeys, halfCheckedKeys }) {
      this.form.menuIdList = checkedKeys;
      this.$refs.form.validateField("menuIdList");
    },
    getFormDefaultValue() {
      return {
        roleName: "",
        status: RULE_STATUS.getValueByName('enabled'),
        menuIdList: [],
      };
    },
    open(params) {
      this.$refs.popup.open(params);
      if (params) {
        for (const key of Object.keys(this.form)) {
          this.form[key] = params[key];
        }
        this.form.roleId = params.id;
        if (params.menuIdList) {
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(params.menuIdList);
          });
        } else {
          this.loadMenuIdList(params.id);
        }
      }
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    handleCancel() {
      this.$refs.popup.close();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const res = await saveRole(this.form);
            if (this.form.roleId) {
              this.$message.success("修改成功");
            } else {
              this.$message.success("新增成功");
            }
            this.$refs.popup.close();
            this.promise.resolve(res.data);
          } finally {
            this.loading = false;
          }
        } else {
          // 表单校验失败
          return false;
        }
      });
    },
    dialogClosed() {
      this.$refs.tree.setCheckedKeys([]);
      this.form = this.getFormDefaultValue();
      this.$nextTick(() => {
        this.$refs.form.clearValidate("menuIdList");
      });
      // this.promise.reject();
    },
  },
};
</script>
<style lang="scss" scoped>
.tree-menus {
  border: 1px solid #dfe4ed;
  height: 200px;
  border-radius: 4px;
  overflow-y: auto;
}
</style>
