<!--
 * @Author: Billy
 * @Date: 2021-08-31 15:26:21
 * @LastEditors: Billy
 * @LastEditTime: 2022-01-04 17:22:09
 * @Description: 请输入
-->
<template>
  <div class="container">
    <el-form ref="form" :model="form" :rules="orgRules" label-width="100px">
      <el-form-item label="上级部门名称">
        <el-input :value="org.name" readonly></el-input>
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button @click="onCancel">{{ btnCancelName }}</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import OrganizationBiz from "../../../biz/Rbac/Organization.js";
export default {
  props: {
    org: { type: Object, required: true }, // 当前的目标上级部门
  },
  data() {
    return {
      form: {
        // id: 0,
        name: "",
      },
      orgRules: {
        name: [{ required: true, message: "请填写部门名称", trigger: "none" }],
      },
      btnCancelName: "取消",
    };
  },
  updated() {},
  methods: {
    onSubmit() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.$confirm(
            `确定把在部门 ${this.org.name} 下新增 ${this.form.name} 子部门?`,
            {
              title: "确认新增",
              showCancelButton: true,
              showConfirmButton: true,
            }
          )
            .then(async () => {
              this.form.name = this.form.name.trim();
              try {
                let newOrg = await OrganizationBiz.add(
                  this.org.id < 0 ? null : this.org.id,
                  this.form.name
                );
                if (newOrg) {
                  this.$message.success(
                    `${this.org.name} 成功增加下级 ${this.form.name}`
                  );
                  this.btnCancelName = "退出";
                  this.$emit("success", this.org, newOrg);
                }
              } catch (e) {
                this.$message.error(e.message);
              }
            })
            .catch((e) => {});
        }
      });
    },

    onCancel() {
      this.$emit("cancel");
    },

    // 供外部调用，更新本组件的一些显示
    updateForm() {
      this.$refs["form"].clearValidate();
      this.btnCancelName = "取消";
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form-item.btns {
  padding-top: 20px;
  margin-bottom: 0;
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: flex-end;
  }
}
</style>