<template>
  <div class="user-edit part-box part-box-pad part-box-border">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item prop="loginName" label="用户名：">
        <el-input
          style="width:282px;"
          v-model.trim="modalForm.loginName"
          placeholder="请输入用户名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="name" label="姓名：">
        <el-input
          style="width:282px;"
          v-model.trim="modalForm.name"
          placeholder="请输入姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号：">
        <el-input
          style="width:282px;"
          v-model.trim="modalForm.phone"
          placeholder="请输入手机号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="roleCode" label="角色：">
        <el-select
          style="width:282px;"
          v-model="modalForm.roleCode"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.roleCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="courseId"
        label="科目："
        v-if="modalForm.roleCode === 'QUESTION_TEACHER'"
      >
        <el-select
          style="width:282px;"
          v-model="modalForm.courseId"
          placeholder="请选择科目"
          multiple
        >
          <el-option
            v-for="item in courses"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          style="width:88px;"
          type="primary"
          :disabled="isSubmit"
          @click="submit('modalFormComp')"
          >保存</el-button
        >
        <el-button style="width:88px;" @click="goback">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateUser, userDetail, roleList, courseList } from "../api";
import { logout } from "../../login/api";
import { phone } from "@/plugins/formRules";

export default {
  name: "user-edit",
  data() {
    const courseIdValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择科目"));
      } else {
        callback();
      }
    };

    return {
      modalForm: {
        id: "",
        name: "",
        phone: "",
        loginName: "",
        roleCode: "",
        courseId: ""
      },
      rules: {
        phone,
        name: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change"
          }
        ],
        loginName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change"
          }
        ],
        roleCode: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change"
          }
        ],
        courseId: [
          {
            required: true,
            validator: courseIdValidator,
            trigger: "change"
          }
        ]
      },
      user: {},
      roles: [],
      courses: [],
      isSubmit: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      const data = await roleList();
      this.roles = data.records;
      const userRes = await userDetail(this.$route.params.userId);
      if (!userRes.account) {
        this.$message.error("当前用户不存在!");
        return;
      }
      this.user = userRes.account;
      this.modalForm = this.$objAssign(this.modalForm, this.user);
      this.modalForm.courseId = this.user.courseId
        ? this.modalForm.courseId.split(",")
        : [];
      this.getCourseList();
    },
    async getCourseList() {
      const data = await courseList();
      this.courses = data.records.map(course => {
        return {
          id: course.id,
          name: `${course.courseName}(${course.courseCode})`
        };
      });
    },
    async submit(name) {
      const valid = await this.$refs[name].validate().catch(() => {});
      if (!valid) return;

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

      const datas = { ...this.modalForm };
      if (datas.roleCode !== "QUESTION_TEACHER") delete datas.courseId;
      const data = await updateUser(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("修改成功！");

      // 自己把自己的角色改了之后要重新登录，重新获取权限
      if (
        this.user.roleCode !== this.modalForm.roleCode &&
        this.$ls.get("user").id === this.user.id
      ) {
        await logout(this.$ls.get("user", { id: "" }).id);
        this.$ls.clear();
        this.$router.push({ name: "Login" });
        this.$message.info("您的权限已经变更，请重新登录系统！");
      }
    }
  }
};
</script>
