<template>
  <view class="earn-points">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-icon" @click="handleBack"></view>
      <text class="header-title">赚取积分</text>
      <view class="header-right"></view>
    </view>

    <!-- 当前积分 -->
    <view class="current-points">
      <text class="label">当前积分</text>
      <text class="value">{{ balance }}</text>
    </view>

    <!-- 积分规则列表 -->
    <view class="rules-section">
      <view class="section-title">积分获取方式</view>
      
      <view class="rule-list">
        <view class="rule-item" v-for="(rule, index) in rules" :key="index">
          <view class="rule-icon">{{ getIcon(rule.ruleType) }}</view>
          <view class="rule-info">
            <view class="rule-name">{{ rule.ruleName }}</view>
            <view class="rule-desc">{{ getDesc(rule.ruleType) }}</view>
          </view>
          <view class="rule-points">+{{ rule.pointValue }}</view>
          <view class="rule-action" :class="{ disabled: rule.ruleType === 1 && isSignedToday }" @click="handleAction(rule)">
            {{ rule.ruleType === 1 && isSignedToday ? '已签到' : getActionText(rule.ruleType) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 积分说明 -->
    <view class="tips-section">
      <view class="section-title">积分说明</view>
      <view class="tips-content">
        <view class="tip-item">1. 积分可在积分商城兑换精美礼品</view>
        <view class="tip-item">2. 每日签到可获得积分奖励</view>
        <view class="tip-item">3. 上传优质线索可获得额外积分</view>
        <view class="tip-item">4. 撮合成功可获得大量积分奖励</view>
        <view class="tip-item">5. 积分永久有效，请放心使用</view>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  name: 'earn-points',
  data() {
    return {
      balance: 0,
      rules: [],
      makerId: null,
      isSignedToday: false  // 今日是否已签到
    }
  },
  onLoad() {
    this.initData()
  },
  onShow() {
    // 每次显示页面时刷新数据，确保数据同步
    if (this.makerId) {
      this.loadBalance()
      this.checkSignInStatus()
    }
  },
  methods: {
    async initData() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo && userInfo.matchmakerId) {
        this.makerId = userInfo.matchmakerId
      } else if (userInfo && userInfo.userId) {
        // 如果没有matchmakerId，通过API获取
        try {
          const res = await api.matchmaker.getByUserId(userInfo.userId)
          let matchmaker = res
          if (res && res.data) {
            matchmaker = res.data
          }
          if (matchmaker && (matchmaker.matchmakerId || matchmaker.matchmaker_id)) {
            this.makerId = matchmaker.matchmakerId || matchmaker.matchmaker_id
            // 保存到userInfo中
            userInfo.matchmakerId = this.makerId
            uni.setStorageSync('userInfo', userInfo)
          }
        } catch (e) {
          console.error('获取红娘信息失败:', e)
        }
      }
      
      await Promise.all([
        this.loadBalance(),
        this.loadRules(),
        this.checkSignInStatus()
      ])
    },
    
    // 检查今日签到状态
    async checkSignInStatus() {
      if (!this.makerId) return
      try {
        const res = await api.matchmaker.checkinStatus(this.makerId)
        // 解析返回数据
        let data = res
        if (res && res.data !== undefined) {
          data = res.data
        }
        this.isSignedToday = data === true || data?.isCheckedIn === true || data?.checked === true
      } catch (e) {
        console.error('检查签到状态失败:', e)
      }
    },
    
    async loadBalance() {
      if (!this.makerId) return
      try {
        const res = await api.pointsMall.getBalance(this.makerId)
        this.balance = res.balance || 0
      } catch (e) {
        console.error('获取积分余额失败:', e)
      }
    },
    
    async loadRules() {
      try {
        const res = await api.pointsMall.getRules()
        this.rules = res || []
      } catch (e) {
        console.error('获取积分规则失败:', e)
      }
    },
    
    handleBack() {
      uni.navigateBack()
    },
    
    getIcon(ruleType) {
      const icons = {
        1: '📅', // 签到
        2: '📤', // 上传线索
        3: '💕', // 撮合成功
        4: '📚', // 完成培训
        5: '🎁'  // 活动奖励
      }
      return icons[ruleType] || '⭐'
    },
    
    getDesc(ruleType) {
      const descs = {
        1: '每日签到即可获得积分',
        2: '上传优质客户线索',
        3: '成功撮合一对情侣',
        4: '完成红娘培训课程',
        5: '参与平台活动获得'
      }
      return descs[ruleType] || '完成任务获得积分'
    },
    
    getActionText(ruleType) {
      const texts = {
        1: '去签到',
        2: '去上传',
        3: '查看',
        4: '去学习',
        5: '查看'
      }
      return texts[ruleType] || '去完成'
    },
    
    async handleAction(rule) {
      if (rule.ruleType === 1) {
        // 签到 - 先检查是否已签到
        if (this.isSignedToday) {
          uni.showToast({ title: '今日已签到', icon: 'none' })
          return
        }
        await this.doSignIn(rule)
      } else if (rule.ruleType === 2) {
        // 上传线索
        uni.navigateTo({
          url: '/pages/matchmaker-workbench/add-resource'
        })
      } else if (rule.ruleType === 4) {
        // 培训课程
        uni.navigateTo({
          url: '/pages/courses/list'
        })
      } else {
        uni.showToast({
          title: '功能开发中',
          icon: 'none'
        })
      }
    },
    
    async doSignIn(rule) {
      if (!this.makerId) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
      }
      
      try {
        // 使用红娘签到接口
        const res = await api.matchmaker.doCheckin(this.makerId)
        
        // 签到成功后更新状态
        this.isSignedToday = true
        
        // 刷新积分余额
        await this.loadBalance()
        
        uni.showToast({
          title: `签到成功，+${rule.pointValue}积分`,
          icon: 'success'
        })
      } catch (e) {
        console.error('签到失败:', e)
        // 如果是已签到的错误，更新状态
        if (e.message && e.message.includes('已签到')) {
          this.isSignedToday = true
        }
        uni.showToast({
          title: e.message || '签到失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.earn-points {
  min-height: 100vh;
  background: #F5F5F5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25rpx 30rpx;
  padding-top: calc(25rpx + env(safe-area-inset-top));
  background: #FFFFFF;
  
  .back-icon {
    width: 44rpx;
    height: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #333;
    &::before { content: '‹'; }
  }
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .header-right {
    width: 44rpx;
  }
}

.current-points {
  background: linear-gradient(135deg, #9C27B0 0%, #E91E63 100%);
  margin: 30rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .label {
    font-size: 30rpx;
    color: rgba(255, 255, 255, 0.8);
  }
  
  .value {
    font-size: 56rpx;
    font-weight: bold;
    color: #FFFFFF;
  }
}

.rules-section {
  background: #FFFFFF;
  margin: 0 30rpx 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.rule-list {
  .rule-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #F0F0F0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .rule-icon {
      font-size: 48rpx;
      margin-right: 20rpx;
    }
    
    .rule-info {
      flex: 1;
      
      .rule-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .rule-desc {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .rule-points {
      font-size: 32rpx;
      font-weight: bold;
      color: #FF9800;
      margin-right: 20rpx;
    }
    
    .rule-action {
      padding: 12rpx 24rpx;
      background: linear-gradient(135deg, #9C27B0 0%, #E91E63 100%);
      color: #FFFFFF;
      font-size: 24rpx;
      border-radius: 30rpx;
      
      &.disabled {
        background: #CCCCCC;
        color: #FFFFFF;
      }
    }
  }
}

.tips-section {
  background: #FFFFFF;
  margin: 0 30rpx 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .tips-content {
    .tip-item {
      font-size: 26rpx;
      color: #666;
      line-height: 2;
    }
  }
}
</style>
