<template>
    <scroll-view
        class="date-strip date-strip__scroll"
        :scroll-x="true"
        :show-scrollbar="false"
        direction="horizontal"
        :style="[styles]"
    >
        <date-strip-item :dates="displayWeeks[0].dates" @click="onClick" />
    </scroll-view>
</template>

<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import dateStripProps from './props'
import { getWeekRange, addDays, addWeeks, calcType, daysBetween } from './utils'
import dateStripItem from './date-strip-item.vue'

const props = defineProps({
    ...dateStripProps
})
const emit = defineEmits([
    'change',
    'select',
    'scroll',
    'panelChange',
    'update:modelValue',
    'input'
])
// 当前选中的周索引
const currentWeekIndex = ref(0)
const selectedDate = ref<Date | null>(null)
// 计算一周的星期顺序
const firstDayOfWeek = computed((): number => Math.min(Math.max(props.firstDayOfWeek, 0), 6))

// 计算最小和最大日期
const today = new Date()
const minDate = computed((): Date => (props.minDate != null ? new Date(props.minDate!) : today))
const maxDate = computed(
    (): Date => (props.maxDate != null ? new Date(props.maxDate!) : addDays(today, 31))
)

const days = computed((): number => {
    return daysBetween(maxDate.value, minDate.value)
})

const styles = computed(() => {
    const style: Record<string, any> = {}

    if (props.height) {
        style['height'] = props.height
    }
    if (props.bgColor) {
        style['background'] = props.bgColor
    }
    return style
})

const cache = new Map()
const createWeek = (currentStartDate: Date, length: number) => {
    const dates = []
    const time = currentStartDate.getTime()
    if (cache.has(time)) {
        return cache.get(time)!
    }
    for (let i = 0; i < length; i++) {
        const date = new Date(time)
        date.setDate(currentStartDate.getDate() + i)
        const week = date.getDay()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const dateObj = {
            key: `${year}-${month}-${day}`,
            date,
            year,
            month,
            day,
            text: `${day}`.padStart(2, '0'),
            type: calcType(date, minDate.value, maxDate.value, selectedDate.value),
            prefix: props.weekdays[week]
        }
        dates.push(props.format != null ? props.format!(dateObj) : dateObj)
    }
    const obj = {
        start: new Date(dates[0].year, dates[0].month - 1, dates[0].day).getTime(),
        end: new Date(
            dates[length - 1].year,
            dates[length - 1].month - 1,
            dates[length - 1].day
        ).getTime(),
        dates
    }

    // cache.set(time, obj)

    return obj
}

const currentDate = ref<Date>(today)

// 计算要显示的三周数据
const displayWeeks = computed(() => {
    const weeks = []
    if (props.switchMode == 'week') {
        const currentRange = getWeekRange(currentDate.value, firstDayOfWeek.value)
        const offsetMap = new Map<number, number[]>([
            [0, [0, 1, -1]],
            [1, [-1, 0, 1]],
            [2, [1, -1, 0]]
        ])
        const indices = offsetMap.get(currentWeekIndex.value)!
        indices.forEach(i => {
            const weekDate = addWeeks(currentRange.start, i)
            weeks.push(createWeek(weekDate, 7))
        })
    } else {
        weeks.push(createWeek(minDate.value, days.value))
    }

    return weeks
})

const onClick = (day: Day) => {
    // if (day.type == 'disabled') return
    selectedDate.value = day.date
    const v = day.date.getTime()
    emit('change', day)
    emit('select', v)
    emit('update:modelValue', v)
    // #ifdef VUE2
    emit('input', v)
    // #endif
}

watchEffect(() => {
    const value = props.value || props.modelValue
    if (!value) return
    selectedDate.value = new Date(value)
})
</script>
<style lang="scss"></style>
