<template>
    <v-cover v-if="state.page == '封面页'"></v-cover>
    <v-invite v-if="state.page == '邀请页'"></v-invite>
    <v-result v-if="state.page == '开奖页'"></v-result>

    <open-box v-show="state.open_box.show"></open-box>
    <v-toast :show="state.toast.show" :txt="state.toast.txt" :has_icon="state.toast.has_icon"></v-toast>
    <div v-show="state.loading_redbag" class="redbag">
        <img :src="require('@/assets/img/icon-loading-redbag.png')" alt />
    </div>

</template>
<script setup>
import { reactive, provide, onMounted, ref } from 'vue'
import VCover from '@/view/iframe/treasure-hunt/cover.vue'
import VInvite from '@/view/iframe/treasure-hunt/invite.vue'
import VResult from '@/view/iframe/treasure-hunt/result.vue'
import { inviteDetail, treasureDetail, treasureOpen } from '@/http/treasure.js'
import { reSetBindTwtterId, reSetBindPostContent, reSetBindRepost } from '@/http/help.js'
import { getQueryString } from '@/uilts/help'
import { getChromeStorage, sendCurrentTabMessage } from '@/uilts/chromeExtension.js'
import VToast from '@/view/iframe/treasure-hunt/components/toast.vue'
import OpenBox from '@/view/iframe/treasure-hunt/components/open-box.vue'
import Report from "@/log-center/log"

let state = reactive({
    loading_redbag: true,
    page: '',
    page_status: '',
    detail: {},
    oldDetail: {},
    btn_loading: false,
    timer: null,
    open_box: {
        showed: false,
        show: false,
        clicked: false,
        data: {}
    },
    open_btn: {
        txt: '',
        disabled: false
    },
    dialog: {
        show: false,
    },
    start_task: {},
    toast: {},
    iframeId: ''
})
let global_refresh = ref(false)
provide('global_refresh', global_refresh)
provide('state', state)

let params = {}
onMounted(() => {
    params = JSON.parse(getQueryString('params') || '{}')
    state.iframeId = getQueryString('iframeId') || ''
    state.postId = params.post_Id || ''
    state.tweetId = params.tweet_Id || ''
    state.invite_code = params.invite_code || ''
    state.page_type = params.page_type || ''

    state.init();
    onRuntimeMsg();
})

state.checkIsLogin = () => {
    return new Promise((resolve) => {
        getChromeStorage('userInfo', (_userInfo) => {
            if (!_userInfo) {
                state.btn_loading = true
                setTimeout(() => {
                    state.btn_loading = false
                }, 3000)
                chrome.runtime.sendMessage({ actionType: "POPUP_LOGIN", data: "" })
                resolve(_userInfo)
            } else {
                resolve(_userInfo)
            }
        })
    })
}

state.init = (callback) => {
    if (params.page_type == '邀请链接') {
        // 邀请链接
        inviteDetail({
            params: {
                inviteCode: params.invite_code
            }
        }).then((res) => {
            if (res.code == 0) {
                state.loading_redbag = false
                handleCommon(res, callback)
                // 绑定repostSrcContentId
                if (!res.data.repostSrcContentId) {
                    reSetBindRepost({
                        inviteCode: state.invite_code,
                        tweetId: state.tweetId
                    })
                }
            }
        })

    } else if (params.page_type == '原始链接') {
        // 原始链接
        treasureDetail({
            params: {
                postId: params.post_Id
            }
        }).then((res) => {
            if (res.code == 0) {
                state.loading_redbag = false
                handleCommon(res, callback)
                // 原始链接绑定post content
                if (!res.data.postSrcContent) {
                    sendCurrentTabMessage({
                        actionType: "GET_CONTENT_BY_TWITTER_ID",
                        data: {
                            tweet_Id: state.tweetId
                        }
                    })
                }
            }
        })
    }
}

const reportOpenBoxLog = () => {
    if (state.open_box.showed) {
        Report.reportLog({
            businessType: Report.businessType.pageView,
            pageSource: Report.pageSource.openTreasurePage,
            redPacketType: Report.redPacketType.treasure,
            shareLinkId: state.invite_code,
            myShareLinkId: state.detail.inviteCopyUrl,
            currentInvitedNum: state.inviteCount,
            postId: state.postId
        });
        state.open_box.showed = false
    }
    if (state.open_box.clicked) {
        Report.reportLog({
            businessType: Report.businessType.buttonClick,
            pageSource: Report.pageSource.openTreasurePage,
            objectType: Report.objectType.nextButton,
            redPacketType: Report.redPacketType.treasure,
            shareLinkId: state.invite_code,
            myShareLinkId: state.detail.inviteCopyUrl,
            currentInvitedNum: state.inviteCount,
            postId: state.postId
        });
        state.open_box.clicked = false
    }
}

const handleCommon = (res, callback) => {
    state.detail = res.data
    state.postId = state.detail.postId
    reportOpenBoxLog()
    try {
        state.tasks = JSON.parse(state.detail.startCondition)
        let follows = state.tasks.filter((item) => { return item.type == 1 })
        if (follows.length) {
            state.follows = follows[0].relatedUsers
        }
    }
    catch (error) {
        console.error('catch', error)
    }
    if (!res.data.srcContentId) {
        reSetBindTwtterId({
            postId: state.postId || '',
            tweetId: state.tweetId || ''
        }, () => {
            sendCurrentTabMessage({
                actionType: "IFRAME_API_GET_TWEET_USER_INFO_REQ",
                data: {
                    screen_name: state.detail.postUserInfo.nickName,
                    tweetId: state.tweetId,
                    objectType: Report.objectType.tweetPostBinded
                }
            })
            state.init()
        })
    }
    handleStatus(callback)
}
let silver_open_box_big = require('@/assets/img/icon-silver-open-box-big.png')
let gold_open_box_big = require('@/assets/img/icon-gold-open-box-big.png')

state.refreshInit = () => {
    state.init(() => {
        global_refresh.value = true
        setTimeout(() => {
            global_refresh.value = false
        }, 1000)
    })
}

state.treasureOpen = () => {
    treasureOpen({
        params: {
            postId: state.postId,
            treasureId: state.treasureId,
        }
    }).then((res) => {
        state.btn_loading = false
        if (res.code == 0) {
            // icon
            for (let i in state.boxs) {
                if (state.boxs[i].id == state.treasureId) {
                    if (i > 0) {
                        state.open_box.icon = gold_open_box_big
                    } else {
                        state.open_box.icon = silver_open_box_big
                    }
                    break
                }
            }
            state.open_box.show = true
            state.open_box.showed = true
            state.open_box.data = res.data

            state.refreshInit()
        } else {
            switch (String(res.code)) {
                case '2037':
                    state.dialog.show = true
                    break;
                case '2203':
                    state.toast.txt = 'You have already opened the treasure chest'
                    state.toast.show = true
                    break
                case '2208':
                    state.toast.txt = 'No treasure chests to open'
                    state.toast.show = true
                    break
                default:
                    state.toast.txt = 'System Error'
                    state.toast.show = true
                    break
            }
            state.toast.has_icon = false
            setTimeout(() => {
                state.toast.show = false
            }, 2000)

            state.refreshInit()
        }
    }).catch(() => {
        state.btn_loading = false
    })
}

const handleStatus = (callback) => {
    // 如果 夺宝状态 = 未开始
    //   显示未开始页面
    // 如果 夺宝状态 = 进行中
    //   如果 夺宝参与状态 = 未参与夺宝
    //      显示封面页
    //   如果 夺宝参与状态 = 已参与夺宝
    //      显示邀请页
    // 如果 夺宝状态 = 已结束
    //  显示结束页面

    let { status, joinStatus } = state.detail || {}
    // 如果 夺宝状态 = 未开始
    if (status == 0) {
        // 未做处理
    }

    // 如果 夺宝状态 = 进行中
    else if (status == 1) {
        // 如果 夺宝参与状态 = 未参与夺宝
        if (joinStatus == 0) {
            // 显示封面页
            state.page = '封面页'
            state.cover_status = '有邀请人'
            state.open_btn.txt = 'Start'
            // state.cover_status = '无邀请人'
            // state.cover_status = '奖励已被领光'
        }
        // 如果 夺宝参与状态 = 已参与夺宝
        else if (joinStatus == 1) {
            if (state.page_show != '总邀请者页') {
                state.page = '邀请页'
            }
        }
    }
    // 如果 夺宝状态 = 已结束
    else {
        state.open_btn.txt = 'Look for more treasures'
        state.page = '封面页'
        state.cover_status = '奖励已被领光'
        state.btn_loading = false
        return
    }
    callback && callback()
}

function onRuntimeMsg() {
    chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
        switch (req.actionType) {
            case 'CONTENT_GET_TWEET_TXT':
                if (req.data.tweet_Id == state.tweetId && !state.detail.postSrcContent) {
                    state.detail.postSrcContent = req.data.txt
                    reSetBindPostContent({
                        postId: state.postId || '',
                        postSrcContent: req.data.txt,
                    })
                }
                break
            case 'CONTENT_API_GET_TWEET_USER_INFO_RES':
                let twitterFans = 0;
                let { user } = req.data || {};
                if (user && user.result && user.result.legacy) {
                    let legacy = user.result.legacy;
                    twitterFans = legacy ? legacy.followers_count : 0;
                }
                if (state.tweetId == req.tweetId && req.objectType == Report.objectType.tweetPostBinded) {
                    Report.reportLog({
                        objectType: Report.objectType.tweetPostBinded,
                        twitterFans: twitterFans,
                        redPacketType: Report.redPacketType.treasure,
                        postId: state.postId
                    });
                }
                break;
        }
        sendResponse && sendResponse();
    })
}
</script>
<style lang="scss" >
html,
body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .redbag {
        z-index: 222;
        text-align: center;
        width: 375px;
        height: 580px;
        position: fixed;
        top: 0;
        left: 0;
        user-select: none;

        img {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -65px;
            margin-left: -65px;
            width: 130px;
            height: 130px;
        }
    }

}
</style>
