<template>
  <view class="bill-page">
    <!-- 顶部积分信息 -->
    <view class="points-header">
      <view class="points-item">
        <text class="points-label">当前可用积分</text>
        <text class="points-value">{{ totalPoints }}</text>
      </view>
      <view class="points-item">
        <text class="points-label">本月获得积分</text>
        <text class="points-value">{{ earnedPoints }}</text>
      </view>
      <view class="points-item">
        <text class="points-label">本月即将到期积分</text>
        <text class="points-value">{{ expirePoints }}</text>
      </view>
    </view>

    <view class="container">
      <!-- 标签切换 -->
      <u-tabs
          :list="tabs"
          :current="opType"
          @change="handleTabChange"
          lineWidth="60"
          lineColor="#20CAC2"
          :activeStyle="{
            color: '#303133',
            fontWeight: 'bold',
            transform: 'scale(1.05)'
        }"
          :inactiveStyle="{
            color: '#606266',
            transform: 'scale(1)'
        }"
          itemStyle="padding:0 85rpx; height: 72rpx;font-size:28rpx"
          class="tabs-container"
      ></u-tabs>

      <!-- 积分记录列表 -->
      <view class="records-container">
        <u-list @scrolltolower="loadMore" ref="list" style="height:calc(75vh - 60rpx)">
          <u-list-item v-for="(item, index) in filteredRecords" :key="index" class="record-item">
            <view class="record-info">
              <text class="record-description">{{ item.activityName }}</text>
              <text class="record-date">{{ item.createTime }}</text>
            </view>
            <text class="record-amount" :class="{ income: item.opType == 2, expense: item.opType == 1 }">
              {{ item.opType == 1 ? '+' : '-' }}{{ item.points }}
            </text>
          </u-list-item>
          <!-- 空数据状态 -->
          <u-empty
            v-if="filteredRecords.length === 0 && !loading"
            text="暂无积分记录"
            mode="list"
          ></u-empty>
          <!-- 加载中状态 -->
          <view v-if="loading && filteredRecords.length === 0" class="loading-container">
            <u-loading-icon text="加载中..."></u-loading-icon>
          </view>
          <!-- 加载更多 -->
          <u-loadmore
            v-if="filteredRecords.length > 0"
            :status="loading ? 'loading' : (hasMore ? 'more' : 'nomore')"
            loading-text="加载中..."
            nomore-text="没有更多记录了"
            @loadmore="loadMore"
          ></u-loadmore>
        </u-list>
      </view>
    </view>
  </view>
</template>

<script>
import {mapState} from "vuex";
import { getPointDetails } from '@/api/points';
import {queryBind, useBind, uuidLogin,pointDraw} from "@/api/index";
import webView from '@/utils/uni.webview.1.5.6.js';
export default {
  name: "billPage",
  data() {
    return {
      // 标签数据
      tabs: [
        { key: '', name: '明细' },
        { key: '1', name: '收入' },
        { key: '2', name: '支出' }
      ],
      // 当前选中的标签
      activeTab: '',
      // 积分记录数据
      pointRecords: [],
      // 分页数据
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      currentUser:'',
      currentPlatform:'',
      nowPlatform:'gyy-aB4cD6eF8gH0iJ2kL4',
      uuId:'',
    }
  },
  computed: {
    ...mapState({
      myPoint: state => state.points.myPoint
    }),
    totalPoints() {
      return this.myPoint && this.myPoint.totalPoints || 0;
    },
    earnedPoints() {
      return this.myPoint && this.myPoint.earnedPoints || 0;
    },
    expirePoints() {
      return this.myPoint && this.myPoint.expirePoints || 0;
    },
    opType() {
      return this.tabs.findIndex(item => item.key === this.activeTab)
    },
    // 积分记录（直接使用原始数据，因为已经通过接口参数过滤）
    filteredRecords() {
      return this.pointRecords
    }
  },
  onLoad(options) {
    // #ifdef H5
    window.addEventListener('popstate', this.__h5BackRefresh);
    // #endif
    if(options.currentPlatform && options.currentUser){
      this.currentPlatform = options.currentPlatform;
      this.currentUser = options.currentUser;
      this.verificationAccount();
    }else{
      this.fetchPointDetails()
    }
  },
  onUnload() {
    // #ifdef H5
    window.removeEventListener('popstate', this.__h5BackRefresh);
    // #endif
  },
  mounted() {
    // 初始获取数据
    //this.fetchPointDetails()
  },
  methods: {
    // 切换标签
    handleTabChange(data) {
      this.activeTab = data.key
      // 重置分页数据
      this.pageNum = 1
      this.hasMore = true
      // 清空数据
      this.pointRecords = []
      // 重新获取数据
      this.fetchPointDetails();
    },
    // 加载更多数据
    loadMore() {
      if (this.loading || !this.hasMore) return
      this.pageNum++
      this.fetchPointDetails(true)
    },
    // 获取积分明细数据
    async fetchPointDetails(isLoadMore = false) {
      this.loading = true
      try {
        const res = await getPointDetails({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          opType: this.activeTab
        })
        const {data} = res;
        if (data.code === 200) {
          if (isLoadMore) {
            // 加载更多数据
            this.pointRecords = [...this.pointRecords, ...data.data.records]
          } else {
            // 初始加载数据
            this.pointRecords = data.data.records
          }
          // 判断是否还有更多数据
          this.hasMore = this.pointRecords.length < data.data.total
        }
      } catch (error) {
        console.error('获取积分明细失败:', error)
      } finally {
        this.loading = false
      }
    },
    // H5 返回强制刷新
    __h5BackRefresh() {
      console.log('返回强制刷新---广誉源')
      if(this.currentPlatform && this.currentUser && uni.getStorageSync('access-token')){
        this.bindAccount();//若没有登录。登录后获取绑定信息
      }
    },
    verificationAccount(){
      // jzg-7kP9xL2mN5vQ8zR1jW  ,晋掌柜
      // gyy-aB4cD6eF8gH0iJ2kL4  ,广誉源
      // bdsh-X9yZ1wV3uT5sR7qP9o  ,本地生活
      // https://test.baoxianzhanggui.com/lxl-api/usercenter
      // 用户ID    userId
      // 平台ID   clientId
      // 租户ID （晋掌柜用）   tenantId
      // source 自己的平台
      // target 要绑的平台
      var _this = this;
      queryBind({
        userId : _this.currentUser,
        clientId :_this.currentPlatform
      }).then(res => {
        if(res.data.code == 200){
          _this.uuId = res.data.data.filter(item=> item.clientId === 'gyy-aB4cD6eF8gH0iJ2kL4')[0]?.uuid;
          if(!uni.getStorageSync('access-token')){
            if(_this.uuId){
              _this.uuLogin();
            }else{
              if (!_this.$utils.checkLogin({ type: 'navigate-webview' })) return;
            }
          }else{
            _this.fetchPointDetails()
          }
        }else{
          if (!_this.$utils.checkLogin({ type: 'navigate-webview' })) return;
        }
      })
    },
    bindAccount(){
      var _this = this;
      useBind({
        sourceUserId: _this.currentUser,       //a项目的id
        sourceClientId: _this.currentPlatform, //a项目的来源平台
        targetUserId: uni.getStorageSync('userId'),            //b项目的id
        targetClientId: _this.nowPlatform,     //b项目的来源平台
        userPhone:uni.getStorageSync('wx_phone')
      }).then(async res => {
        await pointDraw();
        await _this.fetchPointDetails()
      })
    },
    uuLogin(){
      // 广誉源uuid登录
      var _this = this;
      uuidLogin({
        uuid: _this.uuId,
      }).then(res => {
        if(res.data.code == 200){
          uni.setStorageSync('wx_copenid', res.data.data.copenid || '')
          uni.setStorageSync('access-token', res.data.data.token)
          uni.setStorageSync('wx_phone', res.data.data.cphone)
          uni.setStorageSync('userId', res.data.data.id)
          _this.fetchPointDetails()
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
.bill-page{
  width: 750rpx;
  height: 100vh;
  background-image: url("@/static/points/pointBg.png");
  background-size: 100%;
  background-repeat: no-repeat;
  background-color: #ffe5ca;
  padding-top: 62rpx;
}

.points-header{
  display: flex;
  justify-content: space-around;
  margin-bottom: 42rpx;
  .points-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    .points-label{
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #FFFFFF;
      margin-bottom: 24rpx;
    }
    .points-value{
      font-weight: 500;
      font-size: 40rpx;
      color: #FFFFFF;
      line-height: 32rpx;
    }
  }
}
.container{
  width: 686rpx;
  height: 83vh;
  background: #FFFFFF;
  border-radius: 20rpx;
  margin: 0 auto;
  padding: 10rpx 0;
  .tabs-container{
    display: flex;
    overflow: hidden;
    margin-bottom: 32rpx;
  }
}

.records-container{
  .record-item{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 32rpx;
    flex-direction: row;
    .record-info{
      .record-description{
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
        line-height: 28rpx;
        display: block;
        margin-bottom: 12rpx;
      }
      .record-date{
        font-family: PingFang SC, PingFang SC;
        font-size: 24rpx;
        color: #999999;
        line-height: 28rpx;
      }
    }
    .record-amount{
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      line-height: 28rpx;
      &.income{
        color: #34c7c2;
      }
      &.expense{
        color: #f53e54;
      }
    }
  }
  .u-empty{
    margin-top: 20vh!important;
  }

  /* 加载中容器 */
  .loading-container {
    margin-top: 20vh!important;
  }
}
</style>
