<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model.trim="form.deptName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="上级部门" prop="parentId">
        <el-select v-model="form.parentId" placeholder="请选择上级部门">
          <el-option
            v-for="item in deptData"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="save">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDeptList, doDeptAdd, doDeptEdit } from '@/api/dept';

export default {
  data() {
    return {
      form: {
        deptId: '',
        parentId: '',
        deptName: '',
      },
      rules: {
        deptName: [
          { required: true, trigger: 'blur', message: '请输入部门名称' },
        ],
      },
      clearable: true,
      deptData: [],
      title: '',
      dialogFormVisible: false,
    };
  },
  created() {},
  methods: {
    async getDeptData() {
      const { data } = await getDeptList();
      data.push({ deptId: 0, deptName: '顶级部门' });
      this.deptData = data;
    },
    deptEdit(row) {
      this.getDeptData();
      if (!row) {
        this.title = '添加部门';
      } else {
        this.title = '编辑部门';
        this.form.deptId = row.id;
        this.form.parentId = row.parentId;
        this.form.deptName = row.label;
      }
      this.dialogFormVisible = true;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.form.name = this.form.title;
          if (this.form.deptId) {
            const { msg } = await doDeptEdit(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          } else {
            delete this.form.deptId;
            const { msg } = await doDeptAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style>
.select {
  width: 100%;
}
</style>
