<template>
  <div class="profile-page">
    <div class="profile-container">
      <!-- 左侧个人信息卡片 -->
      <div class="profile-left">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button
                type="primary"
                size="small"
                @click="loadProfile"
                :loading="loading"
              >
                刷新
              </el-button>
            </div>
          </template>

          <div v-loading="loading" element-loading-text="加载中...">
            <div v-if="!profile && !loading" class="error-state">
              <el-empty description="未能加载用户信息">
                <el-button type="primary" @click="loadProfile">重新加载</el-button>
              </el-empty>
            </div>

            <div v-else-if="profile">
              <div class="avatar-section">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
            >
              <el-avatar :size="120" :src="avatarUrl" class="user-avatar">
                {{ profile?.user.nickName?.charAt(0) || 'U' }}
              </el-avatar>
              <div class="avatar-overlay">
                <el-icon :size="24"><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </el-upload>
            <h2 class="user-name">{{ profile?.user.nickName || '未知' }}</h2>
          </div>

          <el-descriptions :column="1" class="user-info">
            <el-descriptions-item label="账号">
              {{ profile?.user.userName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号码">
              {{ profile?.user.phonenumber || '未绑定手机号' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ profile?.user.email || '未绑定邮箱' }}
            </el-descriptions-item>
            <el-descriptions-item label="部门">
              <el-tag type="primary" size="small">
                {{ profile?.user.deptName || '未分配部门' }}
              </el-tag>
              <el-tag v-if="profile?.postGroup" type="success" size="small" class="ml-2">
                {{ profile.postGroup }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="角色">
              {{ profile?.roleGroup || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="上次登录">
                  {{ profile?.user.loginDate || '-' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧设置面板 -->
      <div class="profile-right">
        <el-card class="settings-card">
          <el-tabs v-model="activeTab" class="settings-tabs">
            <el-tab-pane label="基本设置" name="basic">
              <BasicSetting :profile="profile" @update="loadProfile" />
            </el-tab-pane>
            <el-tab-pane label="安全设置" name="security">
              <SecuritySetting :profile="profile" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { UserProfile } from '@/api/profile/types';
import type { UploadRequestOptions } from 'element-plus';

import { userProfile, userUpdateAvatar } from '@/api/profile';
import { useUserStore } from '@/stores';
import { ElMessage } from 'element-plus';
import BasicSetting from './components/BasicSetting.vue';
import SecuritySetting from './components/SecuritySetting.vue';

const userStore = useUserStore();
const profile = ref<UserProfile>();
const loading = ref(false);
const activeTab = ref('basic');

const avatarUrl = computed(() => {
  return profile.value?.user.avatar || '';
});

async function loadProfile() {
  loading.value = true;

  try {
    const resp = await userProfile();

    if (resp instanceof Error) {
      ElMessage.error('加载用户信息失败，请检查网络连接');
      return;
    }

    // 尝试处理不同的响应格式
    let userData = resp;

    // 如果响应包含 data 字段，提取 data
    if ((resp as any).data) {
      userData = (resp as any).data;
    }

    profile.value = userData;

    // 更新store中的用户信息，确保字段名匹配
    if (userData && userData.user) {
      const updatedUserInfo = {
        ...userStore.userInfo, // 保留原有的其他字段
        userId: userData.user.userId,
        username: userData.user.userName, // 注意：userName -> username
        nickName: userData.user.nickName,
        avatar: userData.user.avatar,
        phonenumber: userData.user.phonenumber,
        email: userData.user.email,
        deptId: userData.user.deptId,
        deptName: userData.user.deptName,
        roles: userData.user.roles?.map((r: any) => ({
          roleId: r.roleId,
          roleName: r.roleName,
          roleKey: r.roleKey,
        })),
        tenantId: userData.user.tenantId,
      };

      userStore.setUserInfo(updatedUserInfo);
    } else {
      console.error('[Profile] 响应数据格式错误:', resp);
      ElMessage.error('用户信息数据格式错误，请查看控制台');
    }
  } catch (error) {
    console.error('[Profile] 加载用户信息失败:', error);
    ElMessage.error('加载用户信息失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
}

// 头像上传前检查
function beforeAvatarUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

// 上传头像
async function handleAvatarUpload(options: UploadRequestOptions) {
  const res = await userUpdateAvatar(options.file as File);
  if (res instanceof Error) return;
  ElMessage.success('头像更新成功');
  await loadProfile();
}

onMounted(loadProfile);
</script>

<style scoped lang="scss">
.profile-page {
  padding: 24px;
  min-height: calc(100vh - 64px);
  background: var(--color-bg);
}

.profile-container {
  display: flex;
  gap: 24px;
  max-width: 1400px;
  margin: 0 auto;

  @media (max-width: 1024px) {
    flex-direction: column;
  }
}

.profile-left {
  width: 360px;
  flex-shrink: 0;

  @media (max-width: 1024px) {
    width: 100%;
  }
}

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error-state {
  padding: 40px 0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0;
  margin-bottom: 24px;
  border-bottom: 1px solid var(--color-border);
}

.avatar-uploader {
  position: relative;
  cursor: pointer;

  &:hover .avatar-overlay {
    opacity: 1;
  }
}

.user-avatar {
  background: linear-gradient(135deg, #1d5af3, #858bff);
  font-size: 48px;
  font-weight: 700;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;

  span {
    margin-top: 4px;
    font-size: 12px;
  }
}

.user-name {
  margin-top: 16px;
  font-size: 20px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.user-info {
  padding: 0 16px;
}

.profile-right {
  flex: 1;
  min-width: 0;
}

.settings-card {
  border-radius: 12px;
  min-height: 600px;
}

.settings-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 24px;
  }

  :deep(.el-tabs__item) {
    font-size: 15px;
    font-weight: 500;
  }
}
</style>