<script>
import SignIn from '../components/sign-in/sign-in.vue'
import TaskList from '../components/task-list/task-list.vue'
import ProductList from '../components/product-list/product-list.vue'
import ImageItem from "@/components/swiper/components/image.vue";
import { mapState, mapActions } from 'vuex';
import { getSignPoint, signPoint, getHomeTask } from '@/api/points'

export default {
  name: 'PointsHome',
  components: {
    ImageItem,
    SignIn,
    TaskList,
    ProductList
  },
  computed: {
    ...mapState({
      myPoint: state => state.points.myPoint
    }),
    // 总积分
    totalPoints() {
      return this.myPoint && this.myPoint.totalPoints || 0;
    },
    // 本月新获取积分
    monthlyPoints() {
      return this.myPoint && this.myPoint.earnedPoints || 0;
    }
  },
  data() {
    return {
      // 滚动距离
      scrollTop: 0,
      // 签到数据
      signData: [],
      // 任务数据
      taskData: [],
      // 加载状态
      loading: {
        points: false,
        sign: false,
        task: false
      }
    }
  },
  onLoad(options) {

  },
  onReady() {

  },
  onShow(){
    // 初始化数据
    this.initData();
    // 绑定滚动事件
    this.bindScrollEvent();
  },
  onUnload() {
    // 解绑滚动事件
    this.unbindScrollEvent();
  },
  methods: {
    ...mapActions([
      'getPointsInfo'
    ]),
    // 跳转到积分规则界面
    goPointRule(){
      uni.navigateTo({
        url:'/points/home/pointRule'
      })
    },
    // 初始化数据
    async initData() {
      try {
        // 并行获取数据，提高加载速度
        await Promise.all([
          this.fetchPointsInfo(),
          this.fetchSignList(),
          this.fetchTaskList()
        ]);
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    },
    // 获取积分信息
    async fetchPointsInfo() {
      this.loading.points = true;
      try {
        await this.getPointsInfo();
      } catch (error) {
        console.error('获取积分信息失败:', error);
      } finally {
        this.loading.points = false;
      }
    },
    // 获取签到数据
    async fetchSignList() {
      this.loading.sign = true;
      try {
        const res = await getSignPoint({
          cityCode: uni.getStorageSync('selectCitycode')
        });
        if (res.data.code === 200) {
          this.signData = res.data.data;
        }
      } catch (error) {
        console.error('获取签到数据失败:', error);
      } finally {
        this.loading.sign = false;
      }
    },
    // 获取任务数据
    async fetchTaskList() {
      this.loading.task = true;
      try {
        const res = await getHomeTask({
          cityCode: uni.getStorageSync('selectCitycode'),
        });
        if (res.data.code === 200) {
          this.taskData = res.data.data;
        }
      } catch (error) {
        console.error('获取任务数据失败:', error);
      } finally {
        this.loading.task = false;
      }
    },
    // 绑定滚动事件
    bindScrollEvent() {
      if (process.env.UNI_PLATFORM === 'h5') {
        // 在H5端添加滚动事件监听器
        const homeEl = this.$el;
        if (homeEl && typeof homeEl.addEventListener === 'function') {
          homeEl.addEventListener('scroll', this.handleScroll);
        }
      } else {
        // 在非H5端监听页面滚动事件
        uni.onPageScroll(this.handlePageScroll);
      }
    },
    // 解绑滚动事件
    unbindScrollEvent() {
      if (process.env.UNI_PLATFORM === 'h5') {
        const homeEl = this.$el;
        if (homeEl && typeof homeEl.removeEventListener === 'function') {
          homeEl.removeEventListener('scroll', this.handleScroll);
        }
      } else {
        // 移除页面滚动事件监听
        uni.offPageScroll(this.handlePageScroll);
      }
    },
    // 处理滚动事件（H5端）
    handleScroll() {
      const homeEl = this.$el;
      if (homeEl) {
        const scrollTop = homeEl.scrollTop;
        // 更新滚动距离
        this.updateScrollTop(scrollTop);
        // 检查是否触底
        this.checkReachBottom(homeEl, scrollTop);
      }
    },
    // 处理页面滚动事件（非H5端）
    handlePageScroll(e) {
      const scrollTop = e.scrollTop;
      // 更新滚动距离
      this.updateScrollTop(scrollTop);
      // 检查是否触底
      const homeEl = this.$el;
      if (homeEl) {
        this.checkReachBottom(homeEl, scrollTop);
      }
    },
    // 更新滚动距离
    updateScrollTop(scrollTop) {
      this.scrollTop = scrollTop;
    },
    // 检查是否触底
    checkReachBottom(element, scrollTop) {
      const scrollHeight = element.scrollHeight;
      const clientHeight = element.clientHeight;
      // 当滚动到距离底部50px以内时，触发加载更多
      if (scrollTop + clientHeight >= scrollHeight - 50) {
        this.reachBottom();
      }
    },
    // 触底加载更多
    reachBottom() {
      if (this.$refs.productRef) {
        this.$refs.productRef.loadMore();
      }
    },
    // 处理签到
    handleSign(index) {
      var _this = this;
      signPoint({
        cityCode: uni.getStorageSync('selectCitycode'),
      }).then(res => {
        if (res.data.code === 200) {
          _this.signData[index].status = 1;
          _this.$refs.uNotify.show({
            top: 1,
            type: 'success',
            message: '今日签到成功,继续加油哦！！！',
            duration: 1000 * 3,
            fontSize: 14,
            safeAreaInsetTop:true
          })
          _this.fetchPointsInfo();
        }
      }).catch(error => {
        console.error('签到失败:', error);
      });
    },
    // 跳转到积分明细页面
    goBillPage() {
      uni.navigateTo({
        url: '/points/pointInfo/billPage'
      });
    },
    // 跳转到订单列表页面
    orderGo() {
      uni.navigateTo({
        url: '/points/order/orderList'
      });
    },
  }
}
</script>

<template>
  <view class="points-home" ref="homeRef">
    <u-notify ref="uNotify" message=""></u-notify>
    <view class="points-task">
      <!-- 积分头部 -->
      <view class="points-header" @click="goBillPage">
        <view class="points-total">
          <text class="total">{{ totalPoints }}</text>
          <ImageItem src="/static/points/goBill.png" class="billImage"/>
        </view>
        <view class="monthly-points">本月新获取{{ monthlyPoints }}积分</view>
      </view>
      <!-- 规则按钮 -->
      <view class="rule-btn" @click="goPointRule">规则</view>
      <!-- 签到组件 -->
      <SignIn @sign="handleSign" :signData="signData" :loading="loading.sign"/>
      <!-- 任务组件 -->
      <TaskList :taskData="taskData" :loading="loading.task"/>
    </view>
    <!-- 商品列表组件 -->
    <ProductList ref="productRef" :scrollTop="scrollTop" />
    <!-- 积分订单跳转 -->
    <view @click="orderGo" class="orderIcons">
      <ImageItem src="/static/points/orderGo.png"/>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.points-home{
  height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  .orderIcons{
    width: 80rpx;
    height: 80rpx;
    position: fixed;
    right: 6rpx;
    bottom: calc(8vh + 10rpx);
    z-index: 99;
  }
}
.points-task {
  background-image: url("@/static/points/homeBg.png");
  background-size: 100%;
  width: 750rpx;
  height: 890rpx;
  position: relative;
  padding: 52rpx 32rpx 0 32rpx;
  .points-header {
    width: 100%;
    padding: 0 12rpx;
    margin-bottom: 34rpx;
    .points-total{
      width: 100%;
      display: inline-flex;
      .total {
        font-family: DIN, DIN;
        font-weight: 500;
        font-size: 80rpx;
        color: #FFFFFF;
        line-height: 80rpx;
      }
      .billImage{
        width: 32rpx;
        height: 32rpx;
        margin: 28rpx 0 28rpx 8rpx;
      }
    }
    .monthly-points {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #FFFFFF;
      line-height: 28rpx;
      margin: 10rpx 0 0 0;
    }
  }
  .rule-btn {
    position: absolute;
    top: 52rpx;
    right: 0;
    width: 88rpx;
    height: 40rpx;
    background: #FFFFFF;
    border-radius: 26rpx 0 0 26rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 28rpx;
    color: #00B6C8;
    line-height: 40rpx;
    text-align: center;
  }
}
</style>