<template>
  <view class="task-page">
    <!-- 顶部积分信息 -->
    <view class="points-header">
      <view class="points-item">
        <view class="img">
          <u-avatar :src="cIcon" size="96rpx" default-url="/static/common/avatar.png" />
        </view>
      </view>
      <view class="points-item">
        <text class="points-value">{{ totalPoints }}</text>
        <text class="points-label">我的积分</text>
      </view>
      <view class="points-item">
        <text class="points-value">{{ completedTask }}</text>
        <text class="points-label">已完成任务</text>
      </view>
      <view class="points-item" @click="handleServiceTask">
        <text class="points-value">{{ pendingTasks }}</text>
        <text class="points-label">待完成任务</text>
      </view>
    </view>

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

      <!-- 任务列表 -->
      <view class="tasks-container">
        <u-list 
          ref="taskList"
          @scrolltolower="loadMore" 
          style="height:calc(75vh - 60rpx)"
        >
          <u-list-item v-for="(task, index) in tasks" :key="index" class="task-item">
            <view class="task-icon">
              <image :src="getTaskIcon(task.taskName)" mode="aspectFill"></image>
            </view>
            <view class="task-info">
              <text class="task-name">{{ task.taskName }}</text>
              <view class="task-reward">
                <ImageItem src="/static/points/point.png"/>
                <text>+{{ task.rewardPoints }}</text>
              </view>
            </view>
            <view class="task-progress">
              <text class="progress-text">{{ task.completedCount }}/{{ task.triggerValue }}</text>
              <button 
                :class="Number(task.completedCount) >= Number(task.triggerValue) ? 'task-btn' : 'no-task-btn'"
                @click.stop="handleTask(task)"
                :disabled="Number(task.completedCount) >= Number(task.triggerValue)"
              >
                {{ Number(task.completedCount) >= Number(task.triggerValue) ? '已完成' : '去完成' }}
              </button>
            </view>
          </u-list-item>
          <!-- 空数据状态 -->
          <u-empty
              v-if="tasks.length === 0 && !loading"
              icon="document"
              text="暂无任务"
              mode="page"
          ></u-empty>
          <!-- 加载中状态 -->
          <view v-if="loading && tasks.length === 0" class="loading-container">
            <u-loading-icon text="加载中..."></u-loading-icon>
          </view>
          <!-- 加载更多 -->
          <u-loadmore 
            v-if="tasks.length > 0"
            :status="loading ? 'loading' : (hasMore ? 'more' : 'nomore')"
            loading-text="加载中..."
            nomore-text="没有更多任务了"
            @loadmore="loadMore"
          ></u-loadmore>
        </u-list>
      </view>
    </view>
  </view>
</template>

<script>
import ImageItem from "@/components/swiper/components/image.vue";
import { mapState } from 'vuex';
import {getPointTaskList, goComplete} from '@/api/points'
import { handleServiceShare } from '@/utils/share'
export default {
  name: "taskList",
  components: {ImageItem},
  computed: {
    ...mapState({
      myPoint: state => state.points.myPoint
    }),
    totalPoints() {
      return this.myPoint && this.myPoint.totalPoints || 0;
    },
    completedTask() {
      return this.myPoint && this.myPoint.completedTask || 0;
    },
    pendingTasks() {
      return this.myPoint && this.myPoint.pendingTasks || 0;
    },
    type() {
      return this.tabs.findIndex(item => item.key === this.activeTab)
    },

  },
  data() {
    return {
      cIcon: uni.getStorageSync('wx_cIcon'),
      // 标签数据
      tabs: [
        { key: '1', name: '新手任务' },
        { key: '2', name: '每日任务' },
        { key: '3', name: '每月任务' }
      ],
      // 当前选中的标签
      activeTab: '1',
      // 任务数据
      tasks: [],
      // 分页数据
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      // 任务类型配置
      taskConfig: {
        order: {
          icon: '/static/points/task_order.png',
          action: this.handleOrderTask
        },
        merchant: {
          icon: '/static/points/task_shop.png',
          action: this.handleMerchantTask
        },
        dynamic: {
          icon: '/static/points/task_trend.png',
          action: this.handleDynamicTask
        },
        service: {
          icon: '/static/points/task_wx.png',
          action: this.handleServiceTask
        },
        recharge: {
          icon: '/static/points/task_account.png',
          action: this.handleRechargeTask
        }
      }
    }
  },
  onReady() {
    // 初始获取数据
    this.fetchTaskList()
  },
  methods: {
    // 切换标签
    handleTabChange(data) {
      this.activeTab = data.key
      // 重置分页数据
      this.pageNum = 1
      this.hasMore = true
      // 清空数据
      this.tasks = []
      // 重新获取数据
      this.fetchTaskList()
    },
    // 处理任务
    handleTask(task) {
      if (task.completedCount >= task.triggerValue) return;
      if (task.taskName.includes('订单')) {
        this.taskConfig.order.action();
      } else if (task.taskName.includes('商户')) {
        this.taskConfig.merchant.action();
      } else if (task.taskName.includes('动态')) {
        this.taskConfig.dynamic.action();
      } else if (task.taskName.includes('服务号')) {
        this.taskConfig.service.action();
      } else if (task.taskName.includes('充值')) {
        this.taskConfig.recharge.action();
      }
      this.handleCompleteTask(task)
    },
    // 任务去完成
    handleCompleteTask(task) {
      const res = goComplete({
        taskId:task?.taskId
      })
    },
    // 处理订单任务
    handleOrderTask() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    // 处理商户任务
    handleMerchantTask() {
      uni.switchTab({
        url: '/pages/identify/identify'
      });
    },
    // 处理动态任务
    handleDynamicTask() {
      uni.switchTab({
        url: '/pages/discover/discover'
      });
    },
    // 处理服务号任务
    handleServiceTask() {
      // 调用微信服务号分享功能
      handleServiceShare({
        title: '广誉远 - 关注服务号',
        desc: '关注广誉远服务号，获取更多积分和优惠',
        link: window.location.href,
        imgUrl: '/static/points/task_wx.png'
      });
    },
    // 处理账号充值任务
    handleRechargeTask() {
      uni.navigateTo({
        url: '/pages/my/pay'
      });
    },
    // 加载更多数据
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.pageNum++
      this.fetchTaskList(true)
    },
    // 获取任务列表数据
    async fetchTaskList(isLoadMore = false) {
      this.loading = true
      try {
        const res = await getPointTaskList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          type: this.activeTab,
          cityCode: uni.getStorageSync('selectCitycode'),
        })
        const {data} = res;
        if (data.code === 200) {
          if (isLoadMore) {
            this.tasks = [...this.tasks, ...data.data.records]
          } else {
            this.tasks = data.data.records
          }
          this.hasMore = this.tasks.length < data.data.total
        }
        this.loading = false

      } catch (error) {
        console.error('获取任务列表失败:', error)
        this.loading = false
      }
    },
    // 根据任务名称获取图标
    getTaskIcon(taskName) {
      if (taskName.includes('订单')) return this.taskConfig.order.icon;
      if (taskName.includes('商户')) return this.taskConfig.merchant.icon;
      if (taskName.includes('动态')) return this.taskConfig.dynamic.icon;
      if (taskName.includes('服务号')) return this.taskConfig.service.icon;
      if (taskName.includes('充值')) return this.taskConfig.recharge.icon;
      return ''
    }
  }
}
</script>

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

.points-header{
  display: flex;
  justify-content: space-around;
  margin-bottom: 42rpx;
  padding: 0 36rpx;
  .points-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .points-label{
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #FFFFFF;
      line-height: 24rpx;
    }
    .points-value{
      font-family: DIN, DIN;
      font-weight: 500;
      font-size: 40rpx;
      color: #FFFFFF;
      line-height: 32rpx;
      margin-bottom: 16rpx;
      display: block;
    }
  }
}
.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;
  }
}

.tasks-container{
  .task-item{
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    flex-direction: row;
    .task-icon{
      width: 80rpx;
      height: 80rpx;
      margin-right: 24rpx;
      image{
        width: 100%;
        height: 100%;
      }
    }
    .task-info{
      flex: 1;
      .task-name{
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
        line-height: 28rpx;
        display: block;
        margin-bottom: 12rpx;
      }
      .task-reward {
        display: inline-flex;
        height: 32rpx;
        background: #FBF2E1;
        border-radius: 22rpx;
        padding-right: 12rpx;
        image{
          width: 32rpx;
          height: 32rpx;
          margin-right: 4rpx;
        }
        text{
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 24rpx;
          color: #FF9F00;
          line-height: 32rpx;
        }
      }
    }
    .task-progress{
      display: flex;
      flex-direction: row;
      .progress-text{
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #999999;
        line-height: 28rpx;
        margin-right: 8rpx;
        margin-top: 10rpx;
      }
      .task-btn {
        height: 48rpx;
        background: #EEEEEE;
        border-radius: 98rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 26rpx;
        color: #999999;
        line-height: 48rpx;
        border: 1px solid #EEEEEE;
        margin: 0;
        padding: 0 20rpx;
      }
      .no-task-btn {
        height: 48rpx;
        background: #03C1B8;
        border-radius: 98rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 26rpx;
        color: #FFFFFF;
        line-height: 48rpx;
        margin: 0;
        padding: 0 20rpx;
      }
    }
  }
  .u-empty{
    margin-top: 20vh!important;
  }

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