<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { cssAssetUrl } from '@/commons/assets.ts'
import MobileStage from '@/components/MobileStage.vue'
import { useGameSocket, joinSharedRoom, sendGameMessage, userJoinStatus } from '@/composables/useGameSocket'
import LoadingView from './views/LoadingView.vue'
import PlayingView from './views/PlayingView.vue'
import ScoreView from './views/ScoreView.vue'
import { $getWechat, $toast } from '@/commons/utils.ts'
import { playGame1Music } from '@/commons/music'

type GameView = 'loading' | 'playing' | 'score'

const imageUrls = {
    bg: cssAssetUrl('game1/bg.png'),
    bg2: cssAssetUrl('game1/bg2.png'),
    logo: cssAssetUrl('logo.png'),
    title: cssAssetUrl('game1/title.png'),
    avatar: cssAssetUrl('avatar-yellow.png'),
    gu: cssAssetUrl('game1/gu.png'),
    clock: cssAssetUrl('game1/clock.png'),
    gu01: cssAssetUrl('game1/gu01.png'),
    gu02: cssAssetUrl('game1/gu02.png'),
    gu03: cssAssetUrl('game1/gu03.png'),
    scoreBg: cssAssetUrl('game1/score-bg.png'),
    back: cssAssetUrl('game1/back.png'),
    replay: cssAssetUrl('game1/replay.png'),
    close: cssAssetUrl('game1/close.png'),

    rule: cssAssetUrl('game1/rule.png')
}

const wechat = $getWechat()
const currentView = ref<GameView>('loading')
const countdownInterval = ref(60)
const isDivDescVisible = ref(false)
const tick = ref(0)  //点击次数
const rank = ref(0)  //排名
const guFrames: [string, string, string] = [imageUrls.gu01, imageUrls.gu02, imageUrls.gu03]
const currentGu = ref(imageUrls.gu01)
const isGuPlaying = ref(false)
const token = ref(wechat?.token ?? '')
const nickname = ref(wechat?.nickname ?? '')
const avatar = ref(wechat?.avatar ?? '')
const showGameRule = ref(true)

const mobileStageRef = ref<InstanceType<typeof MobileStage> | null>(null)
const _offSocketMessage = ref<(() => void) | undefined>()
let guFrameTimer: ReturnType<typeof window.setTimeout> | undefined
let gameCountdownTimer: ReturnType<typeof window.setTimeout> | undefined

const confirmRefresh = (event: BeforeUnloadEvent) => {
    event.preventDefault()
    event.returnValue = ''
}

function setDivDescVisible(visible: boolean) {
    isDivDescVisible.value = visible
}

function stopGameCountdown() {
    if (gameCountdownTimer) {
        window.clearTimeout(gameCountdownTimer)
        gameCountdownTimer = undefined
    }
}

function submitScore(save: boolean = false) {
    //最后提交保存在数据库中
    if (save) {
        //item_num 游戏项目(1到6)
        //wechat 原始token
        sendGameMessage('submit_score_save', {
            score: tick.value,
            wechat: wechat.token_origin,
            item_num: 1,
            nickname: wechat.nickname,
            avatar: wechat.avatar,
            rank: rank.value,
        })
    } else {
        sendGameMessage('submit_score', { score: tick.value })
    }
}

function startGameCountdown(seconds = 60) {
    stopGameCountdown()
    countdownInterval.value = seconds
    setDivDescVisible(true)

    const tickCountdown = () => {
        countdownInterval.value -= 1

        if (countdownInterval.value <= 0) {
            countdownInterval.value = 0
            gameCountdownTimer = undefined
            setDivDescVisible(false)
            submitScore(true)
            showScoreView()
            return
        }

        gameCountdownTimer = window.setTimeout(tickCountdown, 1000)
    }

    gameCountdownTimer = window.setTimeout(tickCountdown, 1000)
}

function resetToLoadingView() {
    stopGameCountdown()
    if (guFrameTimer) {
        window.clearTimeout(guFrameTimer)
        guFrameTimer = undefined
    }
    tick.value = 0
    rank.value = 0
    countdownInterval.value = 60
    currentGu.value = guFrames[0]
    isGuPlaying.value = false
    userJoinStatus.value = false
    currentView.value = 'loading'
    setDivDescVisible(false)
}

function startGameView() {
    stopGameCountdown()
    tick.value = 0
    currentGu.value = guFrames[0]
    currentView.value = 'playing'
    startGameCountdown()
}

function showScoreView() {
    stopGameCountdown()
    setDivDescVisible(false)
    currentView.value = 'score'
}

const touchHandler = () => {
    if (isGuPlaying.value) {
        return
    }

    tick.value += 5
    submitScore()
    playGame1Music();
    isGuPlaying.value = true

    let frameIndex = 0
    const playNextFrame = () => {
        currentGu.value = guFrames[frameIndex] ?? imageUrls.gu01
        frameIndex += 1

        if (frameIndex >= guFrames.length) {
            guFrameTimer = window.setTimeout(() => {
                currentGu.value = guFrames[0]
                isGuPlaying.value = false
                guFrameTimer = undefined
            }, 200)
            return
        }

        guFrameTimer = window.setTimeout(playNextFrame, 200)
    }

    playNextFrame()
}

if (wechat) {
    const gameId = 'game1';
    const { offSocketMessage } = useGameSocket({
        gameId,
        auth: {
            userid: wechat.token,
        },
        onConnect: () => {
            window.setTimeout(() => {
                const joined = joinSharedRoom(nickname.value, token.value, avatar.value, gameId)
            }, 200)
        },
        onGameStart: async () => {
            showGameRule.value = false;
            await mobileStageRef.value?.startCountdown()
            startGameView()
        },
        onScoreSubmitted: (is_save, data) => {
            if (!is_save) {//非保存状态下
                const nextRank = Number(typeof data === 'object' ? data?.rank : data)
                if (Number.isFinite(nextRank) && nextRank > 0) {
                    rank.value = nextRank
                }
            }
        },
        onRescoreSubmitted: (_recount) => {
            submitScore(true);
        },
        onGameRecover: (data) => {
            const recoveredRank = Number(data?.rank)
            const recoveredScore = Number(data?.score)
            const recoveredSeconds = Number(data?.remainingSeconds)

            rank.value = Number.isFinite(recoveredRank) && recoveredRank > 0 ? recoveredRank : 0
            tick.value = Number.isFinite(recoveredScore) && recoveredScore > 0 ? recoveredScore : 0
            showGameRule.value = false
            // showGameRank.value = false
            currentView.value = 'playing'
            startGameCountdown(
                Number.isFinite(recoveredSeconds) && recoveredSeconds > 0 ? recoveredSeconds : 0,
            )
        },
        onRoomClosed: () => {
            stopGameCountdown()
            currentView.value = 'loading'
            setDivDescVisible(false)
            // alert('管理员关闭了游戏房间')
            $toast('管理员关闭了游戏房间')
        },
        onRoomBack: () => {
            resetToLoadingView()
            window.setTimeout(() => {
                joinSharedRoom(nickname.value, token.value, avatar.value, gameId)
            }, 200)
        },
    })
    _offSocketMessage.value = offSocketMessage
}

onMounted(() => {
    document.title = '互动游戏 - 击鼓齐福'
    if (token.value) {
        window.addEventListener('beforeunload', confirmRefresh)
    }
})

onBeforeUnmount(() => {
    _offSocketMessage.value?.()
    if (guFrameTimer) {
        window.clearTimeout(guFrameTimer)
    }
    stopGameCountdown()
    if (token.value) {
        window.removeEventListener('beforeunload', confirmRefresh)
    }
})

const showGameRuleHandler = () => {
    showGameRule.value = !showGameRule.value;
}
</script>

<template>
    <MobileStage v-if="token" :showGameRule="showGameRule" ref="mobileStageRef"
        :background="`${imageUrls.bg} center/cover`">
        <template #gameRule>
            <div class="rule-container">
                <div class="rule-txt-container">
                    <div class="rule-title">游戏规则</div>
                    <div class="rule-txt">
                        1.主持人开赛即可点击鼓面，单次点击得 5 分;<br />
                        2.限时比拼手速，结束后按积分排名;<br />
                        3.高分用户有机会领取新疆福彩定制周边;<br />
                        4.禁止外挂，作弊，违规账号取消成绩与领奖资格;<br /><br />
                        祝您游戏愉快！
                    </div>
                    <div class="rule-close" @click="showGameRuleHandler"></div>
                </div>
            </div>
        </template>
        <LoadingView v-if="currentView === 'loading'" :image-urls="imageUrls" :user-join-status="userJoinStatus"
            @touchGameRule="showGameRuleHandler" />
        <PlayingView v-else-if="currentView === 'playing'" :image-urls="imageUrls" :tick="tick" :rank="rank"
            :current-gu="currentGu" :countdown-interval="countdownInterval" :is-div-desc-visible="isDivDescVisible"
            @touch="touchHandler" />
        <ScoreView v-else :image-urls="imageUrls" :rank="rank" :tick="tick" />
    </MobileStage>
    <div v-else style="text-align: center; width: 100vw; height: 100vh; line-height: 30; font-size: 20px;">
        请使用微信扫码进入游戏
    </div>
</template>
<style scoped>
.rule-container {
    .rule-txt-container {
        background: v-bind('imageUrls.rule') center / cover no-repeat;
        width: 692px;
        height: 797px;
        margin-top: -20%;
        transform: scale(0.5);

        .rule-title {
            text-align: center;
            color: white;
            font-weight: bold;
            font-size: 26pt;
            line-height: 50pt;
            letter-spacing: 4px;
        }

        .rule-txt {
            font-size: 26pt;
            padding: 40px;
            margin-top: 10px;
            color: #AA0000;
        }
    }

    .rule-close {
        width: 57px;
        height: 57px;
        background: v-bind('imageUrls.close') center / cover no-repeat;
        transform: translateX(-50%) scale(1.4);
        position: absolute;
        top: 0;
        left: 100%;
    }
}
</style>
