<template>
  <div class="profile-page">
    <h2>个人中心</h2>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="page-card profile-card">
          <div class="avatar-section">
            <el-avatar :size="100" :src="authStore.user?.avatarUrl || undefined">
              {{ authStore.user?.nickname?.[0] || authStore.user?.username?.[0] }}
            </el-avatar>
            <el-upload
              action=""
              :auto-upload="false"
              :show-file-list="false"
              @change="handleAvatarChange"
            >
              <el-button type="primary" link>更换头像</el-button>
            </el-upload>
          </div>
          
          <div class="info-section">
            <div class="info-item">
              <span class="label">用户名</span>
              <span class="value">{{ authStore.user?.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">角色</span>
              <el-tag>{{ getRoleText(authStore.user?.role) }}</el-tag>
            </div>
            <div class="info-item">
              <span class="label">注册时间</span>
              <span class="value">{{ formatDate(authStore.user?.createdAt) }}</span>
            </div>
            <div class="info-item">
              <span class="label">上次登录</span>
              <span class="value">{{ formatDate(authStore.user?.lastLoginAt) }}</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="16">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="info">
            <div class="page-card">
              <el-form :model="profileForm" label-width="100px">
                <el-form-item label="昵称">
                  <el-input v-model="profileForm.nickname" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="profileForm.email" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveProfile" :loading="saving">
                    保存修改
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="修改密码" name="password">
            <div class="page-card">
              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input v-model="passwordForm.oldPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePassword" :loading="changingPassword">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from 'element-plus';
import { useAuthStore } from '@/stores/auth';
import { authApi } from '@/api/auth';
import dayjs from 'dayjs';

const authStore = useAuthStore();
const activeTab = ref('info');
const saving = ref(false);
const changingPassword = ref(false);
const passwordFormRef = ref<FormInstance>();

const profileForm = reactive({
  nickname: '',
  email: '',
});

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const validateConfirmPassword = (_rule: any, value: string, callback: Function) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const passwordRules: FormRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' },
  ],
};

function getRoleText(role?: string) {
  const texts: Record<string, string> = {
    admin: '管理员',
    editor: '编辑',
    operator: '运营',
  };
  return texts[role || ''] || role;
}

function formatDate(date?: string | null) {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm');
}

function handleAvatarChange(file: UploadFile) {
  // TODO: 上传头像
  ElMessage.info('头像上传功能开发中');
}

async function saveProfile() {
  saving.value = true;
  try {
    const user = await authApi.updateProfile({
      nickname: profileForm.nickname,
      email: profileForm.email,
    });
    authStore.user = user;
    ElMessage.success('保存成功');
  } catch {
    // 错误已处理
  } finally {
    saving.value = false;
  }
}

async function changePassword() {
  if (!passwordFormRef.value) return;
  
  const valid = await passwordFormRef.value.validate().catch(() => false);
  if (!valid) return;
  
  changingPassword.value = true;
  try {
    await authApi.changePassword(passwordForm.oldPassword, passwordForm.newPassword);
    ElMessage.success('密码修改成功');
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
  } catch {
    // 错误已处理
  } finally {
    changingPassword.value = false;
  }
}

onMounted(() => {
  if (authStore.user) {
    profileForm.nickname = authStore.user.nickname || '';
    profileForm.email = authStore.user.email || '';
  }
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

h2 {
  margin: 0 0 20px;
}

.profile-card {
  text-align: center;
  
  .avatar-section {
    padding: 20px 0;
    border-bottom: 1px solid $border-lighter;
    
    .el-avatar {
      margin-bottom: 12px;
    }
  }
  
  .info-section {
    padding: 20px 0;
    
    .info-item {
      display: flex;
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px solid $border-lighter;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: $text-secondary;
      }
      
      .value {
        color: $text-primary;
      }
    }
  }
}
</style>
