const { getMonthCalendar } = require('../../utils/core/index.js');

Page({
  data: {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    weekHeaders: ['日', '一', '二', '三', '四', '五', '六'],
    calendarDays: [],
    selectedDay: null,
    showMonthPicker: false,
    years: [],
    months: [1,2,3,4,5,6,7,8,9,10,11,12],
    pickerValue: [0, 0]
  },

  onLoad() {
    const years = [];
    for (let y = 1900; y <= 2100; y++) years.push(y);
    this.setData({ years });
    this.loadCalendar();
  },

  loadCalendar() {
    const { year, month } = this.data;
    const weeks = getMonthCalendar(year, month);
    const calendarDays = [];
    weeks.forEach(week => {
      week.forEach(day => calendarDays.push(day));
    });
    this.setData({ calendarDays });
  },

  prevMonth() {
    let { year, month } = this.data;
    month--;
    if (month < 1) { month = 12; year--; }
    this.setData({ year, month }, () => this.loadCalendar());
  },

  nextMonth() {
    let { year, month } = this.data;
    month++;
    if (month > 12) { month = 1; year++; }
    this.setData({ year, month }, () => this.loadCalendar());
  },

  showPicker() {
    const { year, month } = this.data;
    this.setData({
      showMonthPicker: true,
      pickerValue: [year - 1900, month - 1]
    });
  },

  hidePicker() {
    this.setData({ showMonthPicker: false });
  },

  pickerChange(e) {
    this.setData({ pickerValue: e.detail.value });
  },

  confirmPicker() {
    const { pickerValue, years, months } = this.data;
    this.setData({
      year: years[pickerValue[0]],
      month: months[pickerValue[1]],
      showMonthPicker: false
    }, () => this.loadCalendar());
  },

  selectDay(e) {
    const date = e.currentTarget.dataset.date;
    const day = this.data.calendarDays.find(d => d.solarDate === date);
    this.setData({ selectedDay: day });
  },

  goDetail() {
    const { selectedDay } = this.data;
    if (selectedDay) {
      wx.navigateTo({ url: `/pages/day-detail/day-detail?date=${selectedDay.solarDate}` });
    }
  },

  noop() {}
});
