/**
 * 每日签到
 * 对齐后端 /api/marketing/checkin/status + /api/marketing/checkin
 * 奖励规则: 连续签到天数越久积分越多（3天=10,10天=30,30天=100,60天=200）
 */
const api = require('../../utils/api');

Page({
  data: {
    streak: 0,
    checkedToday: false,
    records: [],
    rewardDesc: '',
    todayReward: 0,
    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
    week: []
  },

  onLoad() {
    this.buildWeek();
    this.loadStatus();
  },

  buildWeek() {
    const today = new Date();
    const day = today.getDay();
    const week = [];
    for (let i = 0; i < 7; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() - day + i);
      week.push({
        day: this.data.daysOfWeek[i],
        date: d.getDate(),
        active: i === day
      });
    }
    this.setData({ week });
  },

  async loadStatus() {
    try {
      const res = await api.getCheckinStatus();
      if (res) {
        this.setData({
          streak: res.streak || 0,
          checkedToday: !!res.checked_today,
          records: res.records || []
        });
      }
    } catch (e) {}
  },

  async doCheckin() {
    if (this.data.checkedToday) {
      wx.showToast({ title: '今日已签到', icon: 'none' });
      return;
    }
    try {
      const res = await api.doCheckin();
      if (res) {
        this.setData({ checkedToday: true });
        wx.showToast({ title: res.message || '签到成功', icon: 'success' });
        this.loadStatus();
      }
    } catch (e) {}
  }
});
