<template>
  <el-dialog :title="title" @open="handleOpen" :visible.sync="dialogVisible" width="700px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="6em" v-loading="loading">
      <el-row :gutter="12">
        <form-col :span="24" label="归属部门" prop="deptId" v-if="isAdmin">
          <dept-select v-model="form.deptId" check-strictly/>
        </form-col>
        <form-col :span="span" label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" maxlength="30" />
        </form-col>
        <form-col :span="span" label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" size="small" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </form-col>
        <form-col :span="span" label="登录账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入登录账号" maxlength="30" />
        </form-col>
        <form-col :span="span" label="登录密码" prop="password" v-if="form.userId == null">
          <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
        </form-col>
      </el-row>
      <el-row :gutter="12">
        <form-col :span="span" label="所属代理" prop="agentId" v-if="!isAdmin">
          <user-input v-model="form.agentId" :text.sync="form.agentName" :query="userQuery"/>
        </form-col>
        <form-col :span="span" label="分成比例" prop="point" v-if="!isAdmin">
          <el-input v-model="form.point" placeholder="请输入分成比例" type="number">
            <template slot="append">%</template>
          </el-input>
        </form-col>
        <form-col :span="span" label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
        </form-col>
        <form-col :span="span" label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </form-col>
        <form-col :span="span" label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.user_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </form-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, getUser, updateUser } from '@/api/system/user'
import FormCol from '@/components/FormCol/index.vue'
import { RoleKeys, UserType } from '@/utils/enums'
import UserInput from '@/components/Business/User/UserInput.vue'
import BooleanTag from '@/components/BooleanTag/index.vue'

export default {
  name: "UserFormDialog",
  dicts: ['user_status', 'sys_user_sex'],
  components: { FormCol, UserInput, BooleanTag },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 用户ID
    userId: {
      type: [Number, String],
      default: null
    },
    // 用户类型
    userType: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      span: 12,
      // 部门树选项
      deptOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 默认密码
      initPassword: "",
      // 表单校验
      rules: {
        phonenumber: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ],
        deptId: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        email: [
          {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
        ],
      },
      loading: false
    };
  },
  computed: {
    title() {
      return this.form.userId ? "修改用户" : "添加用户";
    },
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    isAdmin() {
      return this.userType == UserType.ADMIN;
    },
    userQuery() {
      return {
        excludeUserId: this.form.userId,
        roleKey: RoleKeys.AGENT,
      }
    }
  },
  created() {
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    handleOpen() {  
      this.getUser();
    },
    /** 获取用户详情 */
    getUser() {
      this.loading = true;
      getUser(this.userId).then(response => {
        if (this.userId) {
          this.form = response.data;
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.$set(this.form, "postIds", response.postIds);
          this.$set(this.form, "roleIds", response.roleIds);
          this.form.password = "";
        } else {
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.reset();
          this.form.password = this.initPassword;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        agentId: null,
        deptId: null,
        userName: null,
        nickName: null,
        password: null,
        phonenumber: null,
        email: null,
        sex: null,
        status: "0",
        remark: null,
        birthday: null,
        resignDate: null,
        postIds: [],
        roleIds: [],
        idCardFront: null,
        idCardBack: null,
        resume: null,
        // vo
        agentName: null,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            this.loading = true;
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.$emit('success');
            }).finally(() => {
              this.loading = false;
            });
          } else {
            this.loading = true;
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.$emit('success');
            }).finally(() => {
              this.loading = false;
            });
          }
        }
      });
    },
    // 设置部门树选项
    setDeptOptions(options) {
      this.deptOptions = options;
    }
  }
};
</script> 