<template>
  <el-form ref="form" :model="form" label-width="100px">
    <el-form-item label="用户名称">
      <el-input
        v-model="form.nickName"
        size="small"
        placeholder="请输入用户名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="性别" style="width: 100%">
      <el-select v-model="form.sex" size="small" placeholder="请选择性别">
        <el-option label="男" value="0"></el-option>
        <el-option label="女" value="1"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('staff.sjhm')">
      <el-input v-model="form.phone" size="small"></el-input>
    </el-form-item>
    <el-form-item label="用户邮箱">
      <el-input v-model="form.email" size="small"></el-input>
    </el-form-item>
  </el-form>
  <el-button type="primary" size="small" @click="save">保存</el-button>
  <el-button type="primary" size="small" plain>返回</el-button>
</template>

<script>
import { updateInfo, userInfo } from '@/api/user';
export default {
  data() {
    return {
      form: {
        nickName: '',
        sex: '',
        phone: '',
        email: '',
      },
      rawData: '',
      diffData: '',
    };
  },
  created() {
    this.showData();
  },
  methods: {
    async showData() {
      const { data } = await userInfo();
      this.form = data;
      this.rawData = { ...data };
    },

    diffFormData() {
      for (const k in this.rawData) {
        if (this.rawData[k] !== this.form[k]) {
          if (!this.diffData) {
            this.diffData = {};
          }
          this.diffData[k] = this.form[k];
        }
      }
    },
    save() {
      this.diffFormData();
      if (!this.diffData) {
        this.$message.error('未修改任何数据，无需提交');
      } else {
        this.$refs['form'].validate(async valid => {
          if (valid) {
            const { msg } = await updateInfo(this.diffData);
            this.$notify({
              title: msg,
              type: 'success',
            });
            this.showData();
          } else {
            return false;
          }
        });
      }
    },
  },
};
</script>

<style scoped></style>
