import { ref } from 'vue'
import { request } from '@/utils/request'

// 签到状态管理
export function useSignSystem() {
  const signedDays = ref(0)
  const todaySigned = ref(false)
  const signRewards = ref([])
  
  // 加载签到状态
  const loadSignStatus = async () => {
    try {
      const res = await request({
        url: '/sign/status',
        method: 'GET',
        headers: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
      })
      
      signedDays.value = res.data.signedDays || 0
      todaySigned.value = res.data.todaySigned || false
      signRewards.value = res.data.rewards || generateDefaultRewards()
      return true
    } catch (err) {
      console.error('签到状态加载失败', err)
      return false
    }
  }
  
  // 执行签到
  const doSign = async () => {
    if (todaySigned.value) return
    
    try {
      uni.showLoading({ title: '签到中...' })
      const res = await request({
        url: '/sign/do',
        method: 'POST',
        headers: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
      })
      
      if (res.data.success) {
        signedDays.value++
        todaySigned.value = true
        uni.showToast({ title: `签到成功！获得${res.data.reward}金币`, icon: 'success' })
        return res.data.reward
      }
    } catch (err) {
      uni.showToast({ title: '签到失败', icon: 'none' })
    } finally {
      uni.hideLoading()
    }
  }
  
  // 生成默认奖励规则
  const generateDefaultRewards = () => {
    return [
      { day: 1, reward: 10 },
      { day: 2, reward: 15 },
      { day: 3, reward: 20 },
      { day: 4, reward: 25 },
      { day: 5, reward: 30 },
      { day: 6, reward: 40 },
      { day: 7, reward: 50, extra: '双倍金币卡' }
    ]
  }
  
  return {
    signedDays,
    todaySigned,
    signRewards,
    loadSignStatus,
    doSign
  }
}