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

// 签到提醒系统
export const useReminder = {
  // 检查是否需要提醒
  async checkSignReminder() {
    // 获取用户最后签到时间
    const lastSign = uni.getStorageSync('lastSignDate') || ''
    const today = new Date().toISOString().split('T')[0]
    
    // 今天已签到
    if (lastSign === today) return false
    
    // 获取用户设置
    const settings = uni.getStorageSync('userSettings') || {}
    if (settings.signReminder === false) return false
    
    // 检查服务器端签到状态
    try {
      const res = await request({
        url: '/sign/status',
        method: 'GET',
        headers: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
      })
      
      return !res.data.todaySigned
    } catch (e) {
      console.error('签到状态检查失败', e)
      return false
    }
  },
  
  // 显示签到提醒
  showReminder() {
    uni.showModal({
      title: '每日签到',
      content: '您今天还未签到，立即签到可获得金币奖励！',
      confirmText: '去签到',
      cancelText: '稍后提醒',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/welfare/index' })
        } else {
          // 1小时后再次提醒
          setTimeout(this.showReminder, 60 * 60 * 1000)
        }
      }
    })
  },
  
  // 初始化签到提醒
  init() {
    // 每天10点检查签到
    setInterval(async () => {
      const shouldRemind = await this.checkSignReminder()
      if (shouldRemind) {
        this.showReminder()
      }
    }, 60 * 60 * 1000) // 每小时检查一次
    
    // 应用启动时检查
    this.checkSignReminder().then(shouldRemind => {
      if (shouldRemind) {
        setTimeout(() => this.showReminder(), 3000) // 3秒后显示
      }
    })
  }
}