<template>
  <div class="user-info-page">
    <el-card class="page-card">
      <template #header>
        <span class="page-title">{{ t('个人信息') }}</span>
      </template>

      <el-form :model="userInfoForm" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item :label="t('头像')">
          <div class="avatar-section">
            <el-avatar :size="80" :src="userInfoForm.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'" />
            <el-button type="primary" @click="showUploadDialog = true">
              {{ t('更换头像') }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item :label="t('用户名')" prop="first_name">
          <el-input v-model="userInfoForm.first_name" :placeholder="t('请输入用户名')" />
        </el-form-item>

        <el-form-item :label="t('电子邮箱')" prop="email">
          <el-input v-model="userInfoForm.email" :placeholder="t('请输入电子邮箱')" disabled />
        </el-form-item>

        <el-form-item :label="t('电话')" prop="phone">
          <el-input v-model="userInfoForm.phone" :placeholder="t('请输入电话号码')" />
        </el-form-item>

        <el-form-item :label="t('注册日期')">
          <el-input v-model="userInfoForm.created_at" disabled />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="updateLoading" @click="handleUpdate">
            {{ t('保存') }}
          </el-button>
          <el-button @click="router.back()">
            {{ t('取消') }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog v-model="showUploadDialog" :title="t('更换头像')" width="400px">
      <div class="upload-content">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleFileChange"
          accept="image/*"
        >
          <el-button type="primary">{{ t('选择图片') }}</el-button>
        </el-upload>
        <div v-if="selectedFile" class="selected-file">
          <span>{{ selectedFile.name }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="showUploadDialog = false">{{ t('取消') }}</el-button>
        <el-button type="primary" :loading="uploadLoading" @click="handleUpload">
          {{ t('确定') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/request/api'
import { useUserStore } from '@/store/user'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const showUploadDialog = ref(false)
const updateLoading = ref(false)
const uploadLoading = ref(false)
const selectedFile = ref(null)

const userInfoForm = reactive({
  avatar: '',
  first_name: '',
  email: '',
  phone: '',
  created_at: ''
})

const rules = {
  first_name: [
    { required: true, message: t('请输入用户名'), trigger: 'blur' },
    { min: 3, max: 20, message: t('用户名长度在3到20个字符'), trigger: 'blur' }
  ],
  email: [
    { required: true, message: t('请输入电子邮箱'), trigger: 'blur' },
    { type: 'email', message: t('请输入正确的邮箱格式'), trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: t('请输入正确的手机号'), trigger: 'blur' }
  ]
}

const handleFileChange = (file) => {
  if (file.raw) {
    selectedFile.value = file.raw
  }
}

const handleUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning(t('请先选择头像'))
    return
  }

  uploadLoading.value = true
  try {
    const formData = new FormData()
    formData.append('avatar', selectedFile.value)

    const res = await updateUserInfo(formData)

    if (res.code === 1) {
      ElMessage.success(t('头像上传成功'))
      userInfoForm.avatar = res.data.avatar || res.data
      userStore.setUserInfo(res.data)
      showUploadDialog.value = false
      selectedFile.value = null
    }
  } catch (error) {
    ElMessage.error(t('头像上传失败'))
  } finally {
    uploadLoading.value = false
  }
}

const handleUpdate = async () => {
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  updateLoading.value = true
  try {
    const res = await updateUserInfo({
      first_name: userInfoForm.first_name,
      phone: userInfoForm.phone
    })

    if (res.code === 1) {
      ElMessage.success(t('保存成功'))
      userStore.setUserInfo(res.data)
    }
  } catch (error) {
    ElMessage.error(t('保存失败'))
  } finally {
    updateLoading.value = false
  }
}

onMounted(async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 1) {
      Object.assign(userInfoForm, res.data)
      userStore.setUserInfo(res.data)
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
})
</script>

<style scoped>
.user-info-page {
  max-width: 800px;
  margin: 0 auto;
}

.page-card {
  border-radius: 12px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-uploader {
  text-align: center;
}

.selected-file {
  margin-top: 10px;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
</style>
