<template>
  <div class="app-container">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form label-width="120px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="dataForm.username" class="input-width" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="用户手机号码" prop="telephone">
        <el-input v-model="dataForm.telephone" class="input-width" minlength="11" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item v-if="!id" label="用户密码" prop="password">
        <el-input v-model="dataForm.password" class="input-width" minlength="6" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader
            v-model="dataForm.deptId"
            class="input-width"
            placeholder="请选择部门"
            :options="depts"
            :props="{ checkStrictly: true,emitPath:false, value:'id', label:'name' }"
            clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="角色" prop="roles">
        <el-select multiple v-model="dataForm.roles" placeholder="请选择角色" class="input-width" clearable>
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <page-footer showConfirm @confirm="onConfirm" @cancel="onCancel" width="800px"></page-footer>
  </div>
</template>

<script>

import {validateNotEmpty, validatePassword, validatePhone, validateUsername} from "@/utils/validate";
import md5 from "js-md5";

export default {
  name: "SystemUserEdit",
  watch: {},

  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 用户id
        username: undefined, // 用户名称
        telephone: undefined, // 手机号
        password: undefined, // 登录密码
        deptId: undefined, // 部门id
        roles: [], //  角色
      },
      dataRules: {
        'username': [{validator: validateUsername, length: 2, required: true, trigger: 'blur'}],
        'telephone': [{validator: validatePhone, errorMessage: "请输入正确的手机号", required: true, trigger: 'blur'}],
        'password': [{validator: validatePassword, length: 6, required: true, trigger: 'blur'}],
        'disabled': [{validator: validateNotEmpty, errorMessage: "是否禁用不能为空", required: true, trigger: 'blur'}],
        'roles': [{validator: validateNotEmpty, errorMessage: "角色不能为空", required: true, trigger: 'change'}]
      },

      roles: undefined, // 角色列表
      depts: undefined, // 部门列表
    }
  },

  mounted() {
    this.initData();
    if (this.id) {
      this.getDetail(this.id);
    }
  },

  methods: {
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      // 加载角色列表
      this.$axios.get("/v1/system/role/list/option").then(data => {
        this.roles = data;
      });
      // 加载部门
      this.$axios.get("/v1/system/dept/list/tree").then((data) => {
        this.depts = JSON.parse(JSON.stringify(data).replace(/"children":\[]/g, "\"no\":0"));
      });
    },

    // 取消
    onCancel() {
      this.$router.back();
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.id) { // 更新
            this.$axios.put("/v1/system/user/update", this.dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("SystemUserUpdate");
              this.onCancel();
            });
          } else { // 添加
            let dataForm = JSON.parse(JSON.stringify(this.dataForm));
            dataForm.password = md5(dataForm.password);
            this.$axios.post("/v1/system/user/add", dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("SystemUserAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(userId) {
      this.$axios.get(`/v1/system/user/query/${userId}`).then(data => {
        data.roles = data.roles.map(item => item.id);
        this.dataForm = data;
      });
    },
  }
}
</script>

<style scoped lang="scss">
.app-container {
  .input-width {
    width: 400px;
  }
}
</style>
