import { computed } from 'vue';
import moment from 'moment';
import useMemo from '../_util/hooks/useMemo';
const monthsShort = moment().localeData().monthsShort();
export default function useCalendar(props) {
  // const valueRef = ref<Moment>(moment.isMoment(props.value) ? props.value : moment())
  // watch(() => props.value, () => valueRef.value = moment.isMoment(props.value) ? props.value : moment())
  const valueRef = useMemo(() => moment.isMoment(props.value) ? props.value : moment()); // const selectedValueRef = ref<Array<Moment>>(props.selectedValue)
  // watch(() => props.selectedValue, () => selectedValueRef.value = props.selectedValue)

  const selectedValueRef = useMemo(() => props.selectedValue);
  const datesRef = computed(() => {
    const month1 = valueRef.value.clone().date(1);
    const day = month1.day();
    const lastMonthDiffDay = (day + 7 - valueRef.value.localeData().firstDayOfWeek()) % 7; // 显示上月天

    const lastMonth1 = month1.clone().add(-lastMonthDiffDay, 'days');
    return Array.from(Array(42), (_, i) => lastMonth1.clone().add(i, 'days'));
  });
  const monthsRef = computed(() => {
    const jan = valueRef.value.clone().month(0);
    return Array.from(Array(16), (_, i) => jan.clone().add(i, 'months'));
  });
  const yearsRef = computed(() => {
    const year = valueRef.value.year(),
          decade = year - year % 10,
          offset = decade % 4;
    const lastYear = valueRef.value.clone().year(decade).add(-offset, 'years');
    return Array.from(Array(16), (_, i) => lastYear.clone().add(i, 'years'));
  });

  function prevMonth() {
    goMonth(-1);
  }

  function nextMonth() {
    goMonth(1);
  }

  function prevYear() {
    goYear(-1);
  }

  function nextYear() {
    goYear(1);
  }

  function goMonth(direction) {
    valueRef.value = valueRef.value.clone().add(direction, 'months');
  }

  function goYear(direction) {
    valueRef.value = valueRef.value.clone().add(direction, 'years');
  }

  return {
    valueRef,
    selectedValueRef,
    datesRef,
    monthsRef,
    yearsRef,
    // func
    goMonth,
    goYear,
    prevMonth,
    nextMonth,
    prevYear,
    nextYear,

    isSelected(date, granularity, selected = selectedValueRef.value) {
      if (Array.isArray(selected)) {
        const [v1 = null, v2 = null] = selected;
        return date.isSame(v1, granularity) || date.isSame(v2, granularity);
      } else {
        return date.isSame(valueRef.value, granularity);
      }
    },

    isInRange(date, granularity, selected = selectedValueRef.value) {
      const [v1 = null, v2 = null] = selected || [];
      return date.isAfter(v1, granularity) && date.isBefore(v2, granularity);
    },

    // event
    onSelect(m) {
      var _props$onSelect;

      valueRef.value = m.clone();
      (_props$onSelect = props.onSelect) === null || _props$onSelect === void 0 ? void 0 : _props$onSelect.call(props, m);
    }

  };
}