<template>
  <el-dialog
    class="modify-role"
    :visible.sync="modalIsShow"
    :title="title"
    top="10px"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="part-box part-box-pad part-box-border">
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item prop="name" label="角色名称：">
          <el-input
            style="width:100%;"
            v-model.trim="modalForm.name"
            placeholder="请输入角色名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="privilegeIds" label="角色权限：">
          <div class="part-box part-box-pad part-box-border">
            <el-tree
              :data="menus"
              show-checkbox
              node-key="id"
              ref="MenuTree"
              highlight-current
              check-on-click-node
              :expand-on-click-node="false"
              :default-expanded-keys="defaultExpandedKeys"
              :props="defaultProps"
              @check-change="checkChange"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span
                  ><i class="el-icon-link" v-if="data.type === 'URL'"></i>
                  {{ node.label }}</span
                >
              </span>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateRole, menuAuthList, roleBoundPrivileges } from "../../base/api";

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

export default {
  name: "modify-role",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "角色";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      menus: [],
      defaultExpandedKeys: [],
      modalForm: {},
      defaultProps: {
        label: "name"
      },
      rules: {
        name: [
          {
            required: true,
            pattern: /^[0-9a-zA-Z\u4E00-\u9FA5]{1,10}$/,
            message: "角色名称只能输入汉字、字母和数字，长度不能超过10",
            trigger: "change"
          }
        ],
        type: [
          {
            required: true,
            message: "请选择角色类型",
            trigger: "change"
          }
        ],
        privilegeIds: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.modalForm.type !== "CUSTOM" || value.length) {
                callback();
              } else {
                callback(new Error("请选择扩展字段"));
              }
            },
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.getMenus();
  },
  methods: {
    async getMenus() {
      const data = await menuAuthList();
      if (data) this.menus = data.filter(item => item.url !== "common");
      this.defaultExpandedKeys = [];
      this.getDefaultExpandedKeys(this.menus);
    },
    async visibleChange() {
      console.log(this.instance);
      if (this.instance.id) {
        this.modalForm = this.$objAssign(initModalForm, this.instance);
        let privilegeIds = await roleBoundPrivileges(this.instance.id);
        privilegeIds = privilegeIds || [];
        let checkedIds = [];
        const getCheckedIds = list => {
          list.forEach(item => {
            if (item["children"] && item["children"].length) {
              getCheckedIds(item.children);
            } else {
              const isChecked = privilegeIds.includes(item.id);
              if (isChecked) checkedIds.push(item.id);
            }
          });
        };
        getCheckedIds(this.menus);
        this.$refs.MenuTree.setCheckedKeys(checkedIds);
        this.modalForm.privilegeIds = checkedIds;
      } else {
        this.modalForm = { ...initModalForm };
        this.$refs.MenuTree.setCheckedKeys([]);
      }
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    getDefaultExpandedKeys(menus) {
      menus.forEach(item => {
        if (
          item.children &&
          item.children.length &&
          !item.children.some(elem => elem.type === "URL")
        ) {
          this.defaultExpandedKeys.push(item.id);
          this.getDefaultExpandedKeys(item.children);
        }
      });
    },
    checkChange(data, checked) {
      this.modalForm.privilegeIds = this.$refs.MenuTree.getCheckedKeys();
      this.$refs.modalFormComp.validateField("privilegeIds");
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { ...this.modalForm };
      const privilegeIds = [
        ...this.$refs.MenuTree.getCheckedKeys(),
        ...this.$refs.MenuTree.getHalfCheckedKeys()
      ];
      datas.privilegeIds = privilegeIds;
      const data = await updateRole(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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