<template>
  <!-- 基本信息组件 -->
  <BasicInfo v-if="showBasicInfo" @back="handleBackToMain" />
  
  <!-- 我的主页 -->
  <view v-else class="my-page">
    <!-- 顶部渐变背景区域 -->
    <view class="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <text class="header-title">eTMF</text>
    </view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 用户信息卡片 -->
      <view class="user-card">
        <view class="user-info">
          <image 
            class="avatar" 
            :src="userInfo.avatar" 
            mode="aspectFill"
            @error="handleAvatarError"
          />
          <view class="user-details">
            <text class="nickname">{{ displayNickname }}</text>
            <text class="phone">{{ displayPhone }}</text>
          </view>
        </view>
        <view class="vip-badge" @click="handleVipClick">
          <text class="vip-text">普通会员</text>
          <text class="arrow">›</text>
        </view>
      </view>
      
      <!-- 我的任务 -->
      <view class="task-section">
        <view class="section-header">
          <text class="section-title">我的任务</text>
          <text class="arrow">›</text>
        </view>
        <view class="task-grid">
          <view class="task-item" @click="handleTaskClick('pending')">
            <view class="task-icon-wrapper">
              <image class="task-icon" src="/static/pages/my/task-pending.png" mode="aspectFit" />
              <view v-if="taskCounts.pending > 0" class="task-badge">{{ taskCounts.pending }}</view>
            </view>
            <text class="task-label">待传递</text>
          </view>
          <view class="task-item" @click="handleTaskClick('delivered')">
            <view class="task-icon-wrapper">
              <image class="task-icon" src="/static/pages/my/task-delivered.png" mode="aspectFit" />
            </view>
            <text class="task-label">已传递</text>
          </view>
          <view class="task-item" @click="handleTaskClick('reviewing')">
            <view class="task-icon-wrapper">
              <image class="task-icon" src="/static/pages/my/task-reviewing.png" mode="aspectFit" />
              <view v-if="taskCounts.reviewing > 0" class="task-badge">{{ taskCounts.reviewing }}</view>
            </view>
            <text class="task-label">待审核</text>
          </view>
          <view class="task-item" @click="handleTaskClick('approved')">
            <view class="task-icon-wrapper">
              <image class="task-icon" src="/static/pages/my/task-approved.png" mode="aspectFit" />
            </view>
            <text class="task-label">已审核</text>
          </view>
        </view>
      </view>
      
      <!-- 功能列表 -->
      <view class="menu-list">
        <view class="menu-item" @click="handleProtocol">
          <view class="menu-left">
            <image class="menu-icon" src="/static/pages/my/icon-protocol.png" mode="aspectFit" />
            <text class="menu-label">用户协议</text>
          </view>
          <text class="arrow">›</text>
        </view>
        
        <view class="menu-item">
          <view class="menu-left">
            <image class="menu-icon" src="/static/pages/my/icon-language.png" mode="aspectFit" />
            <text class="menu-label">语言切换</text>
          </view>
          <view class="language-switcher" @click="handleLanguageChange">
            <text class="language-text" :class="{ active: locale === 'zh-CN' }">中</text>
            <text class="language-separator">|</text>
            <text class="language-text" :class="{ active: locale === 'en-US' }">EN</text>
          </view>
        </view>
        
        <view class="menu-item" @click="handleAbout">
          <view class="menu-left">
            <image class="menu-icon" src="/static/pages/my/icon-about.png" mode="aspectFit" />
            <text class="menu-label">关于我们</text>
          </view>
          <text class="arrow">›</text>
        </view>
      </view>
      
      <!-- 退出登录按钮 -->
      <view class="logout-section">
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </view>
    </view>
    
    <!-- 底部导航栏 -->
    <TabBar current-tab="mine" />
  </view>
</template>

<script setup>
import BasicInfo from './info/index.vue'
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/store/index'
import { useLocaleStore } from '@/store/locale'
import { getUserInfo as getUserInfoAPI, logout as logoutAPI } from '@/apis/auth'
import TabBar from '@/components/TabBar/index.vue'

const { t, locale } = useI18n()
const userStore = useUserStore()
const localeStore = useLocaleStore()

// 控制显示哪个组件
const showBasicInfo = ref(false)

// 状态栏高度
const statusBarHeight = ref(0)

// 用户信息
const userInfo = ref({
  avatar: '/static/default-avatar.svg',
  nickname: '',
  phoneNumber: ''
})

// 任务数量
const taskCounts = ref({
  pending: 6,
  delivered: 0,
  reviewing: 8,
  approved: 0
})

// 显示的昵称
const displayNickname = computed(() => {
  return userInfo.value.nickname || '未设置昵称'
})

// 加密手机号
const encryptPhone = (phone) => {
  if (!phone) return ''
  // 如果手机号长度为11位，则加密中间4位
  if (phone.length === 11) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  // 如果手机号长度不是11位，则加密中间部分
  if (phone.length > 6) {
    const start = phone.substring(0, 3)
    const end = phone.substring(phone.length - 4)
    return `${start}****${end}`
  }
  return phone
}

// 显示的手机号（加密）
const displayPhone = computed(() => {
  return encryptPhone(userInfo.value.phoneNumber)
})

onMounted(() => {
  // 获取系统信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  
  // 获取用户信息
  fetchUserInfo()
})

// 头像加载失败处理
const handleAvatarError = () => {
  userInfo.value.avatar = '/static/default-avatar.svg'
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfoAPI()
    
    if (response && response.data) {
      userInfo.value = {
        avatar: response.data.avatar || '/static/default-avatar.svg',
        nickname: response.data.nickname || '',
        phoneNumber: response.data.phoneNumber || ''
      }
      
      userStore.setUserInfo(response.data)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    
    const storedUserInfo = userStore.userInfo
    if (storedUserInfo) {
      userInfo.value = {
        avatar: storedUserInfo.avatar || '/static/default-avatar.svg',
        nickname: storedUserInfo.nickname || '',
        phoneNumber: storedUserInfo.phoneNumber || ''
      }
    }
  }
}

// 从基本信息返回主页
const handleBackToMain = () => {
  showBasicInfo.value = false
}

// VIP点击
const handleVipClick = () => {
  uni.showToast({
    title: '会员功能',
    icon: 'none'
  })
}

// 任务点击
const handleTaskClick = (type) => {
  uni.showToast({
    title: `${type}任务`,
    icon: 'none'
  })
}

// 协议说明
const handleProtocol = () => {
  uni.navigateTo({
    url: '/pages/my/aggreement/index'
  })
}

// 语言切换
const handleLanguageChange = () => {
  localeStore.toggleLocale()
  
  setTimeout(() => {
    uni.showToast({
      title: '语言切换成功',
      icon: 'success',
      duration: 1500
    })
  }, 100)
}

// 关于我们
const handleAbout = () => {
  uni.showToast({
    title: '关于我们',
    icon: 'none'
  })
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '退出中...',
            mask: true
          })
          
          await logoutAPI()
          userStore.logout()
          
          uni.hideLoading()
          
          uni.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 1500
          })
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }, 1500)
          
        } catch (error) {
          uni.hideLoading()
          console.error('退出登录失败:', error)
          
          userStore.logout()
          
          uni.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 1500
          })
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.my-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  
  // 顶部渐变背景
  .header-bg {
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    height: 200rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #ffffff;
      letter-spacing: 4rpx;
    }
  }
  
  // 页面内容
  .page-content {
    padding: 0 24rpx;
    margin-top: -80rpx;
    
    // 用户信息卡片
    .user-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      margin-bottom: 24rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      
      .user-info {
        display: flex;
        align-items: center;
        flex: 1;
        
        .avatar {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          margin-right: 24rpx;
          border: 4rpx solid #f0f0f0;
        }
        
        .user-details {
          display: flex;
          flex-direction: column;
          gap: 8rpx;
          
          .nickname {
            font-size: 32rpx;
            font-weight: 600;
            color: #333333;
          }
          
          .phone {
            font-size: 26rpx;
            color: #999999;
          }
        }
      }
      
      .vip-badge {
        background: linear-gradient(135deg, #666666 0%, #555555 100%);
        border-radius: 30rpx;
        padding: 12rpx 24rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;
        
        .vip-text {
          font-size: 24rpx;
          color: #ffffff;
          font-weight: 500;
        }
        
        .arrow {
          font-size: 32rpx;
          color: #ffffff;
          font-weight: 300;
        }
      }
    }
    
    // 我的任务
    .task-section {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      margin-bottom: 24rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      
      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 32rpx;
        
        .section-title {
          font-size: 30rpx;
          font-weight: 600;
          color: #333333;
        }
        
        .arrow {
          font-size: 40rpx;
          color: #cccccc;
          font-weight: 300;
        }
      }
      
      .task-grid {
        display: flex;
        justify-content: space-between;
        
        .task-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 16rpx;
          flex: 1;
          
          .task-icon-wrapper {
            position: relative;
            width: 88rpx;
            height: 88rpx;
            
            .task-icon {
              width: 88rpx;
              height: 88rpx;
            }
            
            .task-badge {
              position: absolute;
              top: -8rpx;
              right: -8rpx;
              background: #ff4444;
              color: #ffffff;
              font-size: 20rpx;
              font-weight: 600;
              min-width: 32rpx;
              height: 32rpx;
              border-radius: 16rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 0 8rpx;
              border: 3rpx solid #ffffff;
            }
          }
          
          .task-label {
            font-size: 24rpx;
            color: #666666;
          }
        }
      }
    }
    
    // 功能列表
    .menu-list {
      background: #ffffff;
      border-radius: 16rpx;
      overflow: hidden;
      margin-bottom: 24rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      
      .menu-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 32rpx 24rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:active {
          background-color: #f8f8f8;
        }
        
        .menu-left {
          display: flex;
          align-items: center;
          
          .menu-icon {
            width: 40rpx;
            height: 40rpx;
            margin-right: 24rpx;
          }
          
          .menu-label {
            font-size: 28rpx;
            color: #333333;
          }
        }
        
        .arrow {
          font-size: 40rpx;
          color: #cccccc;
          font-weight: 300;
        }
        
        .language-switcher {
          display: flex;
          align-items: center;
          background: rgba(30, 201, 201, 0.08);
          backdrop-filter: blur(10rpx);
          border-radius: 30rpx;
          padding: 8rpx 20rpx;
          cursor: pointer;
          transition: all 0.3s;
          gap: 8rpx;
          
          &:active {
            transform: scale(0.95);
            background: rgba(30, 201, 201, 0.15);
          }
          
          .language-text {
            font-size: 24rpx;
            color: #999;
            font-weight: 500;
            transition: all 0.3s;
            
            &.active {
              color: #1ec9c9;
              font-weight: 700;
            }
          }
          
          .language-separator {
            font-size: 24rpx;
            color: #ccc;
            font-weight: 300;
          }
        }
      }
    }
    
    // 退出登录
    .logout-section {
      padding: 32rpx 0 60rpx;
      
      .logout-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background: #ffffff;
        border-radius: 16rpx;
        border: none;
        font-size: 28rpx;
        color: #1ec9c9;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        
        &:active {
          opacity: 0.8;
        }
        
        &::after {
          border: none;
        }
      }
    }
  }
}
</style>
