<template>
  <div class="user-profile">
    <a-card title="个人中心" :bordered="false">
      <a-row :gutter="24">
        <!-- 左侧个人信息 -->
        <a-col :span="8">
          <a-card title="个人信息" size="small">
            <div class="profile-info">
              <div class="avatar-section">
                <a-avatar :size="80" :src="userInfo.avatar">
                  <template #icon><UserOutlined /></template>
                </a-avatar>
                <a-button type="link" @click="showAvatarModal = true">
                  更换头像
                </a-button>
              </div>
              
              <a-descriptions :column="1" bordered size="small">
                <a-descriptions-item label="用户名">
                  {{ userInfo.username }}
                </a-descriptions-item>
                <a-descriptions-item label="真实姓名">
                  {{ userInfo.real_name }}
                </a-descriptions-item>
                <a-descriptions-item label="邮箱">
                  {{ userInfo.email }}
                </a-descriptions-item>
                <a-descriptions-item label="手机号">
                  {{ userInfo.phone }}
                </a-descriptions-item>
                <a-descriptions-item label="角色">
                  <a-tag color="blue">{{ getRoleName(userInfo.role_id) }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="状态">
                  <a-tag :color="userInfo.status === 'active' ? 'green' : 'red'">
                    {{ userInfo.status === 'active' ? '正常' : '禁用' }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="最后登录">
                  {{ formatDate(userInfo.last_login) }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </a-card>
        </a-col>
        
        <!-- 右侧操作区域 -->
        <a-col :span="16">
          <a-tabs v-model:activeKey="activeTab">
            <a-tab-pane key="edit" tab="编辑资料">
              <a-form
                :model="editForm"
                :rules="rules"
                layout="vertical"
                @finish="handleUpdateProfile"
              >
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="真实姓名" name="real_name">
                      <a-input v-model:value="editForm.real_name" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="邮箱" name="email">
                      <a-input v-model:value="editForm.email" />
                    </a-form-item>
                  </a-col>
                </a-row>
                
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="手机号" name="phone">
                      <a-input v-model:value="editForm.phone" />
                    </a-form-item>
                  </a-col>
                </a-row>
                
                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="updating">
                    更新资料
                  </a-button>
                  <a-button style="margin-left: 8px" @click="resetEditForm">
                    重置
                  </a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
            
            <a-tab-pane key="password" tab="修改密码">
              <a-form
                :model="passwordForm"
                :rules="passwordRules"
                layout="vertical"
                @finish="handleChangePassword"
              >
                <a-form-item label="当前密码" name="currentPassword">
                  <a-input-password v-model:value="passwordForm.currentPassword" />
                </a-form-item>
                
                <a-form-item label="新密码" name="newPassword">
                  <a-input-password v-model:value="passwordForm.newPassword" />
                </a-form-item>
                
                <a-form-item label="确认新密码" name="confirmPassword">
                  <a-input-password v-model:value="passwordForm.confirmPassword" />
                </a-form-item>
                
                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="changingPassword">
                    修改密码
                  </a-button>
                  <a-button style="margin-left: 8px" @click="resetPasswordForm">
                    重置
                  </a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
          </a-tabs>
        </a-col>
      </a-row>
    </a-card>
    
    <!-- 头像上传模态框 -->
    <a-modal
      v-model:open="showAvatarModal"
      title="更换头像"
      @ok="handleAvatarUpload"
      @cancel="showAvatarModal = false"
    >
      <a-upload
        v-model:file-list="avatarFileList"
        :before-upload="beforeAvatarUpload"
        list-type="picture-card"
        :max-count="1"
      >
        <div v-if="avatarFileList.length < 1">
          <PlusOutlined />
          <div style="margin-top: 8px">上传头像</div>
        </div>
      </a-upload>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UserOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { userAPI } from '@/utils/api'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 响应式数据
const activeTab = ref('edit')
const updating = ref(false)
const changingPassword = ref(false)
const showAvatarModal = ref(false)
const avatarFileList = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo || {})

// 编辑表单
const editForm = reactive({
  real_name: '',
  email: '',
  phone: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  real_name: [
    { required: true, message: '请输入真实姓名' },
    { min: 2, max: 50, message: '姓名长度在2-50个字符' }
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入有效的邮箱地址' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, message: '密码长度至少6位' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (rule, value) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      }
    }
  ]
}

// 方法
const getRoleName = (roleId) => {
  const roleMap = {
    1: '管理员',
    2: '代理人',
    3: '客户',
    4: '审核员'
  }
  return roleMap[roleId] || '未知'
}

const formatDate = (date) => {
  if (!date) return '从未登录'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const resetEditForm = () => {
  editForm.real_name = userInfo.value.real_name || ''
  editForm.email = userInfo.value.email || ''
  editForm.phone = userInfo.value.phone || ''
}

const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const handleUpdateProfile = async () => {
  try {
    updating.value = true
    await userAPI.updateProfile(editForm)
    
    // 更新本地用户信息
    await userStore.fetchUserInfo()
    
    message.success('个人资料更新成功')
  } catch (error) {
    console.error('更新个人资料失败:', error)
    message.error(error.response?.data?.message || '更新失败')
  } finally {
    updating.value = false
  }
}

const handleChangePassword = async () => {
  try {
    changingPassword.value = true
    await userAPI.changePassword(passwordForm)
    
    message.success('密码修改成功')
    resetPasswordForm()
  } catch (error) {
    console.error('修改密码失败:', error)
    message.error(error.response?.data?.message || '修改密码失败')
  } finally {
    changingPassword.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB')
    return false
  }
  
  return false // 阻止自动上传
}

const handleAvatarUpload = async () => {
  if (avatarFileList.value.length === 0) {
    message.error('请选择头像文件')
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('avatar', avatarFileList.value[0].originFileObj)
    
    await userAPI.uploadAvatar(formData)
    await userStore.fetchUserInfo()
    
    message.success('头像更新成功')
    showAvatarModal.value = false
    avatarFileList.value = []
  } catch (error) {
    console.error('头像上传失败:', error)
    message.error(error.response?.data?.message || '头像上传失败')
  }
}

// 初始化
onMounted(async () => {
  try {
    // 获取最新的用户信息
    await userStore.fetchUserInfo()
    resetEditForm()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败，仍然使用本地存储的用户信息
    resetEditForm()
  }
})
</script>

<style scoped>
.user-profile {
  padding: 24px;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 24px;
}

.avatar-section .ant-btn {
  display: block;
  margin: 8px auto 0;
}
</style>