<template>
  <view class="profile-page">
    <image :src="commonEnum.FIRE_BACKGROUND" class="fire-background"></image>

    <!-- 头部用户信息 -->
    <view class="user-header">
      <view class="avatar">
        <image
          v-if="userInfo.avatar"
          :src="userInfo.avatar"
          class="avatar-image"
          mode="aspectFill"
        />
        <text v-else class="avatar-text"
          >{{ userInfo.nickName ? userInfo.nickName.charAt(0) : '昵' }}
        </text>
      </view>
      <view class="user-info">
        <view v-if="isAgent" class="share-btn" @click="goToSharePromotion">
          <image :src="commonEnum.GIFT" class="share-img" mode="aspectFit"></image>
          <text class="share-text">分享推广</text>
        </view>
        <view v-else style="padding: 30rpx"></view>
      </view>
      <view class="user-details">
        <text class="user-name">{{ userInfo.nickName || '昵称' }}</text>

        <view class="settings-icon" @click="goToSettings">
          <image :src="commonEnum.SET" class="settings-img" mode="aspectFit" />
        </view>
      </view>
    </view>

    <!-- 财务摘要 -->
    <view v-if="isAgent" class="financial-summary">
      <image :src="commonEnum.COIN_BACKGROUND" class="coin-background" mode="width"></image>
      <view class="main-amount">
        <text class="amount-number">{{ financialData.balance || '0.00' }}</text>
        <text class="amount-label">可提现(元)</text>
      </view>
      <view class="action-buttons">
        <view class="action-btn income-expense-btn" @click="goToIncomeExpense">
          <text class="btn-text">收支明细 ></text>
        </view>
        <view class="action-btn withdraw-btn" @click="goToWithdraw">
          <text class="btn-text">立即提现 ></text>
        </view>
      </view>
      <view class="financial-stats">
        <view class="stat-item">
          <text class="stat-number">{{ financialData.waitBalance || '0.00' }}</text>
          <text class="stat-label">待入账(元)</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ financialData.withdrawBalance || '0.00' }}</text>
          <text class="stat-label">提现中(元)</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ financialData.withdrawedBalance || '0.00' }}</text>
          <text class="stat-label">已提现(元)</text>
        </view>
      </view>
    </view>

    <!-- 我的用户 -->
    <view v-if="isAgent" class="my-users-section">
      <view class="section-header">
        <text class="section-title">我的用户</text>
        <view class="view-details" @click="goToUserList">
          <text class="details-text">查看详情 ></text>
        </view>
      </view>
      <view class="user-stats">
        <view class="stat-item">
          <text class="stat-number">{{ userStats.userNum || 0 }}</text>
          <text class="stat-label">名下用户(个)</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userStats.deviceNum || 0 }}</text>
          <text class="stat-label">设备数量(个)</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userStats.rentAmount || 0 }}</text>
          <text class="stat-label">租赁金额(元)</text>
        </view>
      </view>
    </view>

    <!-- 其他功能 -->
    <view class="other-functions">
      <view class="section-header">
        <text class="section-title">其他功能</text>
      </view>
      <view class="function-grid">
        <view v-if="!isAgent" class="function-item" @click="goToAgentApply">
          <view class="function-icon">
            <image :src="commonEnum.REQUEST_AGENT" class="function-img" mode="aspectFit"></image>
          </view>
          <text class="function-text">申请代理</text>
        </view>
        <view class="function-item" @click="goToMyOrderList">
          <view class="function-icon">
            <image :src="commonEnum.AGENCY_INTERESTS" class="function-img" mode="aspectFit"></image>
          </view>
          <text class="function-text">我的订单</text>
        </view>
        <view class="function-item" @click="showServiceModal">
          <view class="function-icon">
            <image
              :src="commonEnum.ONLINE_CUSTOMER_SERVICE"
              class="function-img"
              mode="aspectFit"
            ></image>
          </view>
          <text class="function-text">在线客服</text>
        </view>
      </view>
    </view>
    <!-- 客服弹窗组件 -->
    <customer-service-modal :visible="serviceModalVisible" @close="handleCloseModal" />
  </view>
</template>

<script>
import { commonEnum } from '@/enum/commonEnum.js'
import { getUserInfo, getUserFinancialData, getAgentCount } from '@/api/user/user.js'
import { isAgent } from '@/api/agents.js'

export default {
  name: 'ProfilePage',
  data() {
    return {
      serviceModalVisible: false,
      commonEnum,
      userInfo: {
        nickName: '昵称',

        avatar: '',
        userId: '',
      },
      financialData: {
        balance: 0.0,
        waitBalance: 0,
        withdrawBalance: 0,
        withdrawedBalance: 0,
      },
      userStats: {
        userNum: 0,
        deviceNum: 0,
        rentAmount: 0,
      },
      loading: false,
      isAgent: false,
    }
  },
  onLoad() {
    this.fetchUserData()
  },
  onShow() {
    // 页面显示时刷新数据
    this.fetchUserData()
  },
  mounted() {
    // 监听用户信息更新事件
    uni.$on('userInfoUpdated', this.handleUserInfoUpdate)
  },
  beforeUnmount() {
    // 移除事件监听
    uni.$off('userInfoUpdated', this.handleUserInfoUpdate)
  },
  methods: {
    // 获取用户数据
    async fetchUserData() {
      this.loading = true
      try {
        // 并行获取所有数据
        const [userInfoRes, financialRes, statsRes] = await Promise.allSettled([
          this.fetchUserInfo(),
          this.fetchFinancialData(),
          this.fetchUserStats(),
          this.getIsAgent(),
        ])

        // 处理用户信息
        if (userInfoRes.status === 'fulfilled' && userInfoRes.value.code === 200) {
          this.userInfo = {
            ...this.userInfo,
            ...userInfoRes.value.data,
          }
          console.log('用户信息获取成功:', this.userInfo)
          console.log('用户昵称:', this.userInfo.nickName || this.userInfo.nickname)
          console.log('用户头像:', this.userInfo.avatar)
        } else {
          console.log('用户信息获取失败，使用默认值')
        }

        // 处理财务数据
        if (financialRes.status === 'fulfilled' && financialRes.value.code === 200) {
          this.financialData = {
            ...this.financialData,
            ...financialRes.value.data,
          }
          console.log('财务数据获取成功:', this.financialData)
        }

        // 处理代理统计
        if (statsRes.status === 'fulfilled' && statsRes.value.code === 200) {
          this.userStats = {
            ...this.userStats,
            ...statsRes.value.data,
          }
          console.log('代理统计获取成功:', this.userStats)
        }
      } catch (error) {
        console.error('获取用户数据失败:', error)
        uni.showToast({
          title: '数据加载失败',
          icon: 'none',
        })
      } finally {
        this.loading = false
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await getUserInfo()
        return response
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },

    async getIsAgent() {
      try {
        const response = await isAgent()
        this.isAgent = response.data
      } catch (error) {
        console.error('获取是否是代理失败:', error)
      }
    },

    // 获取财务数据
    async fetchFinancialData() {
      try {
        const response = await getUserFinancialData()
        return response
      } catch (error) {
        console.error('获取财务数据失败:', error)
      }
    },

    // 获取代理统计
    async fetchUserStats() {
      try {
        const response = await getAgentCount()
        return response
      } catch (error) {
        console.error('获取代理统计失败:', error)
        // 如果获取失败，使用默认数据
      }
    },

    // 跳转到设置页面，传递用户信息
    goToSettings() {
      console.log('准备跳转到设置页面，当前用户信息:', this.userInfo)

      // 将当前用户信息存储到本地，供设置页面使用
      try {
        const userInfoToStore = {
          nickName: this.userInfo.nickName || this.userInfo.nickname || '昵称',
          avatar: this.userInfo.avatar || '',
          userId: this.userInfo.userId || '',
        }

        uni.setStorageSync('userInfo', userInfoToStore)
        console.log('用户信息已存储到本地:', userInfoToStore)
      } catch (error) {
        console.error('存储用户信息失败:', error)
      }

      // 跳转到设置页面
      uni.navigateTo({
        url: '/pages/set/set',
      })
    },
    goToAgentApply() {
      uni.navigateTo({
        url: '/pages/agents/agents',
      })
    },
    goToMyOrderList() {
      uni.navigateTo({
        url: '/pages/myOrder/myOrder',
      })
    },
    goToIncomeExpense() {
      uni.navigateTo({
        url: '/pages/cashFlow/cashFlow',
      })
    },
    goToWithdraw() {
      uni.navigateTo({
        url: '/pages/requestWithdrawal/requestWithdrawal',
      })
    },

    // 显示弹窗
    showServiceModal() {
      this.serviceModalVisible = true
    },

    // 关闭弹窗
    handleCloseModal() {
      this.serviceModalVisible = false
    },

    async goToUserList() {
      if (this.isAgent) {
        uni.navigateTo({
          url: '/pages/useList/useList',
        })
      } else {
        uni.showToast({
          title: '请先申请代理',
          icon: 'none',
        })
      }
    },

    async goToSharePromotion() {
      if (this.isAgent) {
        uni.navigateTo({
          url: '/pages/agents/requestAgent',
        })
      } else {
        uni.showToast({
          title: '请先申请代理',
          icon: 'none',
        })
      }
    },

    // 处理用户信息更新事件
    handleUserInfoUpdate(updatedUserInfo) {
      // 更新本地用户信息
      this.userInfo = {
        ...this.userInfo,
        ...updatedUserInfo,
      }

      // 更新本地存储
      try {
        uni.setStorageSync('userInfo', this.userInfo)
      } catch (error) {
        console.error('更新本地用户信息失败:', error)
      }

      console.log('用户信息已更新:', this.userInfo)
    },
  },
}
</script>

<style lang="scss" scoped>
.profile-page {
  background: #f3f5f6;

  .fire-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 750rpx;
    height: 592rpx;
    opacity: 1;
    z-index: -1;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 用户头部
.user-header {
  padding: 40rpx 40rpx 40rpx 40rpx;
  margin: 270rpx 20rpx 20rpx 20rpx;
  border-radius: 20rpx;
  position: relative;
  background: #ffffff;

  .avatar {
    position: absolute;
    top: -80rpx; // 头像向上偏移，一半在容器外
    left: 40rpx;
    width: 160rpx;
    height: 160rpx;
    background: #817f7f;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10; // 确保头像在最上层
    overflow: hidden;

    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }

    .avatar-text {
      font-size: 60rpx;
      font-weight: bold;
      color: #ffffff;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    justify-content: flex-end; // 分享按钮靠右对齐
    margin-bottom: 30rpx;

    .share-btn {
      background: linear-gradient(135deg, #fffcfa 0, #ffe0c7 100%);
      padding: 20rpx 30rpx;
      border-radius: 30rpx;
      display: flex;
      align-items: center;

      .share-img {
        width: 32rpx;
        height: 32rpx;
        margin-right: 10rpx;
      }

      .share-text {
        font-size: 24rpx;
        color: #722b03;
      }
    }
  }

  .user-details {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .user-name {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #3d3d3d;
      margin-bottom: 10rpx;
    }

    .user-id {
      font-size: 28rpx;
      color: #817f7f;
    }

    .settings-icon {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      display: flex;
      padding: 10rpx;

      .settings-img {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
}

// 财务摘要
.financial-summary {
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 54rpx;
  color: #fff;
  position: relative;
  top: -70rpx;
  overflow: hidden;
  //border: 1px red solid;

  .coin-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 1;
    z-index: 1;
  }

  .main-amount {
    margin-top: 30rpx;
    margin-bottom: 66rpx;
    position: relative;
    z-index: 2;

    .amount-number {
      display: block;
      font-size: 44rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      height: 60rpx;
    }

    .amount-label {
      font-size: 28rpx;
      opacity: 0.9;
    }
  }

  .action-buttons {
    position: absolute;
    top: 80rpx;
    right: 40rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    z-index: 2;

    .action-btn {
      padding: 10rpx 34rpx;
      border-radius: 30rpx;
      cursor: pointer;
      transition: all 0.3s ease;

      .btn-text {
        font-size: 24rpx;
      }
    }

    .income-expense-btn {
      .btn-text {
        color: #fff;
      }
    }

    .withdraw-btn {
      background: #fff;

      .btn-text {
        color: #f15a04;
      }
    }
  }

  .financial-stats {
    display: flex;
    justify-content: space-between;
    position: relative;
    z-index: 2;

    .stat-item {
      .stat-number {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 5rpx;
      }

      .stat-label {
        font-size: 24rpx;
        opacity: 0.8;
      }
    }
  }
}

// 我的用户
.my-users-section {
  position: relative;
  top: -70rpx;
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 40rpx;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .view-details {
      .details-text {
        font-size: 28rpx;
        color: #9e9e9e;
      }
    }
  }

  .user-stats {
    display: flex;
    justify-content: space-around;

    .stat-item {
      text-align: center;

      .stat-number {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        color: #3d3d3d;
        margin-bottom: 10rpx;
      }

      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

// 其他功能
.other-functions {
  position: relative;
  top: -70rpx;
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 40rpx;

  .section-header {
    margin-bottom: 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .function-grid {
    display: flex;
    justify-content: space-around;

    .function-item {
      text-align: center;
      flex: 1;

      .function-icon {
        width: 80rpx;
        height: 80rpx;
        background: #f5f5f5;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20rpx;

        .function-img {
          width: 50rpx;
          height: 50rpx;
        }
      }

      .function-text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }
}

//view {
//  border: red solid 1px;
//}
</style>
