<template>
    <mobile-sub-layout :title="$t('promo.header.luckySpin')" :lineHeight="4" bgColor="#51090E">
        <!-- <LotteryWheel :prizes="prizeData.content.amounts" @spin-end="onSpinEnd" :target-index="4" /> -->
        <template #header-right>
            <theme-image src="@/static/spins/image_zpbtn_wh.png" mode="aspectFit" class="faq-img"
                @click="tipPopup.open()"></theme-image>
        </template>
        <view class="spin-container relative safe-area"
            :style="{ background: `top / cover no-repeat ${themeStore.theme.activity.bgImage}`, height: (appStore.windowInfo.screenHeight - 50) + 'px' }">

            <view class="spin-wraper relative">
                <LotteryWheel2 ref="wheel" :prizes="prizeData?.content?.amounts ?? []" @spin-end="onSpinEnd"
                    @spin-start="handleSpinStart" :target-index="targetIndex" :spin-count="spinCount" />
                <theme-image src="@/static/spins/image_jb2.png" mode="aspectFit" class="spin-deco-image"></theme-image>
            </view>
            <view class="my-amount flex-center">
                <text class="my-amount-title" :style="{ color: themeStore.theme.activity.lightApacity(0.8) }">My
                    Amount({{ rtime }})
                </text>
            </view>
            <view class="cash-total flex-center" :style="{ color: themeStore.theme.activity.normal }">
                <text class="text-linear amount-pre">₹</text>
                <text class="text-linear amount-num">{{ activityData.curAmount }}</text>
            </view>
            <view class="cash-out flex-center" :style="{ 'color': themeStore.theme.activity.inviteColor }"
                @click="getPrize">{{
                    t('promo.activity.cashout') }}</view>
            <view v-if="false" class="my-award">My Award: <text style="font-weight: bold; margin-left: 10rpx"
                    :style="{ color: themeStore.theme.activity.normal }">₹{{
                        activityData.curAmount }}</text></view>
            <view class="my-award flex justify-center items-center"
                :style="{ color: themeStore.theme.activity.normal }">
                My Invitation Code:
                <text style="font-weight: bold; margin-left: 10rpx">{{ agentInfo.inviteCode }}</text>
                <theme-image src="@/static/icon-copy.png" class="coby-btn" @click="handleCopy"></theme-image>
            </view>
            <view class="invite-btn flex-center"
                :style="{ 'background': `top / cover no-repeat ${themeStore.theme.deposit.bgImage}`, 'color': themeStore.theme.activity.inviteColor }"
                @click="handleInvite">{{ $t('promo.activity.inviteText') }}</view>
            <view class="end-time flex-center" :style="{ color: themeStore.theme.activity.player }">{{
                $t('promo.activity.endTime') }}: {{ endDate }}</view>
            <view class="lottery-record">
                <view class="lottery-inner relative">
                    <view class="record-title flex-center"
                        :style="{ 'background': `top / cover no-repeat ${themeStore.theme.activity.recordTitleBg}`, color: themeStore.theme.activity.normal }">
                        {{ $t('promo.activity.recordTitle') }}
                    </view>
                    <view class="record-list">
                        <view class="w-full record-item flex justify-between" v-for="item in recordData?.list"
                            :key="item.id">
                            <view class="record-left flex items-center">
                                <theme-image class="user-avatar"
                                    :style="{ borderColor: themeStore.theme.activity.normal }"
                                    src="@/static/icon-avatar.png" mode="aspectFit" />
                                <view class="player-name" :style="{ color: themeStore.theme.activity.player }">{{
                                    $t('promo.activity.playerName') }}{{ item.userId }}</view>
                            </view>
                            <view class="record-right">
                                <view class="send-amount" :style="{ color: themeStore.theme.activity.normal }">₹{{
                                    item.sendAmount }}</view>
                                <view class="send-time" :style="{ color: themeStore.theme.activity.recordTime }">{{ new
                                    Date(item.sendTime).toLocaleString('ind') }}</view>
                            </view>
                        </view>
                    </view>
                    <view class="pagination flex-center relative"
                        :style="{ color: themeStore.theme.activity.inviteColor }">
                        <view class="btn-prev flex-center" :class="{ 'disabled': !prev }"
                            :style="{ background: themeStore.theme.activity.normal }" @click="handlePage('prev')">
                            {{ $t('promo.activity.prev') }}
                        </view>
                        <view class="btn-prev flex-center" :class="{ 'disabled': !next }"
                            :style="{ background: themeStore.theme.activity.normal }" @click="handlePage('next')">
                            {{ $t('promo.activity.next') }}
                        </view>
                    </view>
                </view>
            </view>
            <view class="w-full safe-area" style="height: 40rpx;"></view>
        </view>

        <uni-popup ref="popup" type="center" :is-mask-click="false" mask-background-color="rgba(0, 0, 0, 0.7)"
            :safe-area="false">
            <view class="popup-content">
                <view class="gift-title">
                    <theme-image src="@/static/spins/bt_Cash_Everyday.png" mode="aspectFit"
                        class="gift-title-img"></theme-image>
                    <view class="gifts-wrap">
                        <view v-for="(item, index) in giftArr" :key="item"
                            class="flex-column items-center gift-item relative" @click="handleJoinAct(index)">
                            <theme-image v-if="index === toggledIndex" src="@/static/spins/image_zp_gift02.png"
                                mode="aspectFit" class="git-img-open"></theme-image>
                            <theme-image v-else src="@/static/spins/image_zp_gift.png" mode="aspectFit"
                                class="git-img-close"></theme-image>
                            <theme-image v-if="index === figireIndex" src="@/static/spins/image_zpshouzhi.png"
                                mode="aspectFit" class="gift-img-figure"></theme-image>
                            <text v-if="toggledIndex > -1" class="amount"
                                :style="{ color: themeStore.theme.activity.normal }">₹{{ item }}</text>
                        </view>
                    </view>
                    <view class="choose-gift w-full" :style="{ color: themeStore.theme.activity.popTip }">{{
                        $t('promo.activity.btnTip') }}</view>
                </view>
            </view>
        </uni-popup>
        <Congratulation ref="awardPopup" :prize-amount="prizeAmount" @close="handleClose" />
        <uni-popup ref="tipPopup" type="center" :is-mask-click="false" mask-background-color="rgba(0, 0, 0, 0.7)">
            <view class="tip-content relative">
                <view class="award-title flex-center"
                    :style="{ 'background': `top / cover no-repeat ${themeStore.theme.activity.recordTitleBg}`, color: themeStore.theme.activity.normal }">
                    {{ $t('promo.activity.tips') }}
                </view>
                <view class="tip-inner flex-center">

                    <theme-image class="popup-close-btn" src="@/static/mail/icon-popup-close.png" mode="aspectFit"
                        @click="tipPopup.close()" />
                    <view class="tip-box">
                        <view class="tip-txt">
                            1.When the cumulative amount reaches ₹200, you can apply for withdrawal.
                        </view>
                        <view class="tip-txt">
                            2.The activity lasts for 3 days. After the activity period ends,
                            accumulated
                            rewards will be reset, and the activity will start anew.
                        </view>

                        <view class="tip-txt">
                            3.After approval of the application, the bonus will be directly deposited into your wallet.
                        </view>

                        <view class="tip-txt">
                            4.The bonus requires a turnover of one time before withdrawal.
                        </view>

                        <view class="tip-txt">
                            5.The invitee needs to bind their phone number and link it with the inviter's invitation
                            code for
                            the referral to be considered successful.
                        </view>
                        <view class="tip-txt">
                            6.The interpretation of the activity is reserved by {{ appStore.appName }}. If you have any
                            questions,
                            please
                            contact customer service.
                        </view>
                    </view>
                </view>
            </view>
        </uni-popup>
        <Congratulation ref="awardPopup2" :prize-amount="totalAmount" />
        <BindPhonePop ref="bindPhonePop" />
    </mobile-sub-layout>

</template>


<script setup>
// import LotteryWheel from '@/pages/promo/components/LotteryWheel.vue';
import { computed, onMounted, ref, onBeforeUnmount } from 'vue';
import { usePromoStore } from '@/store/usePromoStore';
import LotteryWheel2 from './components/LotteryWheel2.vue';
import { getActivity, getJoinActApi, getLotteryRecord, getPrizeApi, getSpinResult } from '@/api/promo';
import { useThemeStore } from '@/store/useThemeStore';
import { useAppStore } from '@/store/useAppStore';
import { getAgentV2Home } from '@/api/earn';
import { copyText, shareWithSystem } from '@/module/utils/system';
import { formatTime } from '@/module/utils/conversionTime';
import { useI18n } from 'vue-i18n'
import Congratulation from '@/components/popup/Congratulation.vue';
import { useUserStore } from '@/store/useUserStore';
import BindPhonePop from '@/components/popup/BindPhonePop.vue';
const { t } = useI18n()
const promoStore = usePromoStore()
const themeStore = useThemeStore()
const appStore = useAppStore()
const userStore = useUserStore()
const prizeData = computed(() => {
    if (promoStore.promoList.length == 0) return {}
    const item = promoStore.promoList.find(item => item.type === 12)
    return item
})
const bindPhonePop = ref(null)
const tipPopup = ref(null)
const awardPopup = ref(null)
const awardPopup2 = ref(null)
const totalAmount = ref(0)
const wheel = ref(null)
const targetIndex = ref(-1)
const prizeAmount = ref(0)
const popup = ref(null)
const canJoin = ref(false)
const canSpin = ref(false)
const receivedGift = ref('')
const giftArr = ref([179, 139, 199, 219])
const spinCount = ref(0)
const activityData = ref({})
const toggledIndex = ref(-1);
const figireIndex = ref(0)
const timerId = ref(null)
const agentInfo = ref({})
const endDate = computed(() => {
    if (activityData.value?.endTime) {
        return formatTime(activityData.value.endTime)
    }
    return ''
})
const rtime = ref('')
const timerId2 = ref(null)
const isGetPrize = computed(() => {
    return activityData.value?.curAmount >= activityData.value?.prizeAmount
})
const remainSeconds = () => {
    if (activityData.value?.endTime) {
        const second = (new Date(activityData.value.endTime) - Date.now()) / 1000
        if (second <= 0) {
            clearInterval(timerId2.value)
            timerId2.value = null
            return
        }
        const hour = Math.floor(second / 3600)
        const minute = Math.floor((second % 3600) / 60)
        const sec = Math.floor(second % 60)
        rtime.value = `${hour}:${minute}:${sec}`
    }
}
const recordParam = ref({
    id: '',
    page: 1,
    size: 10
})
const recordData = ref({})
const prev = computed(() => {
    return recordData.value?.pageNum > 1
})
const next = computed(() => {
    return recordData.value?.hasNextPage
})


const handlePage = (type) => {
    switch (type) {
        case 'prev':
            if (prev.value) {
                recordParam.value.page--
                lotteryRecord()
            }
            break;
        case 'next':
            if (next.value) {
                recordParam.value.page++
                lotteryRecord()
            }
            break;
    }
}
const getPrize = async () => {
    if (!isGetPrize.value) {

        uni.showToast({
            title: t('promo.activity.noPrize'),
            icon: 'none'
        })
        return
    };
    await getPrizeApi({})
    totalAmount.value = activityData.value.curAmount
    awardPopup2.value?.open()

}
const onSpinEnd = (prize) => {
    console.log('Won prize:', prize);
    awardPopup.value?.open()
    getActJoinData()
    // spinCount.value--
};
const handleClose = () => {
    wheel.value?.reDraw()
}
const handleCopy = () => {
    const cid = appStore.channelId ?? '';
    const h5No = appStore.h5No ?? 1;

    const link = agentInfo.value.inviteLink.includes('?') ? agentInfo.value.inviteLink + `&cid=${cid}&h5No=${h5No}` : agentInfo.value.inviteLink + `?cid=${cid}&h5No=${h5No}&invite_code=${agentInfo.value.inviteCode}`;
    copyText({ text: link })
}
function handleInvite() {
    const cid = appStore.channelId ?? '';
    const h5No = appStore.h5No ?? 1;
    const link = agentInfo.value.inviteLink.includes('?') ? agentInfo.value.inviteLink + `&cid=${cid}&h5No=${h5No}` : agentInfo.value.inviteLink + `?cid=${cid}&h5No=${h5No}&invite_code=${agentInfo.value.inviteCode}`;
    console.log(link);
    const shareObj = {
        title: 'Let\'s play games together to earn money!',
        content: "Let's play games together to earn money!",
        url: link,
    }
    shareWithSystem(shareObj)
}
async function handleJoinAct(idx) {
    try {
        const { data } = await getActivity({})
        console.log(data);
        receivedGift.value = data
        giftArr.value[idx] = data
        clearInterval(timerId.value)
        timerId.value = null
        figireIndex.value = -1
        toggledIndex.value = idx
        setTimeout(() => {
            popup.value?.close()
        }, 1500)
        await getActJoinData()


    } catch (error) {

    }
}
async function getActJoinData() {
    try {
        const { data } = await getJoinActApi({})

        if (!data) {
            canJoin.value = true
            popup.value?.open()
            timerId.value = setInterval(() => {
                if (figireIndex.value > giftArr.value.length - 2) {
                    figireIndex.value = 0
                } else {
                    figireIndex.value++
                }
            }, 3000)
            wheel.value?.reDraw()
            return
        }
        activityData.value = data
        recordParam.value.id = data.id
        spinCount.value = data.leftCount
        wheel.value?.reDraw()
        remainSeconds()
        timerId2.value = setInterval(() => {
            remainSeconds()
        }, 1000)
    } catch (error) {
        console.error(error)
    }
}

async function startAward() {
    try {
        const { data } = await getSpinResult({})
        console.log(data);
        targetIndex.value = data?.prizeIndex
        prizeAmount.value = data?.prizeAmount
    } catch (error) {
        console.log(error);
    }
}
async function lotteryRecord() {
    if (!activityData.value?.id) return
    try {
        const { data } = await getLotteryRecord(recordParam.value)
        console.log(data);
        recordData.value = data
    } catch (error) {
        console.log(error);

    }
}
async function handleSpinStart() {
    if (!userStore.userInfo?.mobile) {
        bindPhonePop.value?.open()
        return
    }
    if (activityData.value?.leftCount > 0) {
        if (isGetPrize.value) return
        await startAward()
        wheel.value?.startSpin()
        return
    }
    uni.showToast({
        title: t('promo.activity.noChance'),
        icon: 'none'
    })
}
const getAgentHomeInfo = async () => {
    const { code, data } = await getAgentV2Home()
    if (code == 200) {
        agentInfo.value = data || {}
    }
}
onMounted(async () => {
    promoStore.getPromoList()
    await getActJoinData()
    getAgentHomeInfo()
    lotteryRecord()
})
onBeforeUnmount(() => {
    clearInterval(timerId.value ?? 0)
    clearInterval(timerId2.value ?? 0)
})
</script>
<style lang="scss">
::-webkit-scrollbar {
    width: 0;
    display: none;
}

.faq-img {
    width: 42rpx;
    height: 42rpx;
}

.spin-container {
    width: 100%;
    overflow-y: auto;

    .my-amount {
        font-size: 30rpx;
        padding: 24rpx 0;

        .my-amount-title {
            font-weight: 500;
            text-align: center;
        }
    }

    .cash-total {
        display: flex;
        align-items: baseline;
    }

    .cash-out {
        width: 275rpx;
        height: 73rpx;
        background: linear-gradient(180deg, #FFFBD1, #F6E07B, #C38F38, #E7B540);
        box-shadow: 0rpx 6rpx 0rpx 0rpx rgba(50, 12, 6, 0.5), 0rpx 2rpx 6rpx 0rpx #FFFFFF, 0rpx -2rpx 6rpx 0rpx #FFFFFF;
        border-radius: 19rpx;
        border: 2px solid #A60F00;
        margin: 10rpx auto;
    }

    .text-linear {
        background: -webkit-linear-gradient(-90deg, #F8EDAF, #FEE868, #b57c1a);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 64rpx;
        font-weight: 700;
    }

    .amount-pre {
        font-size: 36rpx;
        margin-right: 8rpx;
    }

    .spin-wraper {
        width: 100%;

        .spin-deco-image {
            width: 750rpx;
            height: 213rpx;
            position: absolute;
            left: 0;
            bottom: 0;
        }
    }

    .my-award {
        font-family: Roboto Flex;
        font-size: 32rpx;
        font-weight: 500;
        line-height: 38rpx;
        text-align: center;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: #FEBF05;
        margin-top: 26rpx;

        .coby-btn {
            width: 36rpx;
            height: 36rpx;
            margin-left: 20rpx;
        }
    }

    .invite-btn {
        width: 682rpx;
        height: 84rpx;
        border-radius: 0;
        font-size: 31rpx;
        font-weight: 700;
        color: #7A2500;
        margin: 0 auto;
        margin-top: 26rpx
    }

    .end-time {
        font-family: Roboto Flex;
        font-size: 28rpx;
        font-weight: 500;
        line-height: 28rpx;
        text-align: center;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: #CE3E47;
        margin-top: 18rpx
    }

    .lottery-record {
        background: linear-gradient(90deg, #F7A421, #FDF7AB, #F57F08);
        width: 680rpx;
        height: 480rpx;
        margin: 0 auto;
        border-radius: 19rpx;
        padding: 2px;
        margin-top: 62rpx;

        .lottery-inner {
            width: 100%;
            height: 100%;
            background-color: #440707;
            border-radius: 19rpx;
            padding: 60rpx 30rpx;

            .record-title {
                width: 460rpx;
                height: 69rpx;
                position: absolute;
                top: -35rpx;
                left: 50%;
                transform: translateX(-50%);
                font-family: Roboto;
                font-size: 14px;
                font-weight: 700;
                line-height: 14px;
                text-align: left;
                text-underline-position: from-font;
                text-decoration-skip-ink: none;
                color: #FEBF05;
                z-index: 10;
            }

            .pagination {
                position: absolute;
                left: 50%;
                transform: translateX(-50%);
                bottom: 10rpx;

                .btn-prev {
                    width: 100rpx;
                    height: 40rpx;
                    background: #FEBF05;
                    border-radius: 20rpx;
                    font-size: 24rpx;
                    font-weight: 700;
                    margin-right: 20rpx;
                }

                .disabled {
                    background: rgba(254, 192, 5, 0.7);
                }
            }

            .record-list {
                width: 100%;
                height: 100%;
                overflow-y: auto;

                .record-item {
                    margin-bottom: 20rpx;

                    .record-left {
                        .user-avatar {
                            width: 48rpx;
                            height: 48rpx;
                            border-radius: 50%;
                            border: 1px solid #FEBF05;
                        }

                        .player-name {
                            font-family: Roboto;
                            font-size: 14px;
                            font-weight: 400;
                            line-height: 14px;
                            text-align: left;
                            text-underline-position: from-font;
                            text-decoration-skip-ink: none;
                            color: #CE3E47;
                            margin-left: 10rpx;
                        }
                    }

                    .record-right {
                        display: flex;
                        flex-direction: column;
                        align-items: flex-end;

                        .send-amount {
                            font-family: Roboto;
                            font-size: 14px;
                            font-weight: 500;
                            line-height: 14px;
                            text-align: left;
                            text-underline-position: from-font;
                            text-decoration-skip-ink: none;
                            color: #FEBF05;
                        }

                        .send-time {
                            font-family: Roboto;
                            font-size: 10px;
                            font-weight: 400;
                            line-height: 10px;
                            text-align: left;
                            text-underline-position: from-font;
                            text-decoration-skip-ink: none;
                            color: #A62E36;
                            margin-top: 10rpx
                        }
                    }
                }
            }
        }
    }
}

.popup-content {
    width: 680rpx;
    height: 80%;
}

.gift-title-img {
    width: 669rpx;
    height: 95rpx;
}

.gifts-wrap {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: auto;
    grid-gap: 30rpx;
    margin-top: 57rpx;
}

.gift-item {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 350rpx;
    height: 352rpx;
}

.git-img-open {
    width: 350rpx;
    height: 352rpx;
}

.git-img-close {
    width: 206rpx;
    height: 239rpx;
}

.choose-gift {
    margin-top: 187rpx;
    text-align: center;
    font-weight: bold;
    font-size: 36rpx;
    color: #FFDF3FFF;
}

.gift-img-figure {
    width: 90rpx;
    height: 90rpx;
    position: absolute;
    right: 56rpx;
    bottom: 36rpx;
    animation: scaled 2s infinite;
}

.amount {
    position: absolute;
    bottom: 0rpx;
    left: 50%;
    transform: translateX(-50%);
    font-family: Roboto;
    font-weight: 400;
    font-size: 36rpx;
    color: #FED545;
}

@keyframes scaled {
    0% {
        transform: scale(1);
    }

    50% {
        transform: scale(1.2);
    }

    100% {
        transform: scale(1);
    }
}

.tip-content {
    width: 616rpx;
    height: 900rpx;
    background: linear-gradient(90deg, #F7A421, #FDF7AB, #F57F08);
    border-radius: 19rpx;
    padding: 2px;

    .award-title {
        width: 460rpx;
        height: 69rpx;
        position: absolute;
        top: -28rpx;
        left: 50%;
        transform: translateX(-50%);
        font-family: Roboto;
        font-size: 14px;
        font-weight: 700;
        line-height: 14px;
        text-align: left;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: #FEBF05;
    }

    .tip-inner {
        width: 100%;
        height: 100%;
        background-color: #440707;
        border-radius: 19rpx;
        padding: 60rpx 30rpx 30rpx 30rpx;



        .popup-close-btn {
            position: absolute;
            top: -10rpx;
            right: -10rpx;
            width: 42rpx;
            height: 42rpx;
        }

        .tip-box {
            font-size: 13px;
            color: #ffffff;
            width: 100%;
            height: 100%;
            overflow-y: auto;

            .tip-txt {
                margin-top: 10rpx;
            }
        }
    }
}
</style>