<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="roleCode" label="角色：">
        <el-select
          style="width:142px;"
          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>
        <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 } from "../api";

export default {
  name: "user-edit",
  data() {
    return {
      modalForm: {
        userId: "",
        name: "",
        loginName: "",
        roleCode: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change"
          }
        ],
        loginName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change"
          }
        ],
        roleCode: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change"
          }
        ]
      },
      roles: [],
      isSubmit: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      const data = await roleList();
      this.roles = data.records;
      const user = await userDetail(this.$route.params.userId);
      if (!user.account) {
        this.$message.error("当前用户不存在!");
        return;
      }
      this.modalForm = Object.assign({}, this.modalForm, user.account);
    },
    async submit(name) {
      const valid = await this.$refs[name].validate().catch(() => {});
      if (!valid) return;

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

      this.gaback();
    }
  }
};
</script>
