<template>
  <page-box title="编辑个人资料">
    <el-form ref="profileForm" :model="form" label-width="100px" style="max-width:500px">
      <el-form-item label="头像">
        <div class="avatar-upload">
          <el-avatar :size="80" :src="form.portrait || ''"></el-avatar>
          <el-upload
            class="avatar-uploader"
            action="/api/user-service/common/upload"
            :data="{ space: 'avatar' }"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <el-button size="small" type="primary" plain icon="el-icon-upload2">更换头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickName" placeholder="请输入昵称" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input :value="form.phone" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="备用邮箱">
        <el-input v-model="form.backupEmail" placeholder="请输入备用邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitProfile" :loading="submitting">保存</el-button>
      </el-form-item>
    </el-form>
  </page-box>
</template>

<script>
import PageBox from '@/components/pageBox.vue'
import userApi from '@/api/user'
import msgUtil from '@/utils/msgUtil'

export default {
  name: 'editProfile',
  components: { PageBox },
  data() {
    return {
      pageCode: 'y360',
      form: {
        nickName: '',
        portrait: '',
        phone: '',
        email: '',
        backupEmail: ''
      },
      submitting: false,
      uploadHeaders: {}
    }
  },
  created() {
    this.loadUserInfo()
    this.uploadHeaders['token'] = localStorage.getItem('_token')
  },
  methods: {
    async loadUserInfo() {
      const res = await userApi.getCurrentUser()
      if (res.code === 1 && res.data) {
        const user = res.data.user || res.data
        this.form.nickName = user.nickName || ''
        this.form.portrait = user.portrait || ''
        this.form.phone = user.phone || ''
        this.form.email = user.email || ''
        this.form.backupEmail = user.backupEmail || ''
      }
    },
    handleAvatarSuccess(res) {
      if (res && res.code === 1) {
        this.form.portrait = res.data
        msgUtil.notifySuccess('头像上传成功')
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) msgUtil.notifyError('只能上传图片文件')
      if (!isLt2M) msgUtil.notifyError('图片大小不能超过 2MB')
      return isImage && isLt2M
    },
    async submitProfile() {
      if (!this.form.nickName) {
        msgUtil.notifyError('昵称不能为空')
        return
      }
      // 邮箱格式校验
      if (this.form.email && !this.form.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
        msgUtil.notifyError('邮箱格式不正确')
        return
      }
      if (this.form.backupEmail && !this.form.backupEmail.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
        msgUtil.notifyError('备用邮箱格式不正确')
        return
      }
      this.submitting = true
      try {
        const res = await userApi.editProfile({
          nickName: this.form.nickName,
          portrait: this.form.portrait,
          email: this.form.email,
          backupEmail: this.form.backupEmail
        })
        if (res.code === 1) {
          msgUtil.notifySuccess('保存成功')
          // 刷新 store 中的用户信息
          const currentRes = await userApi.getCurrentUser()
          if (currentRes.code === 1 && currentRes.data) {
            this.$store.dispatch('user/setLoginUser', currentRes.data.user || {})
            this.$store.dispatch('user/setCurrentCustomer', currentRes.data.customer || {})
          }
          this.loadUserInfo()
        } else {
          msgUtil.notifyError(res.msg || '保存失败')
        }
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}
</style>
