<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>
        <div class="footer">
            <v-btn :txt="state.open_btn.txt" :font-size="'17px'" :icon="true" :disabled="false" @onClick="clickBtn"
                :loading="state.btn_loading"></v-btn>
        </div>
    </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, sendCurrentTabMessage } from '@/uilts/chromeExtension.js'
import { reSetBindRepost } from '@/http/help.js'
import { guid } from '@/uilts/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 && changes.userInfo.newValue) {
        // let item = JSON.parse(changes.userInfo.newValue)
        state.btn_loading = false
        state.init()
    }
})
let to_start_time = new Date().getTime()
let now_time
const toStart = (req) => {
    now_time = new Date().getTime()
    if (now_time - to_start_time <= 1000) {
        return
    }
    to_start_time = now_time
    console.log('to_start_time', to_start_time)
    treasureStart({
        params: {
            postId: state.postId || '',
            inviteCode: state.invite_code || '',
            frontFollowRelJSON: JSON.stringify(state.usersFollowStatusList),
            time: new Date().getTime(),
            guid: guid(),
            channelCode: state.invite_channel
        }
    }).then((res) => {
        state.usersFollowStatusList = [];
        if (res.code == 0) {
            // state.page = '开奖页'
            state.init(() => {
                state.page = '邀请页'
                state.page_status = '显示开奖'
                state.btn_loading = false
            })
            state.start_task = res.data
            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 || state.iframeId != req.iframeId) {
                return
            }
            console.log('DO_TASK', req)
            if (req.task_type == 'createTweet1' && req.task_done == '否') {
                console.log('createTweet1', req)
                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 == 'createTweet1' && req.task_done == '是') {
                console.log('createTweet2', req)
                toStart(req);
                getChromeStorage('userInfo', (_userInfo) => {
                    if (_userInfo) {
                        sendCurrentTabMessage({
                            actionType: "IFRAME_API_GET_TWEET_USER_INFO_REQ",
                            data: {
                                screen_name: _userInfo.nickName,
                                tweetId: state.tweetId,
                                objectType: Report.objectType.repostSuccess,
                                iframeId: state.iframeId
                            }
                        })
                    }
                })
            }
            break
        case 'CONTENT_API_GET_TWEET_USER_INFO_RES':
            if (state.iframeId != req.iframeId) {
                return;
            }
            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 && state.iframeId == req.iframeId) {

                if (req.type == 'pre_repost') {
                    // 发送埋点
                    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))

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

                    // 一键三连
                    sendCurrentTabMessage({
                        actionType: "IFRAME_TWITTER_API_DO_TASK",
                        task_data: {
                            tweet_Id: state.tweetId,
                            tweet_text: state.rePostTweetContent
                        },
                        task_type: 'tasks',
                        tasks: state.tasks,
                        iframeId: state.iframeId
                    })

                    // double like
                    sendCurrentTabMessage({
                        actionType: "IFRAME_TWITTER_API_DO_TASK", task_data: {
                            tweet_Id: state.detail.srcContentId
                        }, task_type: 'like',
                        iframeId: state.iframeId
                    })
                }
            }
            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 = []

    // rootTwitterName  上报原始发布者的name
    // fatherTwitterName 上报分享者的name or 原始发布者的name
    // isFatherTwitterFans 在原始链接或分享链接 邀请者非自己
    // isRootTwitterFans 在原始链接或分享链接 发布者非自己

    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.fatherTwitterName = state.detail.postUserInfo.nickName
    }
    params.rootTwitterName = state.detail.postUserInfo.nickName
    let names = []
    if (state.detail.inviteUserInfo) {
        if (state.detail.inviteUserInfo.uid != global_userInfo.uid) {
            // isFatherTwitterFans = inviteUserInfo.nickName 的关注关系
            // 发送事件校验关注关系
            names.push({
                type: 'invite',
                name: state.detail.inviteUserInfo.nickName
            })
        }
    } else {
        if (state.detail.postUserInfo.uid != global_userInfo.uid) {
            names.push({
                type: 'invite',
                name: state.detail.postUserInfo.nickName
            })
        }
    }

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

    sendCurrentTabMessage({
        actionType: "IFRAME_API_GET_TWEET_USER_FOLLOW_STATUS",
        data: {
            userList: names,
            tweetId: state.tweetId
        },
        type: 'pre_repost',
        iframeId: state.iframeId
    })
    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() {
    global_userInfo = await state.checkIsLogin()
    if (!global_userInfo || !global_userInfo.uid) {
        return
    }
    if (state.cover_status == '奖励已被领光') {
        Report.reportLog({
            pageSource: Report.pageSource.expiredPage,
            businessType: Report.businessType.buttonClick,
            objectType: Report.objectType.getMoreGiveaway,
            postId: state.postId,
            shareLinkId: state.invite_code,
            currentInvitedNum: state.inviteCount,
            redPacketType: Report.redPacketType.treasure
        });

        window.open('https://twitter.com/search?q=%23denet');
        return
    }
    state.btn_loading = true

    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
    });

    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
            state.invite_channel = res.channel ? window.atob(res.channel) : '';
        }
        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) {
        sendCurrentTabMessage({
            actionType: "IFRAME_API_GET_TWEET_USER_FOLLOW_STATUS",
            data: {
                userList: userList,
                tweetId: state.tweetId,
            },
            iframeId: state.iframeId
        })
    }
}

</script>
<style lang="scss" scoped>
.cover {
    position: relative;
    width: 375px;
    height: 580px;
    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: 94px;
        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: 30px;
        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: #FFFFFF;
            opacity: 0.6;
        }
    }

    .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.6;
        }
    }

    .box {
        text-align: center;
        position: absolute;
        width: 100%;
        bottom: 155px;

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

    }

    .mark {
        position: absolute;
        bottom: 84px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;

        img {
            margin-right: 9px;
        }

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

        }
    }

    .footer {
        width: 100%;
        position: absolute;
        bottom: 16px;
    }
}
</style>
