<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-width="90px"
    >
      <el-form-item prop="name" label="角色名称：">
        <el-input
          style="width: 282px"
          v-model.trim="modalForm.name"
          placeholder="请输入角色名称"
          :disabled="modalForm.defaultRole"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="interpret" label="角色描述：">
        <el-input
          v-model.trim="modalForm.interpret"
          type="textarea"
          placeholder="建议不超过100个字"
          resize="none"
          :disabled="modalForm.defaultRole"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="dataPermissionType" label="数据权限：">
        <el-select
          v-model="modalForm.dataPermissionType"
          placeholder="请选择"
          style="width: 282px"
          @change="dataPermissionTypeChange"
        >
          <el-option
            v-for="(val, key) in DATA_PRIVILEGE_TYPE"
            :key="key"
            :value="key"
            :label="val"
          ></el-option>
        </el-select>
      </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 { DATA_PRIVILEGE_TYPE } from "../../../constants/enumerate";
import { updateRole, privilegeList, roleBoundPrivileges } from "../api";
import PrivilegeSet from "./PrivilegeSet";
// import navs from "./privilege/navs.json";

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

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: {},
      DATA_PRIVILEGE_TYPE,
      rules: {
        name: [
          {
            required: true,
            pattern: /^[0-9a-zA-Z\u4E00-\u9FA5]{1,20}$/,
            message: "角色名称只能输入汉字、字母和数字，长度不能超过20",
            trigger: "change",
          },
        ],
        // dataPermissionType: [
        //   {
        //     required: true,
        //     message: "请选择数据权限",
        //     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 = [],
        dataPermissionInfo = [],
        disabledIds = [];
      if (this.instance.id) {
        this.modalForm = this.$objAssign(initModalForm, this.instance);
        const data = await roleBoundPrivileges(this.instance.id);
        privilegeIds = data.privilegeIds || [];
        dataPermissionInfo = data.dataPermissionInfo || [];
        if (this.instance.defaultRole)
          disabledIds = data.defaultPrivilegeIds || [];
        this.modalForm.privilegeIds = privilegeIds;
      } else {
        this.modalForm = { ...initModalForm };
      }
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
        this.$refs.PrivilegeSet.buildTableData(
          privilegeIds,
          dataPermissionInfo,
          disabledIds
        );
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dataPermissionTypeChange() {
      this.$refs.PrivilegeSet.resetdataPermissionType(
        this.modalForm.dataPermissionType
      );
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      const { privilegeIds, dataPermissionInfo } =
        this.$refs.PrivilegeSet.getSelectedPrivileges();
      if (!privilegeIds.length) {
        this.$emit("请设置功能权限！");
        return;
      }

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

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