<!--
 * @Author: Billy
 * @Date: 2021-08-17 14:23:18
 * @LastEditors: Billy
 * @LastEditTime: 2022-01-04 17:26:55
 * @Description: 用户添加
-->

<!-- 用户添加成功后，会触发user-add-success事件，参数为新用户 -->

<template>
  <div class="container">
    <el-dialog
      title="添加用户"
      :visible="isVisible"
      :before-close="beforeClose"
      width="30%"
    >
      <el-form
        :model="newUser"
        :rules="newUserRules"
        ref="newUserForm"
        label-width="70px"
        class="newUserForm"
      >
        <el-form-item label="部门名" prop="name">
          <el-input :value="org.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="newUser.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="newUser.password"
            autocomplete="new-password"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onQuitClick">退 出</el-button>
        <el-button type="primary" @click="onConfirmClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import SystemApi from "../../../api/Rbac/System.js";
import UserBiz from "../../../biz/Rbac/User.js";

export default {
  props: {
    isVisible: {
      type: Boolean,
      default: false,
    },
    org: {
      type: Object,
    },
  },
  data() {
    return {
      newUser: {
        name: "",
        password: "",
      },
      newUserRules: {
        name: [{ required: true, message: "请填写用户名", trigger: "none" }],
        password: [
          { required: true, message: "请填写密码", trigger: "none" },
          {
            min: 5,
            max: 18,
            message: "长度在 5 到 18 个字符",
            trigger: "none",
          },
        ],
      },
    };
  },
  methods: {
    onQuitClick() {
      this.$emit("update:isVisible", false);
    },

    onConfirmClick() {
      this.$refs["newUserForm"].validate((valid) => {
        if (valid) {
          UserBiz.add({
            name: this.newUser.name,
            password: this.newUser.password,
            orgId: this.org.id < 0 ? null : this.org.id,
          })
            .then((userId) => {
              this.$message({
                message: "添加用户成功",
                type: "success",
              });
              this.$emit("user-add-success", userId);
              console.log("userId :>> ", userId);
            })
            .catch((err) => {
              this.$message({
                message: err.message,
                type: "error",
              });
            });
        } else {
          return false;
        }
      });
    },

    // “添加用户”对话框的❌被点击时
    beforeClose(done) {
      this.$emit("update:isVisible", false);
      done();
    },
  },
};
</script>

