<template>
    <uni-popup ref="picker" type="bottom" :safe-area="false">
        <view class="picker">
            <view class="title">选择时间</view>
            <text class="demo-icon demo-icon-guanbi" @tap="picker.close()"></text>
            <view class="top">
                <view :class="{ time: true, selected: active === 0 }" @tap="handleClick(0)">
                    {{ startTime || '开始时间' }}
                </view>
                <text>至</text>
                <view :class="{ time: true, selected: active === 1 }" @tap="handleClick(1)">
                    {{ endTime || '结束时间' }}
                </view>
            </view>
            <picker-view
                :value="val"
                indicator-style="height:52px"
                indicator-class="active"
                class="picker-view"
                immediate-change
                @change="change"
            >
                <picker-view-column>
                    <view
                        v-for="(item, index) in years"
                        :key="index"
                        :class="{ item: true, active_item: val[0] === index }"
                    >
                        {{ item }}
                    </view>
                </picker-view-column>
                <picker-view-column>
                    <view
                        v-for="(item, index) in months"
                        :key="index"
                        :class="{ item: true, active_item: val[1] === index }"
                    >
                        {{ item.toString().padStart(2, '0') }}
                    </view>
                </picker-view-column>
                <picker-view-column>
                    <view
                        v-for="(item, index) in days"
                        :key="index"
                        :class="{ item: true, active_item: val[2] === index }"
                    >
                        {{ item.toString().padStart(2, '0') }}
                    </view>
                </picker-view-column>
            </picker-view>
            <view class="operation">
                <button class="cancel_btn" @tap="picker.close()">取消</button>
                <button class="confirm_btn" @tap="confirm">确定</button>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';

const props = withDefaults(
    defineProps<{
        modelValue: [string, string];
        disabled?: boolean;
    }>(),
    {
        disabled: false,
    },
);
const emit = defineEmits(['update:modelValue', 'confirm']);

const startTime = ref('');
const endTime = ref('');

const active = ref(0); // 0 开始时间 1 结束时间

const picker = ref();

const val = ref<number[]>([0, 0, 0]);

const date = new Date();
const now_year = date.getFullYear();
const now_month = date.getMonth() + 1;
const now_day = date.getDate();

const years = ref<number[]>([]);

const months = ref<number[]>([]);

const days = ref<number[]>([]);

// 年
const setYears = () => {
    for (let i = now_year; i <= 2054; i++) {
        years.value.push(i);
    }
};
// 月
const setMonths = (mixMonth?: number) => {
    months.value = [];
    for (let i = mixMonth; i <= 12; i++) {
        months.value.push(i);
    }
};
// 日
const setDays = (...args: number[]) => {
    days.value = [];
    let total = 30;
    if ([1, 3, 5, 7, 8, 10, 12].includes(args[0])) {
        total = 31;
    } else if ([4, 6, 9, 11].includes(args[0])) {
        total = 30;
    } else {
        total = (args[1] % 4 === 0 && args[1] % 100 !== 0) || args[1] % 400 === 0 ? 29 : 28;
    }
    if (args.length === 3) {
        for (let i = args[2]; i <= total; i++) {
            days.value.push(i);
        }
    } else {
        for (let i = 1; i <= total; i++) {
            days.value.push(i);
        }
    }
};

// 有选中值时
const setVal = async (time: string) => {
    const t = new Date(time);
    if (t.getFullYear() === now_year) {
        setMonths(now_month);
        t.getMonth() + 1 === now_month
            ? setDays(now_month, t.getFullYear(), now_day)
            : setDays(t.getMonth() + 1, t.getFullYear());
    } else {
        setMonths(1);
        setDays(t.getMonth() + 1, t.getFullYear());
    }
    const yidx = years.value.indexOf(t.getFullYear());
    const midx = months.value.indexOf(t.getMonth() + 1);
    const didx = days.value.indexOf(t.getDate());

    await nextTick();
    val.value = [yidx, midx, didx];
};

async function change({ detail: { value } }: any) {
    const y = years.value[value[0]];
    let m = months.value[value[1]];
    let d = days.value[value[2]];
    let monthsIdx = 0;
    let daysIdx = 0;
    if (y === now_year) {
        setMonths(now_month);
        setDays(m, now_year, now_day);
        if (m === now_month) {
            setDays(now_month, now_year, now_day);
        } else {
            if (m < now_month) {
                setDays(m, now_year, now_day);
            } else {
                setDays(m, now_year);
            }
        }
        monthsIdx = months.value.findIndex((item: number) => item === m);
        value[1] = monthsIdx === -1 ? 0 : monthsIdx;
        daysIdx = days.value.findIndex((item: number) => item === d);
        value[2] = daysIdx === -1 ? 0 : daysIdx;
    } else {
        setMonths(1);
        setDays(m, y);
        value[1] = months.value.findIndex((item: number) => item === m);
        value[2] = days.value.findIndex((item: number) => item === d);
        await nextTick();
    }
    val.value = value;
    const time = `${years.value[val.value[0]]}-${months.value[val.value[1]]
        .toString()
        .padStart(2, '0')}-${days.value[val.value[2]].toString().padStart(2, '0')}`;
    if (active.value) {
        endTime.value = time;
    } else {
        startTime.value = time;
    }
}

// 切换开始结束
function handleClick(type: 0 | 1) {
    active.value = type;
    if (startTime.value && endTime.value) {
        type ? setVal(endTime.value) : setVal(startTime.value);
    }
}

function confirm() {
    if (!startTime.value) {
        uni.showToast({
            title: '请选择开始时间',
            icon: 'none',
        });
        return;
    }
    if (!endTime.value) {
        uni.showToast({
            title: '请选择结束时间',
            icon: 'none',
        });
        return;
    }
    if (new Date(startTime.value).getTime() >= new Date(endTime.value).getTime()) {
        uni.showToast({
            title: '结束时间大于开始时间',
            icon: 'none',
        });
        return;
    }
    emit('update:modelValue', [startTime.value, endTime.value]);
    picker.value.close();
    emit('confirm');
}

function open() {
    picker.value.open();
    active.value = 0;
    startTime.value = props.modelValue[0];
    endTime.value = props.modelValue[1];
    setYears();
    setMonths(now_month);
    setDays(now_month, now_year, now_day);
    if (startTime.value) {
        setVal(startTime.value);
    }
}
// onMounted(() => {
// 	for (let i = 2024; i <= 2054; i++) {
// 		years.value.push(i);
// 	}
// 	setMonths(12);

// });

defineExpose({
    open,
});
</script>

<style lang="scss" scoped>
.select {
    display: flex;
    align-items: center;
    justify-content: center;

    .demo-icon-xiala {
        width: 44rpx;
        height: 44rpx;
    }
}

.picker-view {
    height: 280rpx;
    margin: 30rpx 140rpx;

    .item {
        line-height: 56px;
        text-align: center;
        margin: 0 5rpx;
        font-size: 40rpx;
        color: #666666;
    }

    .active_item {
        color: #333;
        font-weight: 500;
        font-size: 48rpx;
    }
}

:deep(.active) {
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
}

.picker {
    box-sizing: border-box;
    height: 660rpx;
    width: 750rpx;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0rpx 0rpx;
    padding: 115rpx 30rpx 66rpx;
    position: relative;

    .title {
        position: absolute;
        top: 30rpx;
        left: 30rpx;
        z-index: 99;
        color: #333;
        font-weight: 500;
        font-size: 32rpx;
    }

    .demo-icon-guanbi {
        width: 56rpx;
        height: 56rpx;
        position: absolute;
        top: 24rpx;
        right: 24rpx;
    }

    .top {
        display: flex;
        align-items: center;

        .time {
            box-sizing: border-box;
            width: 280rpx;
            height: 75rpx;
            border-bottom: 1px solid #eee;
            font-size: 32rpx;
            color: #333;
            text-align: center;

            &.selected {
                font-weight: 700;
                color: #615dff;
            }
        }

        text {
            margin: 0 47rpx;
        }
    }

    .operation {
        display: flex;
        justify-content: center;
        position: absolute;
        padding-top: 16rpx;
        bottom: 60rpx;
        left: 4rpx;
        width: 100%;
        box-sizing: border-box;

        button::after {
            border: none;
        }

        .cancel_btn {
            width: 230rpx;
            height: 90rpx;
            color: #615dff;
            background-color: #ececff;
        }

        .confirm_btn {
            margin-left: 20rpx;
            height: 90rpx;
            width: 440rpx;
            color: #fff;
            background-color: #615dff;
        }
    }
}
</style>
