<template>
  <el-dialog
    class="modify-role"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :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="type" label="角色类型：">
          <el-select
            v-model="modalForm.type"
            style="width: 100%;"
            placeholder="请选择"
          >
            <el-option
              v-for="(val, key) in ROLE_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="modalForm.type === 'CUSTOM'"
          prop="privilegeIds"
          label="角色权限："
        >
          <div class="part-box part-box-pad part-box-border">
            <el-tree
              :data="menus"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="MenuTree"
              highlight-current
              :props="defaultProps"
              check-on-click-node
              :expand-on-click-node="false"
              @check-change="checkChange"
            >
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button type="primary" @click="submit">确认</el-button>
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateRole, roleBoundPrivileges } from "../api";
import { getEnums } from "../../login/api";
import { ROLE_TYPE } from "../../../constants/enumerate";

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

export default {
  name: "modify-role",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    menus: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "角色";
    }
  },
  data() {
    return {
      modalIsShow: false,
      modalForm: {},
      defaultProps: {
        label: "name"
      },
      ROLE_TYPE,
      // ROLE_TYPE: {},
      rules: {
        name: [
          {
            required: true,
            pattern: /^[\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"
          }
        ]
      }
    };
  },
  mounted() {
    // this.getRoleTypes();
  },
  methods: {
    async getRoleTypes() {
      const data = await getEnums("ROLE_TYPE");
      let ROLE_TYPE = {};
      data.forEach(element => {
        ROLE_TYPE[element.name] = element.desc;
      });
      this.ROLE_TYPE = ROLE_TYPE;
    },
    async visibleChange() {
      if (this.instance.id) {
        this.modalForm = this.$objAssign(initModalForm, this.instance);
        let privilegeIds = await roleBoundPrivileges(this.instance.id);
        let checkedIds = [];
        const getCheckedIds = list => {
          list.forEach(item => {
            if (item["children"]) {
              getCheckedIds(item.children);
            } else {
              const isChecked = privilegeIds.includes(item.id);
              if (isChecked) checkedIds.push(item.id);
            }
          });
        };
        getCheckedIds(this.menus);
        console.log(checkedIds);
        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;
    },
    checkChange() {
      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.join();
      const data = await updateRole(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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