<template>
    <!-- 封面页 -->
    <div class="cover" v-show-log="state.log_show">
        <v-head :left-data="state.detail.postUserInfo || null"></v-head>
        <div class="waring" v-if="state.cover_status == '奖励已被领光'">
            <div>All treasures</div>
            <div>are hunted</div>
        </div>
        <!-- 邀请人 -->
        <template v-else>
            <div class="invite"
                v-if="state.detail.inviteUserInfo && state.detail.inviteUserInfo.nickName != state.detail.postUserInfo.nickName">
                <img :src="state.detail.inviteUserInfo.avatarUrl" alt="" />
                <span>@{{ state.detail.inviteUserInfo.nickName }} invites you</span>
            </div>
            <div class="in-invite" v-else></div>
            <div class="treasure">
                <component-zoom width="335" fontSize="34" style="margin:0 auto;">
                    <span>Treasure</span>
                    <span>${{ toLast(state.detail.amountUsdValue, 2) }}</span>
                </component-zoom>
            </div>
            <div class="gain" v-if="Number(state.detail.upGainAmountValue) > 0">
                <component-zoom width="335" fontSize="34" style="margin:0 auto;">
                    <span>Your Gain Up to</span>
                    <span>$</span>
                    <span>{{ toLast(state.detail.upGainAmountValue, 3) }}</span>
                </component-zoom>
            </div>
            <div class="coin" v-if="state.detail.currencySymbol != 'USD'">
                <img :src="state.detail.currencyIconPath" alt="" />
                <span> {{ state.detail.currencySymbol }} equivalent (Crypto)</span>
            </div>
            <div class="coin" v-else></div>
        </template>

        <div class="box">
            <img :src="require('@/assets/img/icon-gold-close-box.png')" alt="" v-if="state.cover_status == '奖励已被领光'" />
            <img :src="require('@/assets/img/icon-treasure-box.png')" alt="" v-else />
        </div>
        <div class="mark" :style="{ 'opacity': state.cover_status == '奖励已被领光' ? '0' : '1' }">
            <img :src="require('@/assets/svg/icon-three-line.svg')" alt="" />
            <span>to Hunt Treasure</span>
        </div>
        <v-btn :txt="state.open_btn.txt" :font-size="'17px'" :icon="true" :disabled="false" @onClick="clickBtn"
            :loading="state.btn_loading"></v-btn>
    </div>

</template>
<script setup>
import { inject } from 'vue'
import VBtn from '@/view/iframe/treasure-hunt/components/btn.vue'
import VHead from '@/view/iframe/treasure-hunt/components/head.vue'
import ComponentZoom from "@/view/components/component-zoom.vue";
import { pageUrl } from "@/http/configAPI.js"
import Report from "@/log-center/log"
import { prepareStart, treasureStart } from '@/http/treasure.js'
import { getChromeCookie, removeChromeCookie, getChromeStorage, sendChromeTabMessage } from '@/uilts/chromeExtension.js'
import { reSetBindRepost } from '@/http/help.js'

let state = inject('state')
let global_userInfo
state.log_show = {
    businessType: Report.businessType.pageView,
    pageSource: Report.pageSource.pending_page,
    redPacketType: Report.redPacketType.treasure,
    shareLinkId: state.invite_code,
    postId: state.postId
}

chrome.storage.onChanged.addListener(changes => {
    if (changes.userInfo) {
        // let item = JSON.parse(changes.userInfo.newValue)
        state.btn_loading = false
        state.init()
    }
})

const toStart = (req) => {
    treasureStart({
        params: {
            postId: state.postId || '',
            inviteCode: state.invite_code || '',
            frontFollowRelJSON: JSON.stringify(state.usersFollowStatusList)
        }
    }).then((res) => {
        state.usersFollowStatusList = [];
        if (res.code == 0) {
            state.page = '开奖页'
            state.start_task = res.data
            state.btn_loading = false
            if (req.response) {
                let repost_tweetId = req.response.data.data.create_tweet.tweet_results.result.rest_id
                reSetBindRepost({
                    inviteCode: res.data.inviteCode,
                    tweetId: repost_tweetId
                })
            }
        } else {
            state.init()
        }

    }).catch((error) => {
        console.error(error)
    })
}

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
    switch (req.actionType) {
        case 'DO_TASK':
            if (!req.task_type || state.tweetId != req.tweet_Id) {
                return
            }
            if (!req.task_done && req.task_type == 'createTweet') {
                state.toast.txt = 'Seems something went wrong, please try again'
                state.toast.show = true
                state.toast.has_icon = false
                setTimeout(() => {
                    state.toast.show = false
                }, 2000)
            } else if (req.task_type == 'createTweet' && req.task_done) {
                toStart(req);
                getChromeStorage('userInfo', (_userInfo) => {
                    if (_userInfo) {
                        sendChromeTabMessage({
                            actionType: "IFRAME_API_GET_TWEET_USER_INFO_REQ",
                            data: {
                                screen_name: _userInfo.nickName,
                                tweetId: state.tweetId,
                                objectType: Report.objectType.repostSuccess
                            }
                        })
                    }
                })
            }
            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.repostSuccess) {
                Report.reportLog({
                    objectType: Report.objectType.repostSuccess,
                    twitterFans: twitterFans,
                    redPacketType: Report.redPacketType.treasure,
                    postId: state.postId,
                    shareLinkId: state.invite_code,
                });
            };
            break;
        case 'CONTENT_GET_TWEET_USER_FOLLOW_STATUS_RES':
            if (state.tweetId == req.tweetId) {

                if (req.type == 'pre_repost') {
                    // 发送埋点
                    console.log('getFollowStatus(req.data)', getFollowStatus(req.data))

                    let list = getFollowStatus(req.data)
                    log_pre_repost.names.forEach(item => {
                        list.forEach((item2) => {
                            if (item.name == item2.name) {
                                if (item.type == 'invite') {
                                    log_pre_repost.params.isFatherTwitterFans = item2.followed
                                }
                                if (item.type = 'post') {
                                    log_pre_repost.params.isRootTwitterFans = item2.followed
                                }
                            }
                        })
                    })

                    // 上报埋点
                    Report.reportLog(Object.assign({
                        objectType: Report.objectType.preRepost,
                    }, log_pre_repost.params))

                    // 做任务
                    chrome.tabs.getCurrent((tab) => {
                        // // 一键三连
                        chrome.tabs.sendMessage(tab.id, {
                            actionType: "IFRAME_TWITTER_API_DO_TASK",
                            task_data: {
                                tweet_Id: state.tweetId,
                                tweet_text: state.rePostTweetContent
                            },
                            task_type: 'tasks',
                            tasks: state.tasks,
                        })
                        // double like
                        chrome.tabs.sendMessage(tab.id, {
                            actionType: "IFRAME_TWITTER_API_DO_TASK", task_data: {
                                tweet_Id: state.detail.srcContentId
                            }, task_type: 'like'
                        })
                    })

                } else {
                    state.usersFollowStatusList = getFollowStatus(req.data);
                    // 上报埋点
                    logPreRepost()
                }
            }
            break;
    }
})

const getFollowStatus = (arr = []) => {
    let list = [];
    let userInfoList = arr;
    for (let i = 0; i < userInfoList.length; i++) {
        let item = userInfoList[i];
        if (item.user && item.user.result && item.user.result.legacy) {
            let legacy = item.user.result.legacy;
            list.push({
                name: legacy.screen_name,
                followed: legacy.following
            })
        }
    }
    return list
}

let log_pre_repost = {
    params: {},
    names: []
}
const logPreRepost = () => {
    log_pre_repost.params = {}
    log_pre_repost.names = []

    let params = {}
    params.postId = state.postId
    if (state.page_type == '邀请链接') {
        params.shareLinkId = state.invite_code
        params.fatherTwitterName = state.detail.inviteUserInfo.nickName
    } else if (state.page_type == '原始链接') {
        params.rootTwitterName = state.detail.postUserInfo.nickName
    }

    let names = []
    if (state.detail.inviteUserInfo && (state.detail.inviteUserInfo.uid != global_userInfo.uid)) {
        // isFatherTwitterFans = inviteUserInfo.nickName 的关注关系
        // 发送事件校验关注关系
        names.push({
            type: 'invite',
            name: state.inviteUserInfo.nickName
        })
    }

    if (state.detail.postUserInfo && (state.detail.postUserInfo.uid != global_userInfo.uid)) {
        // isRootTwitterFans = postUserInfo.nickName 的关注关系
        // 发送事件校验关注关系
        names.push({
            type: 'post',
            name: state.postUserInfo.nickName
        })
    }

    if (names.length > 0) {
        sendChromeTabMessage({
            actionType: "IFRAME_API_GET_TWEET_USER_FOLLOW_STATUS",
            data: {
                userList: names,
                tweetId: state.tweetId
            },
            type: 'pre_repost'
        })
    }
    log_pre_repost.params = params
    log_pre_repost.names = names
}

const toLast = (num, bit) => {
    let str = 1
    for (let i = 0; i < bit; i++) {
        str = str + '0'
    }
    let _num = Number(str)
    return Math.floor(Number(num) * _num) / _num
}

async function clickBtn() {
    let global_userInfo = await state.checkIsLogin()
    if (!global_userInfo) {
        return
    }
    if (state.cover_status == '奖励已被领光') {
        Report.reportLog({
            pageSource: Report.pageSource.pending_page,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.getMoreGiveaway,
            postId: state.postId
        });
        window.open('https://twitter.com/search?q=%23denet');
        return
    }


    Report.reportLog({
        businessType: Report.businessType.buttonClick,
        objectType: Report.objectType.open_button,
        pageSource: Report.pageSource.pending_page,
        redPacketType: Report.redPacketType.treasure,
        shareLinkId: state.invite_code,
        postId: state.postId
    });

    state.btn_loading = true
    setTimeout(() => {
        if (state.btn_loading == true) {
            state.btn_loading = false
        }
    }, 10000)

    // 获取邀请码
    getChromeCookie({
        name: state.postId,
        url: pageUrl,
    }, (res) => {
        if (res && res.inviteCode) {
            state.invite_code = res.inviteCode
        }
        startBtn()
    })
}

const startBtn = () => {
    // 获取文本
    prepareStart({
        params: {
            postId: state.postId || '',
            inviteCode: state.invite_code || ''
        }
    }).then((res) => {
        if (res.code == 0) {
            removeChromeCookie({
                name: state.postId,
                url: pageUrl,
            })

            state.rePostTweetContent = res.data.rePostTweetContent;
            getUsersFollowStatus();
        } else {
            state.init()
        }
    })
}

const getUsersFollowStatus = () => {
    let userList = state.follows;

    if (userList && userList.length) {
        sendChromeTabMessage({
            actionType: "IFRAME_API_GET_TWEET_USER_FOLLOW_STATUS",
            data: {
                userList: userList,
                tweetId: state.tweetId,
            }
        })
    }
}

</script>
<style lang="scss" scoped>
.cover {
    width: 375px;
    height: 500px;
    background: linear-gradient(179.96deg, #25180D 38.82%, #5E4025 55.4%, #876635 61.6%, #24180C 71.59%);
    border-radius: 20px;

    .head {
        padding: 10px;
        display: flex;
        align-items: center;

        img {
            width: 16px;
            height: 16px;
            border-radius: 100px;
        }

        span {
            color: #B69882;
            font-weight: 400;
            margin-left: 5px;
            font-size: 11px;
            flex-grow: 0;
        }
    }

    .waring {
        margin-top: 54px;
        font-weight: 900;
        font-size: 34px;
        color: #FFFFFF;
        text-align: center;
        opacity: 0.7;
        margin-bottom: 35px;
    }

    .in {
        height: 58px;
    }

    .in-invite {
        height: 28px;
        margin-top: 20px;
        margin-bottom: 10px;
    }

    .invite {
        background: rgba(255, 255, 255, 0.1);
        height: 28px;
        display: flex;
        align-items: center;
        margin: 0 auto;
        margin-top: 20px;
        margin-bottom: 10px;
        border-radius: 100px;
        width: fit-content;
        padding-right: 11px;


        img {
            width: 18px;
            height: 18px;
            border-radius: 100px;
            margin-left: 11px;
            margin-right: 6px;
        }

        span {
            color: #BE9F89;
        }
    }

    .treasure {
        text-align: center;
        height: 37px;
        display: flex;
        align-items: center;

        span {
            font-size: 34px;
            font-weight: 900;
            line-height: 40px;
        }

        span:first-child {
            color: #FFC83A;
            margin-right: 10px;
        }

        span:last-child {
            color: #FFFFFF;
        }
    }

    .gain {
        width: 100%;
        background: #332319;
        height: 37px;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: center;

        span {
            color: #fff;
            font-weight: 500;
            font-size: 16px;
            line-height: 16px;

        }

        span:first-child {
            font-size: 15px;
            line-height: 15px;
            margin-right: 10px;
        }

        span:last-child {
            margin-left: 2px;
            font-weight: 800;
            font-size: 24px;
            line-height: 24px;
        }
    }

    .coin {
        height: 17px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10px;

        img {
            width: 17px;
            height: 17px;
        }

        span {
            margin-left: 4px;
            font-weight: 400;
            font-size: 11px;
            line-height: 15px;
            color: #FFFFFF;

            opacity: 0.7;
        }
    }

    .box {
        text-align: center;

        img {
            width: 160px;
            height: 160px;
        }

    }

    .mark {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 24px;
        margin-bottom: 15px;

        span {
            font-weight: 500;
            font-size: 12px;
            line-height: 17px;
            color: #65C1FF;

        }
    }

}
</style>
