<template>
  <el-dialog
    title="编辑个人信息"
    :visible.sync="visible"
    width="600px"
    @close="resetForm"
  >
    <el-form
      ref="form"
      :model="formData"
      label-width="100px"
      label-position="right"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <image-upload v-model="formData.avatar"
        >
        </image-upload>
      </el-form-item>

      <!-- 昵称 -->
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="formData.nickName"
          placeholder="请输入用户昵称"
          clearable
        />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="sex">
        <el-select
          v-model="formData.sex"
          placeholder="请选择性别"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 个性签名 -->
      <el-form-item label="个性签名" prop="declaration">
        <el-input
          v-model="formData.declaration"
          type="textarea"
          :rows="3"
          placeholder="请输入个性签名"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateBasicUserProfile } from '@/api/system/user'

export default {
  name: 'EditUserInfo',
  props: {
    userData: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  dicts: ['sys_user_sex'],
  data() {
    return {
      formData: {
        avatar: '',
        nickName: '',
        sex: '',
        phonenumber: '',
        email: '',
        declaration: ''
      },
    }
  },
  watch: {
    userData: {
      immediate: true,
      handler(val) {
        if (val) {
          this.formData = { ...val }
        }
      }
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updateBasicUserProfile(this.formData).then(res => {
            this.$message.success('修改成功')
            this.$emit('update:visible', false)
            this.$emit('success')
          })
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
