<template>
  <el-dialog
    :visible="dialogVisible"
    width="30%"
    style="height: 98%"
    :before-close="handleClose"
    top="5vh"
    lock-scroll
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">{{ title }}</div>
    </div>
    <div class="dialog-content">
      <el-form
        size="mini"
        :model="dialogForm"
        class="basic-info"
        :rules="rules"
        ref="dialogForm"
      >
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="dialogForm.name"
            autocomplete="off"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属父角色"
          :label-width="formLabelWidth"
          prop="pid"
        >
          <el-tree
            :data="allRole"
            show-checkbox
            check-on-click-node
            node-key="id"
            @check="roleParentTreeCheck"
            ref="roleParentTree"
            highlight-current
            :props="{ label: 'name' }"
            check-strictly
            :default-checked-keys="[dialogForm.pid]"
            :default-expanded-keys="[dialogForm.pid]"
          >
            <!-- <span slot-scope="{ node, data }">
              {{ data.id }}
            </span> -->
          </el-tree>
        </el-form-item>
        <el-form-item label="菜单权限" :label-width="formLabelWidth">
          <el-tree
            ref="menuPermisionTree"
            :data="dialogForm.permissionRespNodes"
            show-checkbox
            :props="props"
            node-key="id"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch v-model="status"> </el-switch>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            v-model="dialogForm.remark"
          >
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button size="mini" @click="cancelForm">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleSubmit"
        >确定<i class="el-icon-circle-check" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addRole,
  upadateRole,
  getPermissionTreeAll,
  getUserOwnRolesV1,
} from "@/api/user";
import { mapGetters } from "vuex";
export default {
  name: "InfoEditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      if (this.dialogForm.id) {
        return "修改角色信息";
      } else {
        return "新建角色";
      }
    },
  },
  watch: {
    form: {
      handler: function (value) {
        // debugger
        let that = this;
        that.dialogForm = JSON.parse(JSON.stringify(value));
        // 编辑状态
        if (that.dialogForm.id) {
          // 回填状态
          that.status = Boolean(Number(that.dialogForm.status));
          that.setPer();
          // debugger
        } else {
          that.getAllMenuTree();
        }
        that.getAllRoleTree();
      },
      immediate: true,
      deep: true,
    },
    visible: {
      handler: function (value) {
        this.dialogVisible = value;
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    var validatePid = (rule, value, callback) => {
      let arr = this.$refs.roleParentTree.getCheckedKeys(); // 在此获取选中的树形数据
      if (arr.length == 0 || !arr) {
        callback(new Error("请选择所属角色"));
      } else {
        callback();
      }
    };
    return {
      dialogForm: {},
      formLabelWidth: "100px",
      status: true,
      dialogVisible: false,
      props: {
        value: "id",
        label: "title",
        children: "children",
        checkStrictly: true,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
        ],
        pid: [
          {
            required: true,
            validator: validatePid,
            // message: "请选择所属角色",
            trigger: "blur",
          },
        ],
      },
      allRole: [],
      loading: false,
    };
  },

  methods: {
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.reload();
    },

    handleSubmit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { name, remark } = this.dialogForm;
          let status = this.status ? 1 : 0;
          const checkedKeys = this.$refs.menuPermisionTree.getCheckedKeys();
          const halfCheckedKeys =
            this.$refs.menuPermisionTree.getHalfCheckedKeys(); //半选中的也要传到后台
          const permissions = [...checkedKeys, ...halfCheckedKeys];
          const params = {
            name,
            status,
            permissions,
            remark,
          };
          let parentIdArr = this.$refs.roleParentTree.getCheckedKeys();
          if (parentIdArr.length > 0) {
            let pid = parentIdArr.toString();
            params.pid = pid;
          }
          if (this.dialogForm.id) {
            params.id = this.dialogForm.id;
            let res = await upadateRole(params);
            if (res.code == 0) {
              this.$message.success("修改成功！");
              this.reload();
            }
            this.loading = false;
          } else {
            params.dataScope = "5"; //默认数据权限为自己
            let res = await addRole(params);
            if (res.code == 0) {
              this.$message.success("添加成功！");
              this.reload();
            }
            this.loading = false;
          }
        }
      });
    },
    reload() {
      this.$emit("handleClose");
      this.$refs.dialogForm.resetFields();
      this.$emit("refresh");
      this.$nextTick(() => {
        this.$refs.menuPermisionTree.setCheckedKeys([]);
      });
      this.allRole = [];
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.reload();
        })
        .catch((_) => {});
    },

    setPer() {
      let checkedIds = [];
      getCheckedIds(this.dialogForm.permissionRespNodes);
      function getCheckedIds(arr) {
        if (arr.length > 0) {
          arr.map((item) => {
            if (item.checked) {
              checkedIds.push(item.id);
            } else if (item.children) {
              getCheckedIds(item.children);
            }
          });
        }
      }
      setTimeout(() => {
        if (checkedIds.length > 0) {
          this.$refs.menuPermisionTree.setCheckedKeys(checkedIds);
        }
      }, 100);
    },

    async getAllMenuTree() {
      let res = await getPermissionTreeAll();
      this.$set(this.dialogForm, "permissionRespNodes", res.data);
    },

    async getAllRoleTree() {
      const { id } = this.userInfo;
      let res = await getUserOwnRolesV1(id);
      const { allRole } = res.data;
      this.allRole = allRole;
    },

    roleParentTreeCheck(node, list) {
      if (list.checkedKeys.length == 2) {
        //单选实现
        this.$refs.roleParentTree.setCheckedKeys([node.id]);
      }
    },

    // checkNode(node) {
    //   if (!node.checked) {
    //     // this.check(node);
    //     // debugger;
    //     this.$refs.menuPermisionTree.setChecked(node.id, true);
    //     // node.checked = true;
    //     if (node.parent) {
    //       this.checkNode(node.parent);
    //     }
    //   }
    // },
    // handleCheckPermissonChange(data, checked) {
    //   // 检查子节点
    //   if (data.children) {
    //     data.children.forEach((child) => {
    //       this.checkNode(child);
    //     });
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  margin-bottom: 16px;
  .divider {
    width: 8px;
    border-left: 4px solid #409eff;
    margin-right: 8px;
  }
  .label {
    font-weight: bold;
  }
}
.dialog-content {
  padding: 0 32px;
  display: flex;
  .basic-info {
    flex: 1;
    margin-right: 48px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
