import { digit, format as DateFormat } from './../../../utils/getDay';

const delay = () => new Promise(resolve => {
  setTimeout(resolve, 350);
});

Component({
  data: {
    calendarShow: false,
    showToday: false,
    disableDates: [],
    calendarCreate: true
  },
  props: {
    selectedIndex: 0,

    /*
    * 展示3天的数据
    * */
    threeDayList: [],

    /*
    * 日历的展示
    * */
    calendarTags: [],

    /*
    * 禁用的日期
    * */
    disableDays: [],
    selectedDate: '',
    onChange: () => null,
    onTapDate: () => null,
    onOpenCalendar: () => null
  },
  methods: {
    updateState(state) {
      const func = resolve => {
        this.setData(state, resolve);
      };

      return new Promise(func);
    },

    onItemClick({
      currentTarget
    }) {
      const {
        threeDayList = []
      } = this.props;
      const {
        value
      } = currentTarget.dataset;
      const {
        stock = 0
      } = threeDayList[value] || {};
      if (!+stock) return;
      this.props.onChange(value);
    },

    async onPopupClose() {
      await this.updateState({
        calendarShow: false
      });
      await delay();
      await this.updateState({
        calendarCreate: false
      });
    },

    async onShowHandel() {
      const {
        selectedDate
      } = this.props;
      const date = selectedDate ? new Date(DateFormat(selectedDate)) : new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const dates = this.getDatesByMonth(year, month);
      await this.props.onOpenCalendar([year, digit(month)].join('-'), dates);
      await this.updateState({
        calendarShow: true,
        calendarCreate: true
      });
    },

    onMonthChange({
      year,
      month
    }) {
      const dates = this.getDatesByMonth(year, month);
      this.props.onOpenCalendar([year, digit(month)].join('-'), dates);
    },

    /* 获取某个月的全部日期 */
    getDatesByMonth(year, month) {
      const date = new Date(year, month, 0);
      const dayArray = Array.from({
        length: date.getDate()
      });
      return dayArray.map((item, i) => [year, digit(month), digit(i + 1)].join('-'));
    },

    async onTapDate(res) {
      this.props.onTapDate(res);
      await this.onPopupClose();
    }

  }
});