<template>
    <Picker :columns="columns" :defaultIndex="innerDefaultIndex" @change="change">
        <template #toolbar>
            <view class="toolbar">
                <view class="reset" @click="cancel">重置</view>
                <view class="confirm" @click="confirm">确定</view>
            </view>
        </template>
    </Picker>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import _ from 'lodash'
import { onMounted, ref, watch } from 'vue'
import Picker from './design-picker.vue'

const props = defineProps({
    maxDate: {
        type: Number,
        default: new Date(new Date().getFullYear() + 10, 0, 1).getTime()
    },
    minDate: {
        type: Number,
        default: new Date(new Date().getFullYear() - 10, 0, 1).getTime()
    },
    mode: {
        type: String,
        default: 'date'
    },
    modelValue: {
        type: [String, Number],
        default: ''
    },
    minHour: {
        type: Number,
        default: 0
    },
    maxHour: {
        type: Number,
        default: 23
    },
    minMinute: {
        type: Number,
        default: 0
    },
    maxMinute: {
        type: Number,
        default: 59
    },
    show: {
        type: Boolean,
        default: false
    },
    defaultIndex: {
        type: Array,
        default: () => []
    }
})
const emit = defineEmits(['update:modelValue', 'change', 'confirm', 'cancel'])

const innerValue = ref('')
const columns = ref<string[][]>([[]]) // 各列的值
const innerDefaultIndex = ref<number[]>([])

const init = () => {
    const { modelValue } = props
    innerValue.value = correctValue(modelValue)
    updateColumnValue(innerValue.value)
}
const change = e => {
    const { indexs, values } = e
    const { mode } = props
    let selectValue = ''
    if (mode === 'time') {
        // 根据value各列索引，从各列数组中，取出当前时间的选中值
        selectValue = `${intercept(values[0][indexs[0]])}:${intercept(values[1][indexs[1]])}`
    } else {
        // 将选择的值转为数值，比如'03'转为数值的3，'2019'转为数值的2019
        const year = parseInt(intercept(values[0][indexs[0]], 'year'))
        const month = parseInt(intercept(values[1][indexs[1]]))
        let date = parseInt(values[2] ? intercept(values[2][indexs[2]]) : 1)
        let hour = 0,
            minute = 0
        // 此月份的最大天数
        const maxDate = dayjs(`${year}-${month}`).daysInMonth()
        // year-month模式下，date不会出现在列中，设置为1，为了符合后边需要减1的需求
        if (mode === 'year-month') {
            date = 1
        }
        // 不允许超过maxDate值
        date = Math.min(maxDate, date)
        if (mode === 'datetime') {
            hour = parseInt(intercept(values[3][indexs[3]]))
            minute = parseInt(intercept(values[4][indexs[4]]))
        }
        // 转为时间模式
        selectValue = Number(new Date(year, month - 1, date, hour, minute))
    }
    // 取出准确的合法值，防止超越边界的情况
    selectValue = correctValue(selectValue)
    innerValue.value = selectValue
    updateColumnValue(selectValue)

    emit('change', {
        value: selectValue,
        mode
    })
    emit('update:modelValue', innerValue.value)
}
const confirm = () => {
    emit('update:modelValue', innerValue.value)
    emit('confirm', {
        value: innerValue.value,
        mode: props.mode
    })
}
const cancel = () => {
    emit('cancel')
}

//用正则截取输出值,当出现多组数字时,抛出错误
const intercept = (e, type) => {
    const judge = e.match(/\d+/g)
    //判断是否掺杂数字
    if (judge.length > 1) {
        console.log('请勿在过滤或格式化函数时添加数字')
        return 0
    } else if (type && judge[0].length == 4) {
        //判断是否是年份
        return judge[0]
    } else if (judge[0].length > 2) {
        console.log('请勿在过滤或格式化函数时添加数字')
        return 0
    } else {
        return judge[0]
    }
}

const correctValue = (value: string | number) => {
    const { mode, minDate, maxDate, minHour, maxHour, minMinute, maxMinute } = props
    const isDateMode = mode !== 'time'
    if (isDateMode && !date(value)) {
        // 如果是日期类型，但是又没有设置合法的当前时间的话，使用最小时间为当前时间
        value = minDate
    } else if (!isDateMode && !value) {
        // 如果是时间类型，而又没有默认值的话，就用最小时间
        value = `${padZero(minHour)}:${padZero(minMinute)}`
    }
    // 时间类型
    if (!isDateMode) {
        if (String(value).indexOf(':') === -1) return console.log('时间错误，请传递如12:24的格式')
        let [hour, minute] = value.split(':')
        // 对时间补零，同时控制在最小值和最大值之间
        hour = padZero(range(minHour, maxHour, Number(hour)))
        minute = padZero(range(minMinute, maxMinute, Number(minute)))
        return `${hour}:${minute}`
    } else {
        // 如果是日期格式，控制在最小日期和最大日期之间
        value = dayjs(value).isBefore(dayjs(minDate)) ? minDate : value
        value = dayjs(value).isAfter(dayjs(maxDate)) ? maxDate : value
        return value
    }
}
// 获取每列的最大和最小值
const getRanges = () => {
    const { mode } = props
    if (mode === 'time') {
        return [
            {
                type: 'hour',
                range: [props.minHour, props.maxHour]
            },
            {
                type: 'minute',
                range: [props.minMinute, props.maxMinute]
            }
        ]
    }
    const { maxYear, maxDate, maxMonth, maxHour, maxMinute } = getBoundary('max', innerValue.value)
    const { minYear, minDate, minMonth, minHour, minMinute } = getBoundary('min', innerValue.value)
    const result = [
        {
            type: 'year',
            range: [minYear, maxYear]
        },
        {
            type: 'month',
            range: [minMonth, maxMonth]
        },
        {
            type: 'day',
            range: [minDate, maxDate]
        },
        {
            type: 'hour',
            range: [minHour, maxHour]
        },
        {
            type: 'minute',
            range: [minMinute, maxMinute]
        }
    ]
    if (mode === 'date') result.splice(3, 2)
    if (mode === 'year-month') result.splice(2, 3)
    return result
}

// 根据minDate、maxDate、minHour、maxHour等边界值，判断各列的开始和结束边界值
const getBoundary = (type: string, innerValue: string) => {
    const value = new Date(innerValue)
    const boundary = new Date(props[`${type}Date`])
    const year = dayjs(boundary).year()
    let month = 1
    let date = 1
    let hour = 0
    let minute = 0
    if (type === 'max') {
        month = 12
        // 月份的天数
        date = dayjs(value).daysInMonth()
        hour = 23
        minute = 59
    }
    // 获取边界值，逻辑是：当年达到了边界值(最大或最小年)，就检查月允许的最大和最小值，以此类推
    if (dayjs(value).year() === year) {
        month = dayjs(boundary).month() + 1
        if (dayjs(value).month() + 1 === month) {
            date = dayjs(boundary).date()
            if (dayjs(value).date() === date) {
                hour = dayjs(boundary).hour()
                if (dayjs(value).hour() === hour) {
                    minute = dayjs(boundary).minute()
                }
            }
        }
    }
    return {
        [`${type}Year`]: year,
        [`${type}Month`]: month,
        [`${type}Date`]: date,
        [`${type}Hour`]: hour,
        [`${type}Minute`]: minute
    }
}

const updateColumnValue = value => {
    innerValue.value = value
    updateColumns()
    // 延迟执行,等待u-picker组件列数据更新完后再设置选中值索引
    setTimeout(() => {
        updateIndexs(value)
    }, 0)
}
// 更新索引
const updateIndexs = value => {
    let values = []
    const { mode } = props
    const formatter = (type: string, value: string) => value
    if (mode === 'time') {
        // 将time模式的时间用:分隔成数组
        const timeArr = value.split(':')
        // 使用formatter格式化方法进行管道处理
        values = [formatter('hour', timeArr[0]), formatter('minute', timeArr[1])]
    } else {
        const date = new Date(value)
        values = [
            formatter('year', `${dayjs(value).year()}`),
            // 月份补0
            formatter('month', padZero(dayjs(value).month() + 1))
        ]
        if (mode === 'date') {
            // date模式，需要添加天列
            values.push(formatter('day', padZero(dayjs(value).date())))
        }
        if (mode === 'datetime') {
            // 数组的push方法，可以写入多个参数
            values.push(
                formatter('day', padZero(dayjs(value).date())),
                formatter('hour', padZero(dayjs(value).hour())),
                formatter('minute', padZero(dayjs(value).minute()))
            )
        }
    }

    // 根据当前各列的所有值，从各列默认值中找到默认值在各列中的索引
    const indexs = columns.value.map((column, index) => {
        // 通过取大值，可以保证不会出现找不到索引的-1情况
        return Math.max(
            0,
            column.findIndex(item => item === values[index])
        )
    })
    innerDefaultIndex.value = indexs
}

const updateColumns = () => {
    const formatter = (type: string, value: string) => value
    const results = getOriginColumns().map(column =>
        column.values.map(value => formatter(column.type, value))
    )
    columns.value = results
}
const getOriginColumns = () => {
    const results = getRanges().map(({ type, range }) => {
        const values = times(range[1] - range[0] + 1, index => {
            let value = range[0] + index
            value = type === 'year' ? `${value}` : padZero(value)
            return value
        })
        return { type, values }
    })
    return results
}

onMounted(() => {
    init()
    updateColumnValue(innerValue.value)
})
watch(
    () => props.modelValue,
    () => {
        init()
    }
)
watch(
    () => props.show,
    () => {
        updateColumnValue(innerValue.value)
    }
)
/**
 * 验证日期格式
 */
function date(value) {
    if (!value) return false
    // 判断是否数值或者字符串数值(意味着为时间戳)，转为数值，否则new Date无法识别字符串时间戳
    if (number(value)) value = +value
    return !/Invalid|NaN/.test(new Date(value).toString())
}
/**
 * 验证十进制数字
 */
function number(value) {
    return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
}
/**
 * @description 日期的月或日补零操作
 * @param {String} value 需要补零的值
 */
function padZero(value: string) {
    return `00${value}`.slice(-2)
}
/**
 * @description 如果value小于min，取min；如果value大于max，取max
 * @param {number} min
 * @param {number} max
 * @param {number} value
 */
function range(min = 0, max = 0, value = 0) {
    return Math.max(min, Math.min(max, Number(value)))
}
function times(n, iteratee) {
    let index = -1
    const result = Array(n < 0 ? 0 : n)
    while (++index < n) {
        result[index] = iteratee(index)
    }
    return result
}
</script>

<style lang="scss" scoped>
.toolbar {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
    padding: 0 32rpx;
    margin: 40rpx 0;
    > view {
        flex: 1;
        text-align: center;
        height: 100%;
        line-height: 80rpx;
        border-radius: 8rpx;
        &.reset {
            border: 1px solid $gray-2;
        }
        &.confirm {
            background: $blue-1;
            color: $white-1;
        }
    }
}
</style>
