<template>
  <el-dialog
    class="modify-user"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="70px"
    >
      <el-form-item prop="realName" label="姓名：">
        <el-input
          v-model.trim="modalForm.realName"
          placeholder="请输入姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="mobileNumber" label="手机号：">
        <el-input
          v-model.trim="modalForm.mobileNumber"
          placeholder="请输入手机号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码：">
        <el-input
          v-model.trim="modalForm.password"
          placeholder="请输入密码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="roleId" label="角色：">
        <el-select
          style="width: 100%"
          v-model="modalForm.roleId"
          placeholder="请选择角色"
          @change="roleChagne"
        >
          <el-option
            v-for="item in roles"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="curRole.type === 'ASSIGN'"
        label="学院："
        prop="orgId"
      >
        <el-select
          style="width: 100%"
          v-model="modalForm.orgId"
          placeholder="请选择学院"
          filterable
        >
          <el-option
            v-for="item in orgs"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="enable" required>
        <el-radio-group v-model="modalForm.enable">
          <el-radio
            v-for="(val, key) in ABLE_TYPE"
            :key="key"
            :label="key * 1"
            >{{ val }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUser } from "../api";
import { password } from "@/plugins/formRules";
import { ABLE_TYPE } from "@/constants/enumerate";

const initModalForm = {
  id: "",
  loginName: "",
  realName: "",
  password: "",
  mobileNumber: "",
  roleId: "",
  orgId: null,
  enable: 1,
};

export default {
  name: "modify-user",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    roles: {
      type: Array,
      default() {
        return [];
      },
    },
    orgs: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "用户";
    },
  },
  data() {
    const mobileNumberValidator = (rule, value, callback) => {
      if (/^1\d{10}$/.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入合适的手机号码"));
      }
    };

    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      ABLE_TYPE,
      rules: {
        mobileNumber: [
          {
            required: true,
            validator: mobileNumberValidator,
            trigger: "change",
          },
        ],
        realName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
          {
            max: 50,
            message: "姓名不能超过50",
            trigger: "change",
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择学院",
            trigger: "change",
          },
        ],
        password,
      },
      user: {},
      curRole: {},
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.modalForm.enable = val.enable ? 1 : 0;
        this.roleChagne(this.modalForm.roleId);
      } else {
        this.modalForm = { ...initModalForm };
        const defRole = this.roles.find((item) => item.type === "IMPLEMENT");
        this.modalForm.roleId = defRole ? defRole.id : null;

        this.$nextTick(() => {
          this.$refs.modalFormComp.clearValidate();
        });
      }
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    roleChagne(val) {
      this.curRole = this.roles.find((item) => item.id === val);
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;

      const datas = { ...this.modalForm };
      datas.enable = !!datas.enable;
      datas.loginName = datas.mobileNumber;
      const data = await updateUser(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("修改成功！");
      this.cancel();
      this.$emit("modified");
    },
  },
};
</script>
