<script setup>
import { ref, onMounted } from 'vue'
import AppHeader from '@/components/AppHeader.vue'
import { showFailToast } from 'vant'
import request from '@/utils/request'

// 响应式数据
const smCount = ref(0)
const rate = ref('')
const tzAmountTodayTotal = ref(null)
const tzAmountTotal = ref(null)
const list = ref([])
const total = ref(0)
const allTotal = ref(null)
const pageSize = ref(10)
const pageNum = ref(1)
const loading = ref(false)
const finished = ref(false)
const emptyTipsShow = ref(false)
const oneC = ref(0)
const twoC = ref(0)
const thirC = ref(0)
const teamTotalIncome = ref(0)
const todayIncome = ref(0)
const commissionAmount = ref(0)
const totalInvestment = ref(0)
const userData = ref({})
const listContent = ref(null)

// 获取用户信息
const getUserInfo = async () => {
  const res = await request.get("/system/user/")
  if (res.smCount) {
    smCount.value = res.smCount
    userData.value = res
  }
}
let level = ref(1)
const changeLevel = (level1) => {
  level.value = level1
  resetList()
  getTeam()
}
// 获取团队信息
const getTeam = async () => {
  try {
    loading.value = true
    const data = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      type: level.value
    }
    const res = await request.get('/ops/teamRanking/achievement', data)
    if (res.code === 200) {
      list.value = [...list.value, ...res.data.rows]
      total.value = res.data.total
      allTotal.value = res.data.allTotal
      tzAmountTodayTotal.value = res.data.tzAmountTodayTotal
      tzAmountTotal.value = res.data.tzAmountTotal
      rate.value = res.data.rate
      oneC.value = res.data.firstChildTotal
      twoC.value = res.data.secondChildTotal
      thirC.value = res.data.thirdChildTotal
      teamTotalIncome.value = res.data.teamTotalIncome || 0
      todayIncome.value = res.data.todayIncome || 0
      commissionAmount.value = res.data.commissionAmount || 0
      totalInvestment.value = res.data.totalInvestment || 0

      if (list.value.length >= total.value) {
        finished.value = true
      } else {
        pageNum.value++
      }
    } else {
      showFailToast(res.msg || '加载失败')
      finished.value = true
    }
  } catch (error) {
    console.error('获取团队信息失败:', error)
    showFailToast(error.msg || '加载失败,请重试')
  } finally {
    loading.value = false
  }
}

// 重置列表状态
const resetList = () => {
  list.value = []
  pageNum.value = 1
  finished.value = false
  loading.value = false
  total.value = 0
  emptyTipsShow.value = false
}

// 添加滚动处理函数
const handleScroll = () => {
  if (loading.value || finished.value) return
  
  const scrollEl = listContent.value
  if (!scrollEl) return
  
  const { scrollTop, scrollHeight, clientHeight } = scrollEl
  // 当滚动到距离底部20px时触发加载
  if (scrollHeight - scrollTop - clientHeight < 20) {
    getTeam()
  }
}

// 初始化
onMounted(() => {
  getUserInfo()
  getTeam()
})
</script>

<template>
  <AppHeader title="我的团队"/>
  <div class="container">
    <div class="income-header">
      世界银行团队({{ allTotal }}人)
    </div>
    <div class="income-panel">
      <div class="user-info">Hi,{{ userData?.nickName?.substring(0, 1) }}** <span>用户所属职级</span>
      </div>
      <div class="income-content">
        <div class="income-row">
          <div class="income-item">
            <div class="label">累计团队收益<span>(元)</span></div>
            <div class="value">{{ teamTotalIncome.toFixed(2) }}</div>
          </div>
          <div class="income-item">
            <div class="label">今日收益<span>(元)</span></div>
            <div class="value">{{ todayIncome.toFixed(2) }}</div>
          </div>
          <div class="income-item">
            <div class="label">佣金<span>(元)</span></div>
            <div class="value">{{ commissionAmount.toFixed(2) }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="stats-panel">
      <div class="stats-row">
        <div class="stats-item">
          <div class="label">总注册会员</div>
          <div class="value">{{ allTotal }}<span>人</span></div>
        </div>
        <div class="stats-item">
          <div class="label">总参与会员</div>
          <div class="value">{{ allTotal }}<span>人</span></div>
        </div>
        <div class="stats-item">
          <div class="label">总投资金额<span>(元)</span></div>
          <div class="value">{{ totalInvestment.toFixed(2) }}</div>
        </div>
      </div>

      <div class="team-level">
        <div class="level-header">
          <div @click="changeLevel(1)" :class="['level-tab', level === 1 ? 'active' : '']">一级团队</div>
          <div @click="changeLevel(2)" :class="['level-tab', level === 2 ? 'active' : '']">二级团队</div>
        </div>
        <div class="level-content">
          <div class="level-info">
            <div>{{ level === 1 ? '一级人数' : '二级人数' }}: <span class="number">{{ level === 1 ? oneC : twoC
                }}</span><span>人</span></div>
            <div>收益金额<span>(元)</span>: <span class="number">{{ teamTotalIncome.toFixed(2) }}</span></div>
          </div>
        </div>
      </div>

      <div class="account-list">
        <div class="list-header">
          <div class="col">下级账户</div>
          <div class="col">姓名</div>
          <div class="col">投资金额</div>
          <div class="col">注册时间</div>
        </div>
        <div class="list-content" ref="listContent" @scroll="handleScroll">
          <div class="list-item" v-for="(item, index) in list" :key="index">
            <div class="col">{{ item.userPhone }}</div>
            <div class="col">{{ item.userName }}</div>
            <div class="col">{{ item.tzAmount?.toFixed(2) || '0.00' }}</div>
            <div class="col">{{ item.createTime.split(' ')[0] }}</div>
          </div>
          <div v-if="loading" class="loading-text">加载中...</div>
          <div v-if="finished" class="finished-text">没有更多了</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  margin-top: 54px;
  width: 100%;
  min-height: calc(100vh - 52px);
  background: url('@/static/common/commonbg.png') no-repeat;
  background-size: 100% 100%;
  padding: 10px;

  .income-header {
    font-weight: 500;
    font-size: 20px;
    color: #000000;
    line-height: 22px;
  }

  .income-panel {
    background: #fff;
    border-radius: 12px;
    margin-top: 15px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 15px;

    .user-info {
      display: flex;
      align-items: center;

      span {
        background: url('@/static/my/level.png') no-repeat;
        background-size: 100% 100%;
        display: inline-block;
        width: 89px;
        margin-left: 10px;
        height: 16px;
        text-align: center;
        font-weight: 400;
        font-size: 10px;
        color: #000000;
        line-height: 20px;
      }
    }

    .income-content {
      margin-top: 15px;

      .income-row {
        display: flex;
      }

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

        .label {
          font-weight: 400;
          font-size: 13px;
          color: #4D4D4D;
          line-height: 18px;

          span {
            font-size: 9px;
          }
        }

        .value {
          margin-top: 17px;
          font-family: Arial;
          font-weight: bold;
          font-size: 19px;
          color: #000000;
          line-height: 20px;
        }
      }
    }
  }
}

.stats-panel {
  background: #fff;
  border-radius: 12px;
  margin-top: 15px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    padding: 15px 0 5px;
    border-bottom: 1px dashed #f5f5f5;

    .stats-item {
      text-align: center;

      .label {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;

        span {
          font-size: 9px;
        }
      }

      .value {
        font-size: 18px;
        font-weight: 600;
        color: #333;

        span {
          font-size: 9px;
        }
      }
    }
  }

  .team-level {
    background: url('@/static/my/teambg.png') no-repeat;
    background-size: 100% 100%;
    padding-bottom: 40px;

    .level-header {
      display: flex;
      justify-content: center;

      .level-tab {
        width: 135px;
        height: 25px;
        margin: 24px 0 0;
        text-align: center;
        font-weight: 400;
        font-size: 13px;
        color: #FFFFFF;
        line-height: 25px;
        border: 1px solid #000000;
      }

      .active {
        background: #000000;
        color: #fff;
      }

    }

    .level-content {
      margin-top: 10px;

      .level-info {
        display: flex;
        justify-content: space-around;
        font-weight: 400;
        font-size: 13px;
        color: #FFF4E3;
        line-height: 18px;

        span {
          font-size: 9px;
        }

        .number {
          font-size: 16px;
        }

        >div {
          text-align: center;
        }
      }
    }
  }

  .account-list {
    .list-header {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      padding: 12px 15px;
      font-size: 14px;
      border-top: 1px dashed #eee;
      border-bottom: 1px dashed #eee;
      font-weight: 400;
      font-size: 12px;
      color: #B47E01;
      line-height: 14px;
    }

    .list-content {
      max-height: 30vh;
      overflow: auto;
      -webkit-overflow-scrolling: touch;
      
      .list-item {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        padding: 12px 15px;
        font-weight: 400;
        font-size: 9px;
        color: #1B1B1B;
        line-height: 12px;
        border-bottom: 1px dashed #f5f5f5;

        &:last-child {
          border-bottom: none;
        }
      }

      .loading-text,
      .finished-text {
        text-align: center;
        padding: 10px 0;
        color: #999;
        font-size: 12px;
      }
    }

    .col {
      text-align: center;
    }
  }
}
</style>