import {
  doNavigateWithUser
} from '../../../utils/helper';
import {
  apiArr
} from '../../../api/user';
import {
  postUrl
} from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    starteTime: '',
    endTime: '',
    points: [{
        time: '01.29',
        state: true,
      },
      {
        time: '+2',
        state: false,
      },
      {
        time: '+3',
        state: false,
      },
      {
        time: '+4',
        state: false,
      },
      {
        time: '+5',
        state: false,
      },
      {
        time: '+6',
        state: false,
      },
      {
        time: '+7',
        state: false,
      },
      {
        time: '+1',
        state: false,
      },
      {
        time: '+2',
        state: false,
      },
      {
        time: '+3',
        state: false,
      },
      {
        time: '+4',
        state: false,
      },
      {
        time: '+5',
        state: false,
      },
      {
        time: '+6',
        state: false,
      },
      {
        time: '+7',
        state: false,
      },
      {
        time: '+1',
        state: false,
      },
      {
        time: '+2',
        state: false,
      },
      {
        time: '+3',
        state: false,
      },
      {
        time: '+4',
        state: false,
      },
      {
        time: '+5',
        state: false,
      },
      {
        time: '+6',
        state: false,
      },
      {
        time: '+7',
        state: false,
      },
      {
        time: '+1',
        state: false,
      },
      {
        time: '+2',
        state: false,
      },
      {
        time: '+3',
        state: false,
      },
      {
        time: '+4',
        state: false,
      },
      {
        time: '+5',
        state: false,
      },
      {
        time: '+6',
        state: false,
      },
      {
        time: '+7',
        state: false,
      },
      {
        time: '+1',
        state: false,
      },
      {
        time: '+2',
        state: false,
      },
    ],
    pointsList: [],
    checkedData: 0,
    pointsNum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init();
  },

  async init() {
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    this.getIntegral();
    await postUrl(apiArr.signCycle, {}, async res => {
      const { start_time, end_time, day_num } = res;
      this.setData({
        starteTime: start_time,
        endTime: end_time
      })
      await this.getGridList(start_time, day_num);
      await this.getSignList(start_time, end_time, day_num);
      wx.hideLoading();
    })
  },
  getIntegral() {
    postUrl(apiArr.signIntegral,{}, res => {
      console.log('123131231312311', res)
      this.setData({
        pointsNum: res.integral
      })
    })
  },
  getGridList(startTime, dayNum) {
    // 获取当前日期
    const today = new Date();
    // const todayString = today.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD

    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
    const day = String(today.getDate()).padStart(2, '0');
    const todayString = `${year}-${month}-${day}`;

    
    // 将日期字符串转换为 Date 对象
    const startDate = new Date(startTime);

    const dayList = Array.from({
      length: dayNum
    }, (_, index) => {
      // 创建一个新的 Date 对象，表示当前的天数
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + index);

      const currentDateString = currentDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD


      // 检查当前日期是否是今天
      const isToday = currentDateString === todayString;

      // 格式化当前日期为 MM.DD
      const formattedDate = (`0${currentDate.getMonth() + 1}`).slice(-2) + '.' + (`0${currentDate.getDate()}`).slice(-2);
      return {
        time: formattedDate,
        date: currentDateString,
        points: 1,
        today: isToday,
      }
    });
    console.log('dayListdayListdayListdayList', dayList)
    this.setData({
      pointsList: dayList
    })
  },

  getSignList(startTime, endTime, dayNum) {
    postUrl(apiArr.signList, {
      page_num: 1,
      page_size: dayNum,
      sign_date: [startTime, endTime]
    }, res => {
      const updatedList = this.data.pointsList.map(item => {
        // 使用 some 检查 已签到列表 中是否有匹配的日期
        const isSign = res.rows.some(dayObj => dayObj.day === item.date);
       
        // 返回一个新的对象，包含原始字段和可能的 isSign 字段
        return {
          ...item,
          isSign: isSign
        };
      });
      this.setData({
        checkedData: res.total,
        pointsList: updatedList
      })
    })
  },

  headerPointsClick() {
    doNavigateWithUser({
      url: "/packages/user/points/detail"
    });
  },

  headerSignClick(event) {
    let _this = this;
    postUrl(apiArr.sign, {}, res => {
      // if (res.error) {
      //   wx.showToast({
      //     icon: 'none',
      //     title: `签到失败`,
      //   })
      //   return;
      // }
      wx.showToast({
        icon: 'none',
        title: `签到成功，获得 1 积分`,
        success() {
          setTimeout(() => {
            _this.init()
          }, 1000)
        }
      })
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})