<template>
  <el-dialog
    :title="textMap[propsData.status]"
    :visible.sync="propsData.visible"
    @opened="initData"
    width="600px"
    top="10%"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="formData"
      label-width="90px"
      style="width: 400px; margin-left:30px;"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account" clearable />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" clearable />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" clearable />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" clearable />
      </el-form-item>
      <el-form-item label="选择组织" prop="orgId">
        <el-cascader
          v-model="formData.orgId"
          :options="orgGroupList"
          :props="defaultProps"
          :show-all-levels="false"
          @change="handleOrgChange"
          clearable
        />
      </el-form-item>

      <el-form-item label="选择职位" prop="positionId">
        <el-select v-model="formData.positionId" class="filter-item" clearable>
          <el-option
            v-for="position in positionList"
            :key="position.id"
            :label="position.name"
            :value="position.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :loading="btnloading"
        @click="propsData.status === 'create' ? createData() : updateData()"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import waves from "@/directive/waves"; // 水波纹指令
import { positionCategory } from "@/constants/index";
/* 组织 */
import { dynamicTree } from "@/api/auth/position";
import { createUser, fetchPositionList, updateUser } from "@/api/auth/user";
export default {
  name: "addOrEditOrgDialog", //添加 或 编辑组织信息
  directives: {
    waves
  },
  props: ["propsData"],
  data() {
    return {
      positionCategory,
      btnloading: false,
      defaultProps: {
        label: "name",
        value: "id",
        checkStrictly: true,
        emitPath: false
      },
      formData: {
        orgId: null,
        name: null,
        account: null,
        gender: null,
        phone:null,
        email:null,
        positionId: null
      },
      textMap: {
        create: "新建用户",
        update: "编辑用户"
      },
      orgGroupList: [],
      positionList: [],
      rules: {
        accountVal: [{ required: true, message: "请填写账号", trigger: "blur" }],
        name: [{ required: true, message: "请填写职位名称", trigger: "blur" }],
        orgId: [{ required: true, message: "请选择组织", trigger: "change" }],
        positionId: [
          { required: true, message: "请选择职位", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    async initData() {
      //对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });

      await dynamicTree().then(response => {
        this.orgGroupList = response.data;
      });
      if (this.propsData.status === "update") {
        const data = { ...this.propsData.orgData };
        this.formData = data;
      }
    },
    handleOrgChange(value) {
      // 选择组织后，自动选择所属组织的第一个职位
      if (value && value.length > 0) {
        this.fetchPositionList(value);
      }
    },
    fetchPositionList(orgId) {
      const query = { orgId };
      fetchPositionList(query).then(response => {
        this.positionList = response.data.rows;
      });
    },
    createData() {
      //保存组织
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.btnloading = true;
          createUser(this.formData)
            .then(() => {
              this.$notify({
                title: "成功",
                message: "新建成功",
                type: "success",
                duration: 3000
              });
              //重新加载 -- 调用父节点
              this.$emit("refreshTable");
            })
            .finally(() => {
              this.btnloading = false;
            });
        }
      });
    },
    updateData() {
      //提交更新
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          updateUser(this.formData)
            .then(() => {
              this.$notify({
                title: "成功",
                message: "编辑成功",
                type: "success",
                duration: 3000
              });
              //重新加载 -- 调用父节点
              this.$emit("refreshTable");
            })
            .finally(() => {
              this.btnloading = false;
            });
        }
      });
    },
    handleClose() {
      this.$refs["dataForm"].resetFields();
      this.propsData.visible = false;
      this.formData = {
        orgId: null,
        name: null,
        category: null,
        sortCode: null
      };
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-cascader,
.el-select {
  width: 100%;
}
</style>
