<template>
  <el-dialog
    class="modify-role"
    :visible.sync="modalIsShow"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    fullscreen
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="name" label="角色名称：">
        <el-input
          style="width:282px;"
          v-model.trim="modalForm.name"
          placeholder="请输入角色名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="interpret" label="角色说明：">
        <el-input
          v-model.trim="modalForm.interpret"
          placeholder="请输入角色名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="角色权限：" required></el-form-item>
    </el-form>
    <privilege-set
      v-if="menus && menus.length"
      ref="PrivilegeSet"
      :menus="menus"
    ></privilege-set>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateRole, privilegeList, roleBoundPrivileges } from "../api";
import PrivilegeSet from "./PrivilegeSet";
// import navs from "./privilege/navs.json";

const initModalForm = {
  id: null,
  name: "",
  interpret: "",
  privilegeIds: []
};

export default {
  name: "modify-role",
  components: { PrivilegeSet },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "角色";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      menus: [],
      modalForm: {},
      rules: {
        name: [
          {
            required: true,
            pattern: /^[0-9a-zA-Z\u4E00-\u9FA5]{1,20}$/,
            message: "角色名称只能输入汉字、字母和数字，长度不能超过20",
            trigger: "change"
          }
        ],
        interpret: [
          {
            required: false,
            max: 100,
            message: "角色说明最多100个字符",
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.getMenus();
  },
  methods: {
    async getMenus() {
      const data = await privilegeList();
      const needHideModules = ["common", "customer"];
      if (data)
        this.menus = data
          .filter(item => !needHideModules.includes(item.url))
          .map(item => {
            item.parentId = null;
            return item;
          });
    },
    async visibleChange() {
      let privilegeIds = [];
      if (this.instance.id) {
        this.modalForm = this.$objAssign(initModalForm, this.instance);
        privilegeIds = await roleBoundPrivileges(this.instance.id);
        privilegeIds = privilegeIds || [];
        this.modalForm.privilegeIds = privilegeIds;
      } else {
        this.modalForm = { ...initModalForm };
      }
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
        this.$refs.PrivilegeSet.buildTableData(privilegeIds);
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      const privilegeIds = this.$refs.PrivilegeSet.getSelectedPrivilegeIds();
      if (!privilegeIds.length) {
        this.$emit("请设置角色权限！");
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { ...this.modalForm };
      datas.privilegeIds = privilegeIds;
      const data = await updateRole(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$emit("modified", this.modalForm);
      this.cancel();
    }
  }
};
</script>
