<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">{{ t('my.title') }}</text>
    </view>
    
    <!-- 页面内容 - 可滚动 -->
    <scroll-view 
      scroll-y 
      class="page-scroll"
      :style="{ paddingTop: (statusBarHeight + 60) + 'px' }"
    >
      <view class="page-content">
      <!-- 用户信息卡片 -->
      <view class="user-card" @click="handleUserCardClick">
        <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>
      
      <!-- 我的任务 -->
      <view class="task-section">
        <view class="section-header" @click="handleTaskSectionClick">
          <text class="section-title">{{ t('my.myTasks') }}</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/toSubmit.svg" mode="aspectFit" />
              <view v-if="taskCounts.pending > 0" class="task-badge">{{ taskCounts.pending }}</view>
            </view>
            <text class="task-label">{{ t('my.toSubmit') }}</text>
          </view>
          <view class="task-item" @click="handleTaskClick('reviewing')">
            <view class="task-icon-wrapper">
              <image class="task-icon" src="/static/pages/my/toAudit.svg" mode="aspectFit" />
              <view v-if="taskCounts.reviewing > 0" class="task-badge">{{ taskCounts.reviewing }}</view>
            </view>
            <text class="task-label">{{ t('my.toAudit') }}</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">{{ t('my.userAgreement') }}</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">{{ t('my.languageSwitch') }}</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">{{ t('my.aboutUs') }}</text>
          </view>
          <text class="arrow">›</text>
        </view> -->
      </view>
      
      <!-- 退出登录按钮 -->
      <view class="logout-section">
        <button class="logout-btn" @click="handleLogout">{{ t('my.logout') }}</button>
      </view>
    </view>
    </scroll-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, getTaskCount } 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: 0,
  reviewing: 0
})

// 显示的昵称
const displayNickname = computed(() => {
  return userInfo.value.nickname || t('my.defaultNickname')
})

// 加密手机号
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()
  
  // 获取任务数量
  fetchTaskCount()
})

// 头像加载失败处理
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 fetchTaskCount = async () => {
  try {
    const response = await getTaskCount()
    
    if (response && response.code === 200 && response.data) {
      taskCounts.value = {
        pending: response.data.toSubmit || 0,
        reviewing: response.data.toAudit || 0
      }
    }
  } catch (error) {
    console.error('获取任务数量失败:', error)
    // 失败时保持默认值 0
  }
}

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

// 点击用户卡片
const handleUserCardClick = () => {
  uni.navigateTo({
    url: '/pages/my/info/index'
  })
}

// 任务点击
const handleTaskClick = (type) => {
  let status = null
  
  if (type === 'pending') {
    status = 0 // 待递交
  } else if (type === 'reviewing') {
    status = 1 // 待审核
  }
  
  uni.navigateTo({
    url: `/pages/my/taskDocuments/index?status=${status}`
  })
}

// 点击我的任务标题区域
const handleTaskSectionClick = () => {
  // 跳转到任务列表，不传status参数显示所有任务
  uni.navigateTo({
    url: '/pages/my/taskDocuments/index'
  })
}

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

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

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

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: t('my.tip'),
    content: t('my.logoutConfirm'),
    confirmText: t('my.confirm'),
    cancelText: t('my.cancel'),
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: t('my.loggingOut'),
            mask: true
          })
          
          await logoutAPI()
          userStore.logout()
          
          uni.hideLoading()
          
          uni.showToast({
            title: t('my.logoutSuccess'),
            icon: 'success',
            duration: 1500
          })
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }, 1500)
          
        } catch (error) {
          uni.hideLoading()
          console.error('退出登录失败:', error)
          
          userStore.logout()
          
          uni.showToast({
            title: t('my.logoutSuccess'),
            icon: 'success',
            duration: 1500
          })
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.my-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
  
  // 顶部渐变背景 - 固定
  .header-bg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
    z-index: 100;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #ffffff;
      letter-spacing: 4rpx;
      padding: 16rpx 0 24rpx;
    }
  }
  
  // 可滚动区域
  .page-scroll {
    width: 100%;
    height: 100%;
    
    // 页面内容
    .page-content {
      padding: 0 24rpx 24rpx;
      padding-bottom: calc(124rpx + env(safe-area-inset-bottom));
    
      // 用户信息卡片
      .user-card {
        background: #ffffff;
        border-radius: 16rpx;
        padding: 32rpx 24rpx;
        margin-bottom: 24rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        
        &:active {
          background-color: #f8f8f8;
        }
      
      .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;
          }
        }
      }
      }
      
      // 我的任务
      .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>
