<template>
    <section class="max-w-xl m-auto h-screen bg-[#F7F8FA]">
        <div class="h-[269px]">
            <div class="bg-[url('@/assets/imgs/daily/daily-check-bg.png')] bg-cover h-[200px]">
                <div class="p-4">
                    <SvgIcon name="angle-left-circle" class="w-7 h-7 text-white" @click="$router.back" />
                </div>
                <div class="flex flex-row items-center justify-around mt-3">
                    <span class="text-white text-xl font-bold">{{ t('daily.title') }}</span>
                    <div>
                        <img src="@/assets/imgs/daily/daily-check-book.png" alt="" class="w-28 h-28" />
                    </div>
                </div>
            </div>
            <div class="relative">
                <div class="absolute -top-[28px] left-4 right-4 bg-white rounded-2xl">
                    <div class=" flex-grow h-[69px] flex flex-row items-center justify-around ">
                        <div class="flex flex-col items-center justify-center p-4 ">
                            <span class="text-md font-semibold text-black">{{ continues }}</span>
                            <span class="text-[#AEAEB2] text-ss">{{ t('daily.c') }}</span>
                        </div>
                        <div class="w-[1px] h-[40px] bg-gray-200"></div>
                        <div class="flex flex-col items-center justify-center p-4">
                            <span class="text-md font-semibold text-black">{{ accumulation }}</span>
                            <span class="text-[#AEAEB2] text-ss">{{ t('daily.a') }}</span>
                        </div>
                        <div class="w-[1px] h-[40px] bg-gray-200"></div>
                        <div class="flex flex-col items-center justify-center p-4">
                            <span class="text-md font-semibold text-black">{{ receivedReward }}</span>
                            <span class="text-[#AEAEB2] text-ss">{{ t('daily.r') }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="h-[305px] bg-white mx-4 rounded-2xl">
            <div class="border-b-[1px] border-gray-200 flex flex-row items-center justify-center p-3">
                <!-- <SvgIcon name="daily-left" class="w-8 h-8"></SvgIcon> -->
                <span class="text-[#F96825] font-semibold">{{ getCurrentMonthName() }}</span>
                <span class="text-black font-semibold ml-2">{{ currentYear }}</span>
                <!-- <SvgIcon name="daily-right" class="w-8 h-8"></SvgIcon> -->
            </div>
            <div class="grid grid-cols-7 mx-2 place-items-center mt-2 gap-4">
                <div v-for="week in weekNames" class="w-6 h-6 flex justify-center items-center">
                    <span class="text-ss text-[#AEAEB2]">{{ week }}</span>
                </div>
            </div>
            <!-- Dates -->
            <div class="grid grid-cols-7 gap-3 place-items-center mt-2 mx-2">
                <div v-for="day in days" :key="day.date" class="w-6 h-6 flex items-center justify-center"
                    :class="getDateClasses(day)">
                    <span class="text-[13px] 
                    font-medium">{{ day.date.getDate() }}</span>
                </div>
            </div>
        </div>
        <div class="mt-8 mx-4">
            <van-button block color="linear-gradient(90deg, #F70 0%, #FF4900 100%)" @click="handleDailySignIn" :disabled="disable">
                <span class="font-semibold text-base">{{ t('daily.btn') }}</span></van-button>
        </div>
    </section>
    <Success ref="successRef" />
    <Dialog ref="dialogRef" />
</template>

<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon.vue';
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import Success from '@/components/Success.vue';

const successRef = ref()
const dialogRef = ref()

const { t } = useI18n()

import { userCheckIn, getUserCheckIn } from '@/api/checkIn'

const getCurrentMonthName = () => {
    const date = new Date();
    return new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);
}

const weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const days = reactive<Array<{ date: Date, isSignedIn: boolean }>>([]);

const currentMonth = ref(new Date().getMonth());
const currentYear = ref(new Date().getFullYear());
const signedInDates = ref([])
const continues = ref(0)
const accumulation = ref(0)
const receivedReward = ref(0)
const disable = ref(false)

const getDateClasses = (day: { date: Date, isSignedIn: boolean }) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    // Check if the day is in the past or is today
    const isInPastOrToday = day.date <= today;
    // Base class for not yet arrived days
    let classes = {};
    // If the day has already arrived
    // Check if the day is today
    const isToday = day.date.getTime() === today.getTime();

    if (isInPastOrToday) {
        classes = {
            'bg-[#F2F2F7] text-[#AEAEB2] rounded-full': !day.isSignedIn && !isToday,
            'bg-[#F96825] rounded-full text-white': day.isSignedIn,
            'border-2 border-[#F96825] rounded-full bg-white': isToday && !day.isSignedIn
        };
    }

    return classes;
}

const handleDailySignIn = async () => {
    const res = await userCheckIn()
    console.log('handleDailySignIn', res)
    if (res.code === 0) {
        successRef.value.open()
        await initUserCheckIn()
    } else {
        if (res.code === 1004220001) {
            dialogRef.value.open({
                type: 'warning',
                content: t('daily.task_not_compiled'),
                showConfirmButton: true,
                showCancelButton: false,
                confirmText: t('common.confirm'),
            })
        }
    }
}

const initUserCheckIn = async () => {
    const checkInDates = await getUserCheckIn()
    // checkInDates 是有一个list，里面有时间戳，把他转为日期，并获取天数转为数组
    signedInDates.value = checkInDates.map((item: number) => {
        const date = new Date(item.signInDate)
        receivedReward.value += item.reward
        return date.getDate()
    })
    if(checkInDates.length > 0) {
        const lastRecord = checkInDates[checkInDates.length - 1]
        continues.value = lastRecord.continuousDays
        accumulation.value = lastRecord.totalDays
    }else{
        continues.value = 0
        accumulation.value = 0
    }

    // 今天是否已经签到
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    // 获取今天几号
    const date = today.getDate()
    const isTodaySignedIn = signedInDates.value.includes(today.getDate())
    disable.value = isTodaySignedIn
}

onMounted(async () => {
    await initUserCheckIn()
    for (let i = 1; i <= new Date(currentYear.value, currentMonth.value + 1, 0).getDate(); i++) {
        days.push({
            date: new Date(currentYear.value, currentMonth.value, i),
            isSignedIn: signedInDates.value.includes(i)
        });
    }


});

</script>