<!-- 红包任务页面 -->
<template>
    <div class="content">
        <!-- global-tip -->
        <global-tip :type="'1'"></global-tip>
        <!-- open -->
        <div v-show="state.status == 'opened'" class="opened">

            <div class="header"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top-1.svg')})` }">
                <!--  -->
                <img :src="require('@/assets/subject/001-icon-red-packet.svg')" alt="">
                <div class="txt">
                    <p>Complete tasks</p>
                    <p>to Draw Prizes</p>
                </div>
            </div>

            <div class="list">
                <template v-for="item, i in state.detail.taskCondition" v-bind:key="i">
                    <div class="item" v-if="item.type == 1 && item.relatedUsers && item.relatedUsers.length > 0">
                        <div class="item-content">
                            <div class="item-follow-title">
                                <img :src="require('@/assets/svg/icon-task-twitter.svg')" alt />
                                <!-- <img :src="require('@/assets/svg/icon-follow.svg')" alt /> -->
                                <div class="item-title">Follow</div>
                                <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                                    v-show="!state.done.follow && state.done.follow_red" />
                                <img v-if="state.done.follow" :src="require('@/assets/svg/icon-true.svg')" alt />
                                <div v-else class="btn" @click="clickFollowAll(item.relatedUsers, 'all')">Follow All
                                </div>
                            </div>
                            <div class="item-follow-area">
                                <template v-for="item2, i in item.relatedUsers" v-bind:key="i">
                                    <div class="item-follow" v-if="item2.finished">
                                        <span :class="{ finished: item2.finished }">@{{ item2.name }}</span>
                                        <img :src="require('@/assets/svg/icon-true-ed.svg')" alt />
                                    </div>
                                    <div class="item-follow" v-else @click="clickFollowAll([item2])">
                                        <span :class="{ finished: item2.finished }">@{{ item2.name }}</span>
                                        <img :src="require('@/assets/svg/icon-add.svg')" alt />
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                    <div class="item" v-if="item.type == 2">
                        <img :src="require('@/assets/svg/icon-task-twitter.svg')" alt />
                        <!-- <img :src="require('@/assets/svg/icon-like.svg')" alt /> -->
                        <div class="item-content">
                            <div class="item-title">Like</div>
                        </div>
                        <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                            v-show="!state.done.like && state.done.like_red" />
                        <img v-if="state.done.like" :src="require('@/assets/svg/icon-true.svg')" alt />
                        <div v-else class="btn" @click="clickLikeBtn">Like</div>
                    </div>
                    <div class="item" v-if="item.type == 3">
                        <img :src="require('@/assets/svg/icon-task-twitter.svg')" alt />
                        <!-- <img :src="require('@/assets/svg/icon-retweet.svg')" alt /> -->
                        <div class="item-content">
                            <div class="item-title">Retweet</div>
                        </div>
                        <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                            v-show="!state.done.retweet && state.done.retweet_red" />
                        <img v-if="state.done.retweet" :src="require('@/assets/svg/icon-true.svg')" alt />
                        <div v-else class="btn" @click="clickRetweetBtn">Retweet</div>
                    </div>
                    <!-- Comment、艾特 friends -->
                    <div class="item" v-if="item.type == 9">
                        <img :src="require('@/assets/svg/icon-task-twitter.svg')" alt />
                        <div class="item-content">
                            <div class="item-title">Comment and Tag 3 friends</div>
                        </div>
                        <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                            v-show="!state.done.reply && state.done.reply_red" />
                        <img v-if="state.done.reply" :src="require('@/assets/svg/icon-true.svg')" alt />
                        <div v-else class="btn" @click="clickReply(item)">Comment</div>
                    </div>
                    <!-- repost feacebook -->
                    <div class="item" v-if="item.type == 8">
                        <img :src="require('@/assets/svg/icon-task-facebook.svg')" alt />
                        <div class="item-content">
                            <div class="item-title">Repost to Facebook</div>
                        </div>
                        <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                            v-show="!state.done.repost_facebook && state.done.repost_facebook_red" />
                        <img v-if="state.done.repost_facebook" :src="require('@/assets/svg/icon-true.svg')" alt />
                        <div v-else class="btn" @click="clickRepostFacebook(item)">Repost</div>
                    </div>
                    <!-- join discord  -->
                    <div class="item" v-if="item.type == 7">
                        <img :src="require('@/assets/svg/icon-discord-mini.svg')" alt />
                        <div class="item-content">
                            <div class="item-title">Join Discord</div>
                        </div>
                        <img :src="require('@/assets/gif/red-right.gif')" alt class="red-right"
                            v-show="!state.done.join_discord && state.done.join_discord_red" />
                        <img v-if="state.done.join_discord" :src="require('@/assets/svg/icon-true.svg')" alt />
                        <template v-else>
                            <div v-if="joinDiscordIng" class="loading-wrapper">
                                <img class="icon-loading" :src="require('@/assets/svg/icon-loading-gray.svg')" />
                            </div>
                            <div v-else class="btn" @click="joinDiscord">
                                Join
                            </div>
                        </template>
                    </div>
                </template>
            </div>
            <!-- <div class="people" @click="clickRoad">
        <div class="txt">
          {{ state.detail.receiveCount || 0 }}/{{ state.detail.totalCount || 0 }} Winners,{{
              state.detail.receiveAmountValue
          }}/{{ state.detail.amountValue }} {{ state.detail.currencySymbol }}</div>
        <div class="right" v-if="state.detail.allReceived">

          <img :src="require('@/assets/svg/icon-right.svg')" alt class="road" />
        </div>
      </div> -->
            <div class="footer">

                <div class="btn" @click="clickGetGiveaways">Complete</div>
            </div>
        </div>


        <!-- success -->
        <div v-if="state.status == 'success'" class="success">
            <div class="header" v-if="state.detail.rewardType === RewardType.money"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top-180.svg')})` }">
                <div class="success-title">
                    🎉 Awesome! You are Winner!
                </div>
                <div class="money">
                    <img :src="state.detail.currencyIconPath" alt />
                    <font-amount :amount="state.receiveAmount" class="big" :fontSize="46"></font-amount>
                    <!-- <span class="small">{{ state.detail.currencySymbol }}</span> -->
                </div>
                <div class="done" @click="clickDone">
                    <img :src="require('@/assets/subject/001-icon-done.svg')" alt class="icon-done" />
                    <span>View Rewards In Wallet</span>
                    <img :src="require('@/assets/svg/icon-right.svg')" alt class="icon-right" />
                </div>
            </div>
            <div class="header header-custom-prize" v-else
                :style="{ 'backgroundImage': `url(${successTopBgCpd})`, 'minHeight': '150px' }">
                <div class="success-title">
                    🎉 Awesome! You are the Winner!
                </div>
                <div class="custom-prize-show">
                    <component-zoom width="340" fontSize="22" class="custom-prise-name">
                        <img :src="require('@/assets/subject/icon-gift-inline.svg')" alt />
                        <span>{{ state.detail.customizedReward }}</span>
                    </component-zoom>
                    <!-- <font-zoom :amount="state.detail.customizedReward" width="500" class="custom-prise-name" fontSize="22"></font-zoom> -->
                </div>
            </div>
            <div class="luck-list-title">
                <div>{{ state.detail.receiveCount || 0 }}/{{ state.detail.totalCount || 0 }} Winners</div>
                <div class="right">
                    <span class="text" v-if="state.detail.rewardType === RewardType.money">
                        <a-tooltip :title="state.detail.receiveAmountValue">
                            {{ getBit(state.detail.receiveAmountValue) }}
                        </a-tooltip>
                        /
                        <a-tooltip :title="state.detail.amountValue">
                            {{ getBit(state.detail.amountValue) || '' }}
                        </a-tooltip>
                    </span>
                    {{ state.detail.currencySymbol || '' }}
                </div>
            </div>
            <div class="luck-list max" @scroll="handleScroll($event)">
                <div class="luck-item" v-for="item, i in state.detail.allReceived" v-bind:key="i">
                    <img v-if="item.simpleUserInfoVO.avatarUrl" :src="item.simpleUserInfoVO.avatarUrl"
                        @click="openTwitterDetail(item)" alt />
                    <img v-else :src="require('@/assets/svg/icon-twitter.svg')" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-1.svg')" v-if="i == 0" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-2.svg')" v-if="i == 1" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-3.svg')" v-if="i == 2" alt />
                    <div class="luck-content">
                        <div class="luck-title" v-if="item.simpleUserInfoVO.nickName">{{ item.simpleUserInfoVO.nickName
                        }}</div>
                        <div class="luck-title" v-else>Twitter User</div>
                        <div class="luck-time">{{ moment(item.receiveTimestamp).format('MM-DD HH:mm') }}</div>
                    </div>
                    <div class="luck-money" v-if="state.detail.rewardType === RewardType.money">
                        <img :src="state.detail.currencyIconPath" alt />
                        <div class="luck-money-txt">
                            <a-tooltip :title="item.amountValue">
                                {{ getBit(item.amountValue) }}
                            </a-tooltip>
                        </div>
                    </div>
                    <div class="luck-custom-prize" v-else>winner</div>
                    <div class="luck-king" v-if="state.detail.rewardType === RewardType.money && item.maxAmount">
                        <img :src="require('@/assets/svg/icon-king-hat.svg')" alt />
                        <span>Luckiest Draw</span>
                    </div>
                </div>
            </div>
            <get-more :reportData="{
                pageSource: Report.pageSource.received_success_page,
                postId: state.postId
            }"></get-more>
        </div>


        <!-- no-open -->
        <div v-else-if="state.status == 'not-open'" class="not-open">
            <!-- <template v-if="state.detail.posterType === 2 && state.detail.customPosterInstalled">
                <img class="customImg" :src="state.detail.customPosterInstalled" />
                <div class="customBottom">
                    <div class="theme">
                        <img class="icon" :src="require('@/assets/svg/icon-last-time.svg')"/>
                        <span class="time">{{ state.count_down_time }}</span>
                        <span class="info">Left</span>
                    </div>
                    <div class="winner-info">
                        <span class="count">{{state.detail.totalCount}} Winners</span>
                        <span>to Share </span>
                        <span class="prize-name">{{state.detail.rewardType === RewardType.money ? state.detail.amountValue + ' ' + state.detail.currencySymbol : state.detail.customizedReward}}</span>
                    </div>
                    <div class="open-red" @click="clickOpenRedPacket">
                        Participate Now
                    </div>
                </div>
            </template> -->
            <!-- <template v-else> -->
            <custom-card-cover :data="{
                totalCount: state.detail.totalCount,
                amountValue: state.detail.amountValue,
                tokenSymbol: state.detail.currencySymbol,
                encyCode: state.detail.amountCurrencyCode,
                encyIconUrl: state.detail.currencyIconPath,
                pe: PlayType.lottery,
                validityDuration: state.count_down_time,
                countDown: state.count_down_time,
                userInfo: {
                    nickName: state.detail.postUserInfo.nickName,
                    avatarUrl: state.detail.postUserInfo.avatarUrl
                },
                rewardType: state.detail.rewardType,
                customizedReward: state.detail.customizedReward,
                customPosterUrl: state.detail.customPosterInstalled
            }" @clickOpenRedPacket="clickOpenRedPacket"></custom-card-cover>
            <!-- </template> -->
        </div>


        <!-- 领取列表 -->
        <div v-else-if="state.status == 'luck-peopel-list'" class="luck-peopel-list">
            <div class="head">
                <img :src="require('@/assets/svg/icon-back.svg')" alt />
            </div>
            <div class="luck-list-title">
                <div>{{ state.detail.receiveCount || 0 }}/{{ state.detail.totalCount || 0 }} Winners</div>
                <div class="right" v-if="state.detail.rewardType === RewardType.money">
                    <span class="text">
                        <a-tooltip :title="state.detail.receiveAmountValue">
                            {{ getBit(state.detail.receiveAmountValue) }}
                        </a-tooltip>
                        /
                        <a-tooltip :title="state.detail.amountValue">
                            {{ getBit(state.detail.amountValue) || '' }}
                        </a-tooltip>
                    </span> {{
                            state.detail.currencySymbol || ''
                    }}
                </div>
            </div>
            <div class="luck-list" @scroll="handleScroll">
                <div class="luck-item" v-for="item, i in     state.detail.allReceived" v-bind:key="i">
                    <img v-if="item.simpleUserInfoVO.avatarUrl" :src="item.simpleUserInfoVO.avatarUrl" alt
                        @click="openTwitterDetail(item)" />
                    <img v-else :src="require('@/assets/svg/icon-twitter.svg')" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-1.svg')" v-if="i == 0" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-2.svg')" v-if="i == 1" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-3.svg')" v-if="i == 2" alt />
                    <div class="luck-content">
                        <div class="luck-title" v-if="item.simpleUserInfoVO.nickName">{{ item.simpleUserInfoVO.nickName
                        }}</div>
                        <div class="luck-title" v-else>Twitter User</div>
                        <div class="luck-time">{{ moment(item.receiveTimestamp).format('MM-DD HH:mm:ss') }}</div>
                    </div>
                    <div class="luck-money" v-if="state.detail.rewardType === RewardType.money">
                        <img :src="state.detail.currencyIconPath" alt />
                        <div class="luck-money-txt">
                            <a-tooltip :title="item.amountValue">
                                {{ getBit(item.amountValue) }}
                            </a-tooltip>
                        </div>
                    </div>
                    <div class="luck-custom-prize" v-else>winner</div>
                    <div class="luck-king" v-if="state.detail.rewardType === RewardType.money && item.maxAmount">
                        <img :src="require('@/assets/svg/icon-king-hat.svg')" alt />
                        <span>Luckiest Draw</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 关闭状态 -->
        <div v-else-if="state.status == 'close'" class="close">
            <!-- 红包被领完了 -->
            <!-- <div class="header"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top.svg')})` }"
                v-if="state.close_status == '已经过期了'">
                <div class="rabbit">
                    <img class="flower" :src="require('@/assets/svg/icon-flower.svg')" alt />
                    <p>This Draw is Complete</p>
                </div>
            </div> -->
            <div class="header"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top.svg')})` }"
                v-show="state.close_status == '已经过期了'">
                <div class="close-title" v-for="item in state.close_text">{{ item }}</div>
            </div>

            <!-- 没有抽中 -->
            <div class="header"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top.svg')})` }"
                v-if="state.close_status == '没有抽中'">
                <div class="rabbit">
                    <img :src="require('@/assets/subject/001-icon-rabbit.svg')" alt />
                    <p>Good Luck Next Time!</p>
                </div>
            </div>


            <!-- 等待结果 -->
            <div class="header"
                :style="{ 'backgroundImage': `url(${require('@/assets/subject/002-back-head-top.svg')})` }"
                v-if="state.close_status == '等待结果'">
            </div>
            <div class="load-result" v-if="state.close_status == '等待结果'">
                <div class="title">
                    <img :src="require('@/assets/svg/icon-enter-ed.svg')" alt />
                    <span>Participate Successful</span>
                </div>
                <!-- 票 -->
                <div class="ticket">
                    <div class="div-ticket">
                        <img :src="require('@/assets/svg/icon-ticket.svg')" alt />
                    </div>
                </div>
                <p>Announcement Winner</p>
                <div class="time">
                    <img :src="require('@/assets/svg/icon-win-time.svg')" alt />
                    <span>{{ state.count_down_time || '' }}</span>
                </div>
                <get-more :style_type="2" :reportData="{
                    pageSource: Report.pageSource.waitingLotteryPage,
                    postId: state.postId
                }"></get-more>
                <div class="notification_switch" v-if="state.notification_show">
                    <span>Announcement Notification</span>
                    <a-switch v-model:checked="state.notification_switch" @change="changeNotification" />
                </div>
            </div>

            <div class="luck-list-title" v-show="state.close_status != '等待结果'">
                <div>{{ state.detail.receiveCount || 0 }}/{{ state.detail.totalCount || 0 }} Winners</div>
                <div class="right" v-if="state.detail.rewardType === RewardType.money">
                    <span class="text">
                        <a-tooltip :title="state.detail.receiveAmountValue">
                            {{ getBit(state.detail.receiveAmountValue) }}
                        </a-tooltip>
                        /
                        <a-tooltip :title="state.detail.amountValue">
                            {{ getBit(state.detail.amountValue || '') }}
                        </a-tooltip>
                    </span> {{
                            state.detail.currencySymbol || ''
                    }}
                </div>
            </div>

            <div class="luck-list max" @scroll="handleScroll" v-show="state.close_status != '等待结果'">
                <div class="luck-item" v-for="item, i in state.detail.allReceived" v-bind:key="i">
                    <img v-if="item.simpleUserInfoVO.avatarUrl" :src="item.simpleUserInfoVO.avatarUrl" alt
                        @click="openTwitterDetail(item)" />
                    <img v-else :src="require('@/assets/svg/icon-twitter.svg')" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-1.svg')" v-if="i == 0" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-2.svg')" v-if="i == 1" alt />
                    <img class="win" :src="require('@/assets/svg/icon-win-3.svg')" v-if="i == 2" alt />
                    <div class="luck-content">
                        <div class="luck-title" v-if="item.simpleUserInfoVO.nickName">{{ item.simpleUserInfoVO.nickName
                        }}</div>
                        <div class="luck-title" v-else>Twitter User</div>
                        <div class="luck-time">{{ moment(item.receiveTimestamp).format('MM-DD HH:mm:ss') }}</div>
                    </div>
                    <div class="luck-money" v-if="state.detail.rewardType === RewardType.money">
                        <img :src="state.detail.currencyIconPath" alt />
                        <div class="luck-money-txt">
                            <a-tooltip :title="item.amountValue">
                                {{ getBit(item.amountValue) }}
                            </a-tooltip>
                        </div>
                    </div>
                    <div class="luck-custom-prize" v-else>winner</div>
                    <div class="luck-king" v-if="state.detail.rewardType === RewardType.money && item.maxAmount">
                        <img :src="require('@/assets/svg/icon-king-hat.svg')" alt />
                        <span>Luckiest Draw</span>
                    </div>
                </div>

                <div class="empty" v-show="state.detail.allReceived && state.detail.allReceived.length == 0">
                    <img :src="require('@/assets/svg/icon-error.svg')" alt />
                </div>
            </div>
            <get-more :reportData="{
                pageSource: Report.pageSource.missingLotteryPage,
                postId: state.postId
            }" v-if="state.close_status != '等待结果'"></get-more>
        </div>


        <!-- error -->
        <div v-else-if="state.status == 'error'" class="error">
            <img :src="require('@/assets/svg/icon-error.svg')" alt />
            <div class="txt">
                {{ state.error_txt }}
            </div>
            <div class="retry" v-show="state.retry" @click="clickRetry">
                Retry
            </div>
        </div>


        <!-- loading -->
        <div v-show="state.loading_show" class="loading">
            <img :src="require('@/assets/svg/icon-loading.svg')" alt />
        </div>

        <div v-show="state.loading_redbag" class="redbag">
            <img :src="require('@/assets/img/icon-loading-redbag.gif')" alt />
        </div>

    </div>
    <div style="width: 100%; height: 30px; position: fixed; color: red; top:0;"
        v-if="state.process_mode != 'production'">
        {{ state.detail.validity }}</div>
</template>

<script>
export default {
    name: 'redPacket',
}
</script>
<script setup>
import { onMounted, reactive, ref, computed } from "vue";
import { getPostDetail, getRedPacket, finishRedPacket, oneKeyLike, oneKeyReTweet, oneKeyFollow, getTaskDetail, getReceivedList, addFinishEvent } from '@/http/redPacket.js'
import { getQueryString, guid, getBit, formatSecondsAsDaysOrTime } from '@/uilts/help.js'
import { message } from 'ant-design-vue';
import FontAmount from '@/view/components/font-amount.vue'
import FontZoom from '@/view/components/font-zoom.vue'
import ComponentZoom from '@/view/components/component-zoom.vue'
import GetMore from '@/view/iframe/publish/components/get-more.vue'
import { setChromeStorage, getChromeStorage, sendChromeTabMessage, chromeExtensionUrl } from '@/uilts/chromeExtension.js'
import Report from "@/log-center/log"
import { srcPublishSuccess } from '@/http/publishApi'
import { discordAuthUrl, checkGuildJoined } from '@/http/discordApi'
import { discordAuthRedirectUri, faceShareRedirectUrl } from '@/http/configAPI'
import { getSetting, putSetting } from '@/http/user'
import { getFrontConfig } from "@/http/account";
import { getInviteGuildInfo } from "@/http/discordApi";
import GlobalTip from '@/view/components/global-tip.vue';
import customCardCover from '@/view/components/custom-card-cover.vue';
import { RewardType, PlayType } from "@/types";

var moment = require('moment');

let discordAuthorizeRequired = false;
let joinDiscordActionState = 'default'; //authAndJoinIng  joinIng  reAuth
let joinDiscordIng = ref(false);

let facebookAppConfig = {
    facebookAppId: "",
    faceShareRedirectUrl
};

let reportParams = {
    discordFans: '',
    twitterFans: '',
    done: {
    },
    hasReport: false,
}

let discordTaskDetail = null;

let state = reactive({
    status: '',
    userId: '',
    loading_show: false,
    loading_redbag: true,
    detail: {},
    luck_list_end: false,
    page_index: 1,
    page_size: 20,
    srcContentId: '',
    customCover: '',
    customGiveaway: '',
    error_txt: `oops, new accounts cannot participate in this event,`,
    receiveAmount: 0,
    money: 0,
    // 状态
    done: {
        follow: false,
        like: false,
        retweet: false,
        join_discord: false,
        repost_facebook: false,
        reply: false
    },
    notification_show: false,
    notification_switch: false,
    open_timer_status: false,
    count_down_time: ''
})

let fullName = '';

let successTopBgCpd = computed(() => {
    const { rewardType } = state.detail
    switch (rewardType) {
        case RewardType.custom:
            return require('@/assets/subject/success-top-bg-2.svg');
        default:
            return require('@/assets/subject/002-back-head-top-180.svg');
            break;
    }
});

function clickRetry() {
    init()
}

let follow_open_tabs = []

async function clickLikeBtn() {
    let _userInfo = await checkIsLogin()
    if (!_userInfo) {
        return
    }
    state.detail.finishTaskTypeV2 = state.detail.finishTaskTypeV2.toString() || ''
    if (state.window_origin.indexOf('facebook.com') >= 0) {
        state.detail.finishTaskTypeV2 = '2'
    }
    switch (state.detail.finishTaskTypeV2) {
        case '1':
            state.loading_show = true
            oneKeyLike({
                params: {
                    tweetId: state.srcContentId
                }
            }).then((res) => {
                state.loading_show = false
                if (res.code == 0) {
                    if (res.data.result) {
                        state.done.like = true
                    } else {
                        state.done.like = false
                        window.open(`https://twitter.com/intent/like?tweet_id=${state.tweetId}`)
                    }
                } else {
                    window.open(`https://twitter.com/intent/like?tweet_id=${state.tweetId}`)
                    state.done.like = false
                }
            }).catch(() => {
                state.loading_show = false
            })
            break
        case '2':
            window.open(`https://twitter.com/intent/like?tweet_id=${state.tweetId}`)
            break
        case '3':
            state.loading_show = true
            chrome.tabs.getCurrent((tab) => {
                chrome.tabs.sendMessage(tab.id, {
                    actionType: "IFRAME_TWITTER_API_DO_TASK", task_data: {
                        tweet_Id: state.tweetId
                    }, task_type: 'like'
                }, (res) => { console.log(res) });
            })
            break
        default:
            window.open(`https://twitter.com/intent/like?tweet_id=${state.tweetId}`)
            break
    }

    // 埋点
    Report.reportLog({
        objectType: Report.objectType.like,
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}
function clickDone() {
    window.open(`${chromeExtensionUrl + ('iframe/home.html')}`)
    // 埋点
    Report.reportLog({
        objectType: Report.objectType.wallet_button,
        pageSource: Report.pageSource.received_success_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}
function handleScroll(e) {
    if (state.luck_list_end) {
        return
    }
    e = e.target
    if ((e.clientHeight + e.scrollTop) / e.scrollHeight > .8) {
        state.luck_list_end = true
        state.page_index++
        handleReceivedList()
    }
}
function handleReceivedList() {
    getReceivedList({
        params: {
            pageNum: state.page_index,
            pageSize: state.page_size,
            postId: state.postId
        }
    }).then((res) => {
        if (res.code == 0) {
            if (res.data.length > 0) {
                state.detail.allReceived = state.detail.allReceived.concat(res.data)
                state.luck_list_end = false
            } else {
                state.luck_list_end = true
            }
        } else {
            console.log('getReceivedList', res)
        }
    })
}

const openTwitterDetail = (item) => {
    if (item.simpleUserInfoVO.nickName) {
        window.open(`https://twitter.com/${item.simpleUserInfoVO.nickName}`)
    }
}

async function clickRetweetBtn() {
    let _userInfo = await checkIsLogin()
    if (!_userInfo) {
        return
    }

    state.detail.finishTaskTypeV2 = state.detail.finishTaskTypeV2.toString() || ''
    if (state.window_origin.indexOf('facebook.com') >= 0) {
        state.detail.finishTaskTypeV2 = '2'
    }
    switch (state.detail.finishTaskTypeV2) {
        case '1':
            state.loading_show = true
            oneKeyReTweet({
                params: {
                    tweetId: state.srcContentId
                }
            }).then((res) => {
                state.loading_show = false
                if (res.code == 0) {
                    if (res.data.result) {
                        state.done.retweet = true
                    } else {
                        window.open(`https://twitter.com/intent/retweet?tweet_id=${state.tweetId}`)
                        state.done.retweet = false
                    }
                } else {
                    window.open(`https://twitter.com/retweet/like?tweet_id=${state.tweetId}`)
                    state.done.retweet = false
                }
            }).catch(() => {
                state.loading_show = false
            })
            break;
        case '2':
            window.open(`https://twitter.com/intent/retweet?tweet_id=${state.tweetId}`)
            break
        case '3':
            state.loading_show = true
            chrome.tabs.getCurrent((tab) => {
                chrome.tabs.sendMessage(tab.id, {
                    actionType: "IFRAME_TWITTER_API_DO_TASK", task_data: {
                        tweet_Id: state.tweetId
                    }, task_type: 'retweet'
                }, (res) => { console.log(res) });
            })
            break
        default:
            window.open(`https://twitter.com/intent/retweet?tweet_id=${state.tweetId}`)
            break;
    }

    // 埋点
    Report.reportLog({
        objectType: Report.objectType.retweet,
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}

function onTweetReplyClick(params) {
    let replyData = {
        postId: state.postId,
        type: params.type,
        taskLuckdropId: state.detail.taskLuckdropId
    }

    window.parent.postMessage({ actionType: "IFRAME_RED_PACKET_ON_TWEET_REPLY_CLICK", data: replyData }, "*");
}

function changeNotification(checked) {
    let noticeSwitch = checked ? 1 : 0;
    // set
    putSetting({
        params: { noticeSwitch }
    }).then(res => {
        let { code } = res;
        if (code === 0) {
            state.notification_switch = checked
        } else {
            state.notification_switch = !checked
        }
    }).catch(() => {
        state.notification_switch = !checked
    })
}

function setNotification(req) {
    state.notification_switch = req.status;
}

async function clickReply(params) {
    let _userInfo = await checkIsLogin()
    if (!_userInfo) {
        return
    }

    let replyData = {
        postId: state.postId,
        type: params.type,
        taskLuckdropId: state.detail.taskLuckdropId
    }
    if (state.window_origin.indexOf('facebook.com') > -1) {
        let url = `https://twitter.com/${state.tweet_author}/status/${state.tweetId}?actionType=denetFacebookToTwitterReply&deReplyParams=${JSON.stringify(replyData)}`
        window.open(url)
    } else {
        window.parent.postMessage({ actionType: "IFRAME_RED_PACKET_REPLY_CLICK", data: replyData }, "*");
    }

    // 埋点
    Report.reportLog({
        objectType: Report.objectType.comment_and_tag,
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}

/**
 * 点击repost facebook
 */
async function clickRepostFacebook(params) {
    let _userInfo = await checkIsLogin()
    if (!_userInfo) {
        return
    }

    let deUrlParams = {
        fullName,
        tweetId: state.tweetId
    }
    let href = `${state.postRedirectUrl}?deUrlParams=${JSON.stringify(deUrlParams)}`;
    console.log(href);
    let shareUrlparams = {
        href,
        type: params.type,
        taskLuckdropId: state.detail.taskLuckdropId
    }

    setChromeStorage({
        shareFacebookData: JSON.stringify({
            contentStr: state.srcContent
        })
    })

    let shareUrl = feacebookShareUrl(shareUrlparams);
    openShareFacebookWindow({ url: shareUrl });

    // 埋点
    Report.reportLog({
        objectType: Report.objectType.share_facebook,
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}

/**
 * 分享到facebook
 */
function openShareFacebookWindow({ url }) {
    const width = 800;
    chrome.windows.create({
        width,
        type: 'normal',
        url
    }, function (window) {

    })
}

/**
 * 分享fecebook 地址
 */
function feacebookShareUrl(params = {}) {
    let { href = '', type = '', taskLuckdropId } = params;
    let cbParams = JSON.stringify({
        type,
        taskLuckdropId
    })
    let shareUrl = `https://www.facebook.com/dialog/share?app_id=${facebookAppConfig.facebookAppId}&display=popup&href=${href}&redirect_uri=${facebookAppConfig.faceShareRedirectUrl}?params=${cbParams}`;

    return shareUrl;
}

/**
 * 分享成功
 */
function facebookShareSuccess(params) {
    let { taskLuckdropId } = params;

    if (taskLuckdropId == state.detail.taskLuckdropId) {
        state.done.repost_facebook = true;
        state.done.repost_facebook_red = false;
    }
}


function getValidity() {
    let _d1, _d2, _d3, _h, _m, _s
    if (!state.detail.myReceived.taskEndTimestamp) {
        return
    }
    let timer = setInterval(() => {
        let _time = new Date().getTime()
        _d3 = state.detail.myReceived.taskEndTimestamp - _time
        if (_d3 > 0) {
            _d1 = moment(state.detail.myReceived.taskEndTimestamp)
            _d2 = moment(_time)
            _h = moment.duration(_d1.diff(_d2)).hours()
            if (_h < 10) {
                _h = '0' + _h
            }
            _m = moment.duration(_d1.diff(_d2)).minutes()
            if (_m < 10) {
                _m = '0' + _m
            }
            _s = moment.duration(_d1.diff(_d2)).seconds()
            if (_s < 10) {
                _s = '0' + _s
            }
            state.detail.validity = `${_h}:${_m}:${_s}`
        } else {
            state.detail.validity = `00:00:00`
            clearInterval(timer)
        }
    }, 1000)
}

// 倒计时
const getTimeStr = (end_time_ms) => {
    let now_time_ms, now_time, end_time
    let _time, _h, _m, _s, _time_str
    now_time_ms = new Date().getTime()
    _time = end_time_ms - now_time_ms
    if (_time > 0) {
        now_time = moment(now_time_ms)
        end_time = moment(end_time_ms)
        _h = moment.duration(end_time.diff(now_time)).hours()
        _m = moment.duration(end_time.diff(now_time)).minutes()
        _s = moment.duration(end_time.diff(now_time)).seconds()
        if (_h < 10) {
            _h = '0' + _h
        }
        if (_m < 10) {
            _m = '0' + _m
        }
        if (_s < 10) {
            _s = '0' + _s
        }
        _time_str = `${_h}:${_m}:${_s}`
    } else {
        _time_str = `00:00:00`
    }
    return _time_str
}

function openConutDownTime(end_time_ms, callback) {
    end_time_ms = Number(end_time_ms) + 5000
    let end_time_s = Number((end_time_ms - new Date().getTime()) / 1000)
    let timer = setInterval(() => {
        end_time_s = Number((end_time_ms - new Date().getTime()) / 1000)
        if (state.open_timer_status == true) {
            clearInterval(timer)
        }
        callback(formatSecondsAsDaysOrTime(end_time_s))
    }, 1000);
    callback(formatSecondsAsDaysOrTime(end_time_s))
}

const openFollowTabs = (arr_name) => {
    let array_finish = arr_name.filter((item) => { return !item.finished })
    // let array_finish = state.detail.taskCondition[0].relatedUsers.filter((item) => { return item.finished == false })
    let url
    if (array_finish.length > 0) {
        state.done.follow = false
        // 打开标签页的方法
        array_finish.forEach((item) => {
            url = `https://twitter.com/intent/follow?screen_name=${item.name}&tweet_id=${state.tweetId}`
            chrome.tabs.create({ url }, (tab) => {
                if (follow_open_tabs.filter((item) => { return item.url == tab.url }).length == 0) {
                    follow_open_tabs.push(tab)
                }
            })
        })
    }
}

async function clickFollowAll(item, is_all) {
    let _userInfo = await checkIsLogin()
    if (!_userInfo) {
        return
    }
    let arr_name = []
    for (let i in item) {
        if (!item[i].finished) {
            arr_name.push(item[i])
        }
    }
    // ----
    state.detail.finishTaskTypeV2 = state.detail.finishTaskTypeV2.toString() || ''
    if (state.window_origin.indexOf('facebook.com') >= 0) {
        state.detail.finishTaskTypeV2 = '2'
    }
    switch (state.detail.finishTaskTypeV2) {
        case '1':
            // openapi
            state.loading_show = true
            oneKeyFollow({
                params: {
                    names: arr_name
                }
            }).then((res) => {
                state.loading_show = false
                if (res.code == 0) {
                    res.data.forEach((item1) => {
                        state.detail.taskCondition[0].relatedUsers.forEach(item2 => {
                            if (item1.name == item2.name && item1.finished) {
                                item2.finished = true
                            }
                        });
                    })
                    openFollowTabs(arr_name)
                }
            }).catch(() => {
                state.loading_show = false
            })
            break
        case '2':
            openFollowTabs(arr_name)
            break
        case '3':
            if (arr_name.filter((item) => { return !item.twitterUserId }).length > 0) {
                openFollowTabs(arr_name)
                return
            }
            let follow_data = []
            arr_name.forEach((item) => {
                follow_data.push(item)
            })
            state.loading_show = true
            chrome.tabs.getCurrent((tab) => {
                chrome.tabs.sendMessage(tab.id, {
                    actionType: "IFRAME_TWITTER_API_DO_TASK",
                    task_data: {
                        tweet_Id: state.tweetId,
                        follow_data: follow_data,
                    },
                    task_type: 'follow'
                }, (res) => { console.log(res) });
            })

            break
        default:
            openFollowTabs(arr_name)
            break
    }
    // -------- 埋点 --------
    let _log_obj = {
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        objectType: Report.objectType.follow,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    }
    if (is_all) {
        _log_obj.objectType = Report.objectType.follow_button
    }
    Report.reportLog(_log_obj, {
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
    });
}


// 重新绑定
const reSetBindTwtterId = (_params) => {
    let postBizData = JSON.parse(_params.postBizData);
    let { taskCondition } = postBizData;
    let discordTask = JSON.parse(taskCondition).find(item => item.type == 7);

    getChromeStorage('userInfo', (_userInfo = {}) => {
        // if (_userInfo && _userInfo.uid == _params.uid) {
        if (_userInfo.uid) {
            srcPublishSuccess({
                params: {
                    postId: state.postId,
                    srcContentId: state.tweetId
                }
            }).then((res) => {
                if (res.code == 0 || res.code == 3003) {
                    init({ from: 'reSetBindTwtterId' })
                    reportBindTweetSuccess({ discordTask, ..._params });
                }
            })
        }
    })
}

const reportBindTweetSuccess = (params) => {
    let { discordTask, srcUserId } = params || {};
    discordTaskDetail = discordTask;
    sendChromeTabMessage({
        actionType: "IFRAME_API_GET_TWEET_USER_INFO_REQ",
        data: {
            screen_name: srcUserId,
            tweetId: state.tweetId
        }
    })

    if (discordTask) {
        getDiscordInfo({ inviteUrl: JSON.parse(discordTask.bizData).inviteUrl }, (res) => {
            if (res.inviteCode == res.code) {
                reportParams.discordFans = res.approximate_member_count;

                if (reportParams.twitterFans !== '' && !reportParams.hasReport) {
                    reportParams.hasReport = true;
                    Report.reportLog({
                        objectType: Report.objectType.tweetPostBinded,
                        twitterFans: reportParams.twitterFans,
                        discordFans: reportParams.discordFans,
                        redPacketType: 1,
                        postId: state.postId
                    });
                }
            }
        })
    }
}

const getDiscordInfo = (params, cb) => {
    let { inviteUrl } = params;
    if (!inviteUrl) return;

    let inviteCode = '';
    let arr = inviteUrl.split('/');
    if (arr.length > 0) {
        inviteCode = arr[arr.length - 1];
    }
    if (!inviteCode) {
        return;
    }

    getInviteGuildInfo({
        inviteCode
    }).then(res => {
        cb && cb({
            ...res,
            inviteCode
        })
    }).catch((err) => {
    });
}

const showCloseEndTimePage = () => {
    state.status = 'close'
    state.open_timer_status = true
    state.close_status = '已经过期了'
    state.close_text = [`This Giveaways`, `expired on ${moment(state.detail.endTimestamp).format('MM-DD')}`]
}

const showCloseEndTimePageReport = () => {
    // 埋点
    Report.reportLog({
        pageSource: Report.pageSource.expired_page,
        businessType: Report.businessType.pageView,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
    });
}

const showSuccessPage = () => {
    state.status = 'success'
    state.open_timer_status = true;

    if (!reportParams.reportReceivedPageViewSuccess) {
        reportParams.reportReceivedPageViewSuccess = true;

        // 埋点
        Report.reportLog({
            pageSource: Report.pageSource.received_success_page,
            businessType: Report.businessType.pageView,
            postId: state.postId,
            srcContentId: state.tweetId,
            senderId: state.userId,
            isOldTwitterFans: reportParams.done.follow,
            isOldDiscordFans: reportParams.done.join_discord,
            redPacketType: 1,
            customCover: state.customCover,
            customGiveaway: state.customGiveaway,
        });
    }
}

const showNotOpenPage = () => {
    state.status = 'not-open'
    openConutDownTime(state.detail.endTimestamp, (time_str) => {
        state.count_down_time = time_str
        if (time_str == '00:00:00') {
            init()
        }
    })
    Report.reportLog({
        pageSource: Report.pageSource.pending_page,
        businessType: Report.businessType.pageView,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}
const showOpenedPage = () => {
    state.status = 'opened'
    state.open_timer_status == true
    initTaskDetail(() => {
        showOpenedPageReport()
    })
}
const showOpenedPageReport = () => {
    reportParams.done.follow = state.done.follow;
    reportParams.done.join_discord = state.done.join_discord;

    // 埋点
    Report.reportLog({
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.pageView,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        isOldTwitterFans: state.done.follow,
        isOldDiscordFans: state.done.join_discord,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}

const showRabbitPage = () => {
    state.status = 'close'
    state.close_status = '没有抽中'
    state.open_timer_status = true
}
const showRabbitPageReport = () => {
    Report.reportLog({
        pageSource: Report.pageSource.received_empty_rewards_page,
        businessType: Report.businessType.pageView,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
    });
}
const handleStatusPage = () => {
    // status 红包状态（0:未开始，1:进行中，2:已结束，3:已终止，4:终止退款进行中）
    // myReceived 我是否领取过
    // taskFinishStatus 任务完成状态（0:未完成，1:已完成，2:已过期）
    // receiveTimeExpired 是否已经过了红包的领取截止时间
    // endTimestamp 开奖时间

    // ---- 判断结构 ----
    // 如果 红包状态 = 未开始
    //    显示未打开页面 return

    // 如果 红包状态 =  已终止 ｜ 终止退款进行中
    //      显示过期页面
    // 如果 我领取过了
    //    如果 任务完成状态 = 未完成 & 红包状态 = 进行中
    //         显示任务未完成页面
    //    如果 任务完成状态 = 未完成 & 红包状态 = 已结束
    //         显示过期页面
    //    如果 任务完成状态 = 已经完成
    //        如果 （货币奖品类型 领取到红包金额 = 0 || 通用奖品类型 winner = 0) & 红包状态 = 已结束
    //            显示兔子页面
    //        否则如果 红包状态 = 已结束
    //            显示成功页面
    //        如果 红包状态 = 进行中
    //            显示等待结果页面

    //    如果 任务完成状态 = 已经过期
    //        如果 红包状态 = 进行中
    //            显示未打开页面
    //        否则
    //            显示已经过期页面

    // 如果 我没有领取过 & 红包状态 = 进行中
    //    如果 过了红包的领取截止时间 = true
    //        显示已经过期页面
    //    如果 过了红包的领取截止时间 = false
    //        显示未打开页面

    // 如果 我没有领取过 & 红包状态 = 已结束 ｜ 已终止 ｜ 终止退款进行中
    //    显示过期页面

    // -------- 华丽的分割线 --------
    // 如果 红包状态 = 未开始

    if (state.detail.status == 0) {
        showNotOpenPage()
        return
    }
    // 如果 红包状态 =  已终止 ｜ 终止退款进行中
    if (state.detail.status == 3 || state.detail.status == 4) {
        //      显示过期页面
        showCloseEndTimePage()
        showCloseEndTimePageReport()
    }
    // 如果 我领取过了
    else if (state.detail.myReceived) {
        state.receiveAmount = state.detail.myReceived.amountValue || 0
        state.detail.taskCondition = JSON.parse(state.detail.taskCondition)
        // 如果 任务完成状态 = 未完成 & 红包状态 = 进行中
        if (state.detail.myReceived.taskFinishStatus == 0 && state.detail.status == 1) {
            // 显示任务未完成页面
            showOpenedPage()
            if (state.process_mode != 'production') {
                getValidity()
            }
            //    如果 任务完成状态 = 未完成 & 红包状态 = 已结束
            else if (state.detail.myReceived.taskFinishStatus == 0 && state.detail.status == 2) {
                // 显示已经过期页面
                showCloseEndTimePage()
                showCloseEndTimePageReport()
            }
            //如果 任务完成状态 = 已经完成
        } else if (state.detail.myReceived.taskFinishStatus == 1) {
            // 领取到空红包 & 红包状态 = 已结束
            if (((state.detail.rewardType === RewardType.money && state.receiveAmount == 0) || (state.detail.rewardType === RewardType.custom && state.detail.myReceived.winner === 0)) && state.detail.status == 2) {
                showRabbitPage()
                showRabbitPageReport()
            } else if (state.detail.status == 2) {
                // 显示成功页面
                showSuccessPage()
            }
            // 如果  红包状态 = 进行中
            else if (state.detail.status == 1) {
                // 显示等待结果页面
                showLoadResult()
                openTimer()
            }
            // 如果 任务完成状态 = 已经过期
        } else {
            // 如果 红包状态 = 进行中
            if (state.detail.status == 1) {
                // 显示未打开页面
                showNotOpenPage()
                // 否则
            } else {
                // 显示已经过期页面
                showCloseEndTimePage()
                showCloseEndTimePageReport()
            }
        }
        // 如果 我没有领取过
    } else {
        // 如果 红包状态 = 进行中
        if (state.detail.status == 1) {
            // 如果 过了红包的领取截止时间 = true
            if (state.detail.receiveTimeExpired) {
                // 显示过期页面
                showCloseEndTimePage()
                showCloseEndTimePageReport()
                // 如果 过了红包的领取截止时间 = false
            } else {
                // 显示未打开页面
                showNotOpenPage()
            }
            // 红包状态 = 已经结束了 ｜ 已经终止 ｜ 终止退款中
        } else {
            // 显示过期页面
            showCloseEndTimePage()
            showCloseEndTimePageReport()
        }
    }

}

function setFrontConfig() {
    getFrontConfig({
        params: {},
    }).then((res) => {
        if (res.code == 0) {
            facebookAppConfig.facebookAppId = res.data.fbClientId;
        }
    });
};

function init(initParams) {
    let { type } = initParams || {};
    onPageVisbile();
    onWindowMessage();
    setFrontConfig();
    getPostDetail({
        params: {
            postId: state.postId
        }
    }).then((res) => {
        state.loading_show = false
        // 领取0元为空红包继续流程
        // ---- 完成任务接口 ----
        // 如果金额是0
        //    显示没有抽中
        if (res.code == 0) {
            state.srcContent = res.data.srcContent;
            state.postRedirectUrl = res.data.postRedirectUrl;

            // 判断推特id，绑定逻辑
            state.srcContentId = res.data.srcContentId

            if (!state.srcContentId) {
                reSetBindTwtterId(res.data)
                return
            }
            state.detail = JSON.parse(res.data.postBizData)
            state.detail.taskCondition = state.detail.taskCondition || []
            state.tweetId = state.srcContentId;
            state.userId = res.data.srcUserId;
            state.tweet_author = state.detail.postUserInfo && state.detail.postUserInfo.nickName || '';
            state.customCover = state.detail.posterType == 2 ? 1 : 0;
            state.customGiveaway = state.detail.rewardType == 2 ? 1 : 0;
            // 不要删除这个console
            console.log('postBizData', state.detail)
            checkFacebookReply();
            handleStatusPage()
        } else {
            handleErrorCode(res)
        }
    }).finally(() => {
        state.loading_redbag = false
    })
}

function initTaskDetail(cb) {
    getChromeStorage('userInfo', (_userInfo) => {
        if (_userInfo && _userInfo.uid) {
            // 任务详情
            getTaskDetail({
                params: {
                    postId: state.postId
                }
            }).then((res) => {
                if (res.code.toString()) {
                    for (let i in res.data) {
                        switch (res.data[i].type) {
                            case 1:
                                state.done.follow = res.data[i].finished
                                state.detail.taskCondition[0].relatedUsers = res.data[i].detail
                                break
                            case 2:
                                state.done.like = res.data[i].finished
                                break
                            case 3:
                                state.done.retweet = res.data[i].finished
                                break
                            case 7:
                                state.done.join_discord = res.data[i].finished
                                discordAuthorizeRequired = res.data[i].discordAuthorizeRequired
                                break
                            case 8:
                                state.done.repost_facebook = res.data[i].finished;
                                break;
                            case 9:
                                state.done.reply = res.data[i].finished;
                                if (!state.done.reply) {
                                    onTweetReplyClick({ type: 9 });
                                }
                                break;
                        }
                    }
                } else {
                    handleErrorCode(res)
                }
                cb && cb()
            })
        }
    })
}

let tab_index = 0
const doTaskReport = (req, sender) => {
    state.loading_show = false
    let follow_name = req.task_data.follow_name || ''
    // 1 Twitter follow Twitter ScreenName
    // 2 Tweet like
    // 3 Retweet
    let event_type = 0
    switch (req.task_type) {
        case 'retweet':
            event_type = 3
            state.done.retweet = req.task_done
            if (!req.task_done && req.do_type == 'api') {
                window.open(`https://twitter.com/intent/retweet?tweet_id=${state.tweetId}`)
            }
            break;
        case 'like':
            event_type = 2
            state.done.like = req.task_done
            //
            if (!req.task_done && req.do_type == 'api') {
                window.open(`https://twitter.com/intent/like?tweet_id=${state.tweetId}`)
            }
            break
        case 'follow':
            event_type = 1
            // for (let i = 0; i < follow_open_tabs.length; i++) {
            //   if (follow_open_tabs[i].id == sender.tab.id) {
            //     follow_open_tabs.splice(i, 1)
            //     break
            //   }
            // }
            // chrome.tabs.getCurrent((tab) => {
            //   if (follow_open_tabs.length > 0) {
            //     tab_index = follow_open_tabs[follow_open_tabs.length - 1].index
            //   } else {
            //     tab_index = tab.index
            //   }
            //   chrome.tabs.highlight({ windowId: tab.windowId, tabs: tab_index })
            // })
            let has_no_finished = false
            state.detail.taskCondition[0].relatedUsers.forEach((item) => {
                if (follow_name == item.name) {
                    item.finished = req.task_done
                }
            })
            state.detail.taskCondition[0].relatedUsers.forEach((item) => {
                if (!item.finished) {
                    has_no_finished = true
                }
            })
            if (!has_no_finished) {
                state.done.follow = true
                state.done.follow_red = false
                openFollowTabs(state.detail.taskCondition[0].relatedUsers)
            }
            break
    }
    if (req.do_type != 'api') {
        chrome.tabs.remove(sender.tab.id)
    }
    if (req.task_done) {
        addFinishEvent({
            params: {
                eventData: follow_name,
                eventType: event_type,
                luckdropId: state.detail.taskLuckdropId
            }
        })
    }
}

let open_timer_flag = false
// 倒计时开奖
const openTimer = () => {
    if (open_timer_flag) {
        return
    }
    open_timer_flag = true

    openConutDownTime(state.detail.endTimestamp, (time_str) => {
        state.count_down_time = time_str
        if (time_str == '00:00:00') {
            init()
        }
    })
}

async function showLoadResult() {
    state.status = 'close'
    state.close_status = '等待结果'
    getChromeStorage('userInfo', (_userInfo) => {
        if (_userInfo) {
            getUserSetting()
        }
    })
}

const getUserSetting = () => {
    getSetting({}).then((res) => {
        let { code, data } = res;
        if (code === 0) {
            state.notification_show = true
            state.notification_switch = data.noticeSwitch === 1 ? true : false;
        }
    });
}

onMounted(() => {
    state.process_mode = process.env.NODE_ENV
    state.postId = getQueryString('postId')
    state.window_origin = getQueryString('window_origin') || '';
    if (state.window_origin.indexOf('twitter.com') > -1) {
        state.tweetId = getQueryString('tweetId')
        state.tweet_author = getQueryString('tweet_author');
    }

    getTweetAuthor()
    init()
    onRuntimeMsg();
    // state.loading_show = true
    // state.status = 'not-open'
    // state.status = 'success'
    // state.status = 'close'
    // state.close_status = '已经过期了'
    // state.close_text = [`This Giveaways`, `expired on ${moment(state.detail.endTimestamp).format('MM-DD')}`]
    // state.close_status = '没有抽中'
    // state.close_status = '已过期'

})

function getTweetAuthor() {
    if (state.window_origin.indexOf('twitter.com') > -1) {
        window.parent.postMessage({
            actionType: "IFRAME_RED_PACKET_GET_TWEET_AUTHOR", data: {
                postId: state.postId,
                taskLuckdropId: state.detail.taskLuckdropId
            }
        }, "*");
    }
}

function checkFacebookReply() {
    console.log('checkFacebookReply')
    if (state.window_origin.indexOf('twitter.com') > -1) {
        window.parent.postMessage({
            actionType: "IFRAME_RED_PACKET_CHECK_FACEBOOK_REPLY", data: {
                postId: state.postId
            }
        }, "*");
    }
}

// 点击领取
function clickOpenRedPacket() {
    callEventPageMethod('CONTENT_GET_PINED', {})
    handleRedPacket()
}

function handleRedPacket() {
    state.loading_show = true
    getRedPacket({
        params: {
            postId: state.postId
        }
    }).then((res) => {
        if (res.code == 0) {
            init()
        } else {
            state.loading_show = false
            handleErrorCode(res)
        }
    }).catch(() => {
        state.loading_show = false
    })
    // 埋点
    Report.reportLog({
        pageSource: Report.pageSource.pending_page,
        businessType: Report.businessType.buttonClick,
        objectType: Report.objectType.open_button,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });
}

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

// 校验是否封路
function checkIsLogin() {

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

async function clickGetGiveaways() {
    let _userInfo = await checkIsLogin()
    if (_userInfo) {
        handleFinishRedPacket()
    }
}

function handleFinishRedPacket() {
    state.loading_show = true
    finishRedPacket({
        params: {
            postId: state.postId
        }
    }).then((res) => {
        if (res.code == 0) {
            if (res.data.finished) {
                state.receiveAmount = res.data.receiveAmount
                init()
                // 埋点
                Report.reportLog({
                    pageSource: Report.pageSource.task_page,
                    businessType: Report.businessType.buttonClick,
                    objectType: Report.objectType.get_giveaway,
                    postId: state.postId,
                    srcContentId: state.tweetId,
                    senderId: state.userId,
                    customCover: state.customCover,
                    customGiveaway: state.customGiveaway,
                }, {
                    get_giveaway_result: Report.extParams.success
                });
            } else {
                state.loading_show = false
                let _data = res.data.conditionResult
                for (let i in _data) {
                    switch (_data[i].type.toString()) {
                        case '1':
                            state.detail.taskCondition[0].relatedUsers = _data[i].detail
                            if (_data[i].finished) {
                                state.done.follow = true
                                state.done.follow_red = false
                            } else {
                                // alert('Please complete the task: follow')
                                state.done.follow = false
                                state.done.follow_red = true
                            }
                            break
                        case '2':
                            if (_data[i].finished) {
                                state.done.like = true
                                state.done.like_red = false
                            } else {
                                // alert('Please complete the task: like tweet')
                                state.done.like = false
                                state.done.like_red = true
                            }
                            break
                        case '3':
                            if (_data[i].finished) {
                                state.done.retweet = true
                                state.done.retweet_red = false
                            } else {
                                // alert('Please complete the task: Retweet')
                                state.done.retweet_red = true
                                state.done.retweet = false
                            }
                            break
                        case '7':
                            //join discord
                            discordAuthorizeRequired = _data[i].discordAuthorizeRequired;
                            if (_data[i].finished) {
                                state.done.join_discord = true
                                state.done.join_discord_red = false
                            } else {
                                state.done.join_discord = false;
                                state.done.join_discord_red = true
                            }
                            break
                        case '8':
                            //repost feacebook
                            if (_data[i].finished) {
                                state.done.repost_facebook = true
                                state.done.repost_facebook_red = false
                            } else {
                                state.done.repost_facebook = false;
                                state.done.repost_facebook_red = true
                            }
                            break
                        case '9':
                            //reply
                            if (_data[i].finished) {
                                state.done.reply = true
                                state.done.reply_red = false
                            } else {
                                state.done.reply = false;
                                state.done.reply_red = true
                            }
                            break
                    }
                }
                // 埋点
                Report.reportLog({
                    pageSource: Report.pageSource.task_page,
                    businessType: Report.businessType.buttonClick,
                    objectType: Report.objectType.get_giveaway,
                    postId: state.postId,
                    srcContentId: state.tweetId,
                    senderId: state.userId,
                    customCover: state.customCover,
                    customGiveaway: state.customGiveaway,
                }, {
                    get_giveaway_result: Report.extParams.failure,
                });
                if (discordAuthorizeRequired) {
                    discordAuth('reAuth');
                }
            }
        } else {
            state.loading_show = false
            // 埋点
            Report.reportLog({
                pageSource: Report.pageSource.task_page,
                businessType: Report.businessType.buttonClick,
                objectType: Report.objectType.get_giveaway,
                postId: state.postId,
                srcContentId: state.tweetId,
                senderId: state.userId,
                customCover: state.customCover,
                customGiveaway: state.customGiveaway,
            }, {
                get_giveaway_result: Report.extParams.failure,
            });
            handleErrorCode(res)
        }
    }).catch(() => {
        state.loading_show = false
    })
}


function handleErrorCode(res) {
    switch (res.code.toString()) {
        // 数据异常,请联系管理员
        case '-102':

            break
        //系统错误
        case '-101':

            break

        // 参数不对
        case '-103':
            break
        // 接口被限流
        case '-105':
            break

        // 访问凭证不存在
        case '-107':
            break
        // 重复操作过于频繁
        case '-106':
            message.error('Clicking too often, wait a moment and click again')
            state.loading_show = false
            break
        // 红包不存在
        case '2001':
            // message.error(res.msg)
            break
        // 还未到红包领取时间
        case '2002':
            // message.error(res.msg)
            break
        // 已超过红包领取时间
        case '2003':
            init()
            break
        // 红包支付状态异常 没有可提交的任务红包
        case '2004':
            init()
            break
        // 红包活动已结束
        case '2006':
            init()
            break
        // 红包金额已经被领取完了
        case '2007':
            state.status = 'close'
            state.close_status = '已经过期了'
            state.close_text = [`This Giveaways`, `expired on ${moment(state.detail.endTimestamp).format('MM-DD')}`]
            init()
            break
        // 红包个数已经被领取完了
        case '2008':
            state.status = 'close'
            state.close_status = '已经过期了'
            state.close_text = [`This Giveaways`, `expired on ${moment(state.detail.endTimestamp).format('MM-DD')}`]
            init()
            break
        // 该用户不满足领取条件
        case '2009':
            state.error_txt = [`oops, new accounts cannot participate in this event,`]
            state.status = 'error'
            state.retry = true
            // 埋点
            Report.reportLog({
                pageSource: Report.pageSource.robot_detection_failed_page,
                businessType: Report.businessType.pageView,
                postId: state.postId,
                srcContentId: state.tweetId,
                senderId: state.userId,
            });
            break
        // 无法校验用户Twitter信息
        case '2010':
            // message.error(res.msg)
            break
        // 用户已经领过该红包
        case '2011':
            // message.error(res.msg)
            break
        // 推文不存在
        case '2022':
            // message.error(res.msg)
            break
        // 推文未发布 and 不是红包任务的推文
        case '2023':
            // message.error(res.msg)
            break
        // 没有可提交的任务红包
        case '2024':
            state.status = 'not-open'
            break
        // 红包任务已完成
        case '2025':
            break
        // 任务已经过期
        case '2026':
            break
        // 任务未完成
        case '2027':
            break
        // 红包金额每人不足1分钱
        case '2028':
            break
        // 推文未发布
        case '2029':
            message.error('Tweet not posted')
            break
        // 不是红包任务的推文
        case '2030':
            break
        case '2037':
            showCloseEndTimePage()
            init()
            break
        //用户没有领取过红包，无法重抽
        case '2031':
            break
        // 需要重新授权 discord
        case '1010':
            discordAuth('reAuth');
            break
    }
}

// function clickBack() {
//   state.status = 'opened'
//   // 埋点
//   Report.reportLog({
//     pageSource: Report.pageSource.task_page,
//     businessType: Report.businessType.pageView,
//   });
// }

// function clickRoad() {
//   state.status = 'luck-peopel-list'
//   // 埋点
//   Report.reportLog({
//     pageSource: Report.pageSource.task_page,
//     businessType: Report.businessType.buttonClick,
//     objectType: Report.objectType.received_list
//   });
//   // 埋点
//   Report.reportLog({
//     pageSource: Report.pageSource.received_list_page,
//     businessType: Report.businessType.pageView
//   });
// }
function onWindowMessage() {
    window.addEventListener("message", function (event) {
        if (event.data) {
            switch (event.data.actionType) {
                case 'CONTENT_RED_PACKET_REPLY_RASK_FINSH':
                    state.done.reply = true;
                    state.done.reply_red = false;
                    break;
                case 'CONTENT_RED_PACKET_GET_TWEET_AUTHOR':
                    fullName = event.data.data.fullName
                    break;
                case 'CONTENT_RED_PACKET_FACEBOOK_REPLY':
                    clickReply(event.data.data)
                    break;
            }
        }
    });
}

function onPageVisbile() {
    document.addEventListener('visibilitychange', function () {
        let isHidden = document.hidden;
        if (!isHidden) {
            checkJoinDiscord();
        }
    });
}

function onRuntimeMsg() {
    chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
        ;
        switch (req.actionType) {
            case 'BACK_DISCORD_LOGIN_SUCCESS':
                discordLoginSuccess();
                break;
            case 'BG_FACEBOOK_SHARE_SUCCESS':
                facebookShareSuccess(req.data);
                break;
            case 'DO_TASK':
                if (!req.task_type || state.tweetId != req.tweet_Id) {
                    return
                }
                state.loading_show = false
                doTaskReport(req, sender);
                break;
            case 'CONTENT_RED_PACKET_REPLY_RASK_FINSH':
                if (req.data && req.data.postId == state.postId) {
                    state.done.reply = true;
                    state.done.reply_red = false;
                }
                break;
            case 'CONTENT_API_GET_TWEET_USER_INFO_RES':
                let { user } = req.data || {};
                if (req.tweetId == state.tweetId && user && user.result && user.result.legacy) {
                    let legacy = user.result.legacy;
                    reportParams.twitterFans = legacy ? legacy.followers_count : 0;

                    if (!discordTaskDetail) {
                        if (reportParams.hasReport) return;
                        reportParams.hasReport = true;
                        Report.reportLog({
                            objectType: Report.objectType.tweetPostBinded,
                            twitterFans: reportParams.twitterFans,
                            redPacketType: 1,
                            postId: state.postId
                        });
                    } else {
                        if (reportParams.discordFans !== '') {
                            if (reportParams.hasReport) return;
                            reportParams.hasReport = true;
                            Report.reportLog({
                                objectType: Report.objectType.tweetPostBinded,
                                twitterFans: reportParams.twitterFans,
                                discordFans: reportParams.discordFans,
                                redPacketType: 1,
                                postId: state.postId
                            });
                        }
                    }
                }
                break;
            case 'USER_SETTING':
                setNotification(req.data)
                break;
        }
        sendResponse && sendResponse();
    })
}

/**
 * 检查是否加入discord
 */
function checkJoinDiscord() {
    // 如果上次的状态是 joinIng 检查是否真正join
    if (joinDiscordActionState == 'joinIng') {
        joinDiscordActionState = 'default';
        let url = getInviteUrl();
        if (url) {
            joinDiscordIng.value = true;
            checkGuildJoinedStatus({ url }, (res = {}) => {
                joinDiscordIng.value = false;
                if (res.code == 0) {
                    let { joined } = res.data || {};
                    if (joined) {
                        state.done.join_discord = true;
                    } else {
                        state.done.join_discord = false;
                    }
                } else if (res.code == 1010) {
                    discordAuth('reAuth');
                }
            })
        }
    }
}


const checkGuildJoinedStatus = ({ url }, cb) => {
    checkGuildJoined({
        params: {
            inviteUrl: url
        }
    }).then(res => {
        cb && cb(res);
    }).catch(err => {
        cb && cb({ catch: true })
    })
}

/**
 * 加入discord 事件
 */
async function joinDiscord() {
    let _userInfo = await checkIsLogin();
    if (!_userInfo) {
        return
    }
    if (joinDiscordIng.value) {
        return;
    }
    // 埋点
    Report.reportLog({
        objectType: Report.objectType.join_discord,
        pageSource: Report.pageSource.task_page,
        businessType: Report.businessType.buttonClick,
        postId: state.postId,
        srcContentId: state.tweetId,
        senderId: state.userId,
        redPacketType: 1,
        customCover: state.customCover,
        customGiveaway: state.customGiveaway,
    });

    let url = getInviteUrl();
    if (url) {
        joinDiscordIng.value = true;
        checkGuildJoinedStatus({ url }, (res) => {
            setTimeout(() => {
                joinDiscordIng.value = false;
            }, 1500);
            if (res.code == 0) {
                let { joined } = res.data || {};
                if (joined) {
                    state.done.join_discord = true;
                } else {
                    state.done.join_discord = false;
                    if (discordAuthorizeRequired) {
                        discordAuth('authAndJoinIng');
                    } else {
                        openInviteUrl();
                    }
                }
            } else if (res.code == 1010) {
                discordAuth('authAndJoinIng');
            }
            if (res.catch) {
                //判断是否需要授权
                if (discordAuthorizeRequired) {
                    discordAuth('authAndJoinIng');
                } else {
                    openInviteUrl();
                }
            }
        })
    }
}

/**
 * discord授权
 */
function discordAuth(actionState = 'default') {
    let state = guid();
    discordAuthUrl({
        params: {
            redirectUrl: discordAuthRedirectUri,
            state
        }
    }).then(res => {
        if (res.code == 0) {
            let { authorizeUrl = '' } = res.data || {};
            if (authorizeUrl) {
                joinDiscordActionState = actionState;
                const width = 500;
                chrome.windows.create({
                    width,
                    type: 'normal',
                    url: authorizeUrl
                }, function (window) {
                    let windowId = window.id;
                    callEventPageMethod("RED_PACKET_SAVE_DISCORD_AUTH_WINDOW_ID", {
                        windowId: windowId
                    });
                })
            }
        }
    })
}

/**
 * sendMessage
 */
const callEventPageMethod = (actionType, data, callback) => {
    chrome.runtime.sendMessage(
        {
            actionType: actionType,
            data: data
        },
        function (response) {
            if (typeof callback === "function") callback(response);
        }
    );
};

/**
 * discord 授权成功
 */
function discordLoginSuccess() {
    console.log('discordloginSuccess');
    // 如果是授权并join 默认打开 邀请链接
    if (joinDiscordActionState == 'authAndJoinIng') {
        openInviteUrl();
    }
    if (discordAuthorizeRequired) {
        discordAuthorizeRequired = false;
    }
}

/**
 * 获取discord邀请链接
 */
function getInviteUrl() {
    let inviteData = state.detail.taskCondition.find(item => {
        return item.type == 7;
    });
    let url;
    if (inviteData && inviteData.bizData) {
        url = JSON.parse(inviteData.bizData).inviteUrl;
    }
    return url;
}

/**
 * 打开邀请discord链接
 */
function openInviteUrl() {
    joinDiscordActionState = 'joinIng';
    let url = getInviteUrl();
    if (url) {
        if (!url.startsWith('http')) {
            url = 'https://' + url;
        }
        window.open(url);
    }
}

</script>

<style lang="scss" scoped>
html,
body {
    margin: 0;
    padding: 0;
    width: 375px;
    height: 500px;
    background-color: unset !important;
}

:deep() .ant-switch {
    background-color: #E9ECEE;
    height: 14px;
    line-height: 16px;
    min-width: 36px;
}

:deep() .ant-switch-checked {
    background-color: #AED8F5 !important;
}

:deep() .ant-switch::after {
    width: 20px;
    height: 20px;
    top: -4px;
    left: -1px;
}

:deep() .ant-switch-checked::after {
    background-color: #1D9BF0 !important;
    margin-left: 3px;
    left: 100% !important;
}

.content {
    position: relative;
    width: 375px;
    height: 500px;
    background: #fafafa;
    overflow: hidden;
    box-sizing: border-box;
    font-family: "SF Pro Display";
    font-style: normal;

    .loading {
        background: #FFFFFF;
        opacity: 0.8;
        z-index: 222;
        text-align: center;
        width: 375px;
        height: 500px;
        position: fixed;
        top: 0;
        left: 0;

        img {
            margin-top: 216px;
            width: 70px;
            height: 70px;
        }
    }

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

        img {
            margin-top: 172px;
            width: 130px;
            height: 130px;
        }
    }

    .error {
        width: 100%;
        height: 100%;
        text-align: center;
        position: relative;

        img {
            width: 100px;
            height: 100px;
            margin-top: 100px;
        }

        .txt {
            font-weight: 500;
            font-size: 22px;
            line-height: 26px;
            text-align: center;
            letter-spacing: 0.3px;
            color: #a8a8a8;
            margin: 34px 44px 0 44px;
        }

        .retry {
            position: absolute;
            bottom: 30px;
            left: 50%;
            margin-left: -167.5px;
            width: 335px;
            height: 46px;
            line-height: 46px;
            text-align: center;
            border-radius: 100px;
            border: 1px solid #1D9BF0;
            background: rgba(196, 196, 196, 0.01);
            color: #1D9BF0;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
        }
    }

    .success,
    .close,
    .luck-peopel-list {
        filter: drop-shadow(0px 4px 94px rgba(0, 0, 0, 0.3));
        width: 100%;
        height: 100%;
        border-radius: 11px;
        background: #fff;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .close-title {
            width: 100%;
            font-weight: 600;
            font-size: 27px;
            line-height: 32px;
            text-align: center;
            letter-spacing: 0.3px;
            font-weight: 800;
            font-size: 22px;
            color: #ffffff;
        }

        .head {
            padding: 14px 16px;

            img {
                cursor: pointer;
                width: 24px;
                height: 24px;
            }
        }

        .header {
            text-align: center;
            min-height: 160px;
            width: 100%;
            background: #fff;
            // padding-top: 30px;
            background-size: 100% 100%;
            position: relative;
            display: flex;
            align-content: center;
            flex-wrap: wrap;

            .rabbit {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                align-content: center;
                flex-wrap: wrap;
                justify-content: center;

                img {
                    width: 150px;
                    height: 80px;
                    margin-bottom: 6px;
                }

                .flower {
                    width: 62px;
                    height: 62px;
                }

                p {
                    width: 100%;
                    margin: 0;
                    padding: 0;
                    font-size: 22px;
                    font-weight: 800;

                    color: #fff;
                    text-align: center;
                    letter-spacing: 0.3px;
                }
            }

            .done {
                cursor: pointer;
                position: absolute;
                top: 107px;
                left: 50%;
                margin-left: -150px;
                width: 300px;
                height: 60px;
                display: flex;
                align-items: center;
                border-radius: 100px;
                background: #ffffff;
                box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
                justify-content: center;

                span {
                    color: #000000;
                    font-size: 14px;
                }

                .icon-done {
                    width: 24px;
                    height: 24px;
                    margin-right: 10px;
                }

                .icon-right {
                    margin-left: 5px;
                    width: 7px;
                    height: 14px;
                }
            }

            .title {
                margin-top: 30px;
                color: #fff7e4;
                opacity: 0.6;

                font-weight: 700;
                font-size: 18px;
                line-height: 21px;
                letter-spacing: -0.3px;
            }

            .money {
                margin-bottom: 30px;
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;

                img {
                    width: 40px;
                    height: 40px;
                    margin-right: 9px;
                    border-radius: 50%;
                    border: solid 2px #fff;
                }

                .big {
                    font-weight: 700;
                    font-size: 46px;
                    line-height: 55px;
                    /* identical to box height */

                    letter-spacing: 0.3px;

                    color: #fff;
                }

                .small {
                    margin-left: 4px;

                    font-weight: 700;
                    font-size: 13px;
                    line-height: 16px;
                    /* identical to box height */

                    letter-spacing: 0.5px;

                    color: #fff;
                }
            }

            .custom-prize-show {
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 44px;
                margin-top: 20px;

                img {
                    width: 24px;
                    height: 24px;
                    margin-right: 9px;
                }
            }
        }



        .luck-list-title {
            /*      margin-top: 47px;*/
            margin: 0 16px;
            padding: 14px 0 11px 0;
            background: #fff;
            display: flex;
            justify-content: space-between;
            color: #B0B0B0;
            font-weight: 500;
            border-bottom: 1px solid #F2F2F2;

            div:last-child {
                text-align: right;
            }

            .text {
                cursor: pointer;
            }
        }

        .luck-list {
            background: #fff;
            overflow: auto;

            &.max {
                height: 250px;
            }

            .empty {
                width: 100%;
                height: 100%;
                text-align: center;

                img {
                    margin-top: 70px;
                    width: 100px;
                    height: 100px;
                }
            }

            .luck-item {
                display: flex;
                padding: 10px 0;
                margin: 0 16px;
                border-bottom: 1px solid #F2F2F2;
                justify-content: space-between;
                position: relative;

                .win {
                    position: absolute;
                    left: 28px;
                    bottom: 7px;
                    width: 20px;
                    height: 20px;
                }

                img:first-child {
                    border-radius: 50%;
                }

                .luck-king {
                    position: absolute;
                    top: 36px;
                    right: 0px;
                    display: flex;
                    align-items: center;

                    img {
                        width: 22px;
                        height: 19px;
                        margin: 0;
                    }

                    span {
                        font-weight: 500;
                        font-size: 12px;
                        line-height: 14px;
                        letter-spacing: 0.3px;
                        color: #f5b945;
                    }
                }

                img {
                    cursor: pointer;
                    width: 42px;
                    height: 42px;
                    margin-right: 12px;
                }

                .luck-content {
                    flex: auto;

                    .luck-title {
                        color: #444444;
                        font-weight: 500;
                        font-size: 16px;
                        letter-spacing: 0.3px;
                        margin-bottom: 5px;
                    }

                    .luck-time {
                        font-weight: 400;
                        font-size: 12px;
                        line-height: 14px;
                        color: #B0B0B0;
                    }
                }

                .luck-money {
                    display: flex;
                    height: 17px;
                    align-items: center;
                    height: 100%;

                    img {
                        width: 14px;
                        height: 14px;
                        margin-right: 6px;
                    }

                    .luck-money-txt {
                        font-weight: 500;
                        font-size: 14px;
                        word-break: break-all;
                        /* identical to box height */

                        text-align: right;
                        letter-spacing: 0.3px;

                        color: #444444;
                    }
                }

                .luck-custom-prize {
                    font-weight: 500;
                    font-size: 14px;
                    letter-spacing: 0.3px;
                    color: #F5B945;
                }
            }

            .luck-item:last-child {
                border: 0;
            }
        }
    }

    .close {
        position: relative;

        .load-result {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            text-align: center;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-content: flex-start;

            .title {
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 36px;

                img {
                    width: 26px;
                    height: 26px;
                    margin-right: 10px;
                }

                span {
                    color: #FFFFFF;
                    font-size: 18px;
                    font-weight: 800;
                    letter-spacing: 0.3px;

                }
            }

            .ticket {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 163px;

                img {
                    width: 250px;
                    height: 103px;
                    animation: myfirst 0.5s;
                }

            }

            .div-ticket {
                position: relative;
                overflow: hidden;
                transition-delay: 1s;
            }

            .div-ticket:after {
                position: absolute;
                right: -100%;
                /*改变left的值，让其相对box影藏*/
                top: 0;
                width: 30%;
                height: 100%;
                content: "";
                /* Safari 5.1 - 6.0 */
                background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, .3) 50%, rgba(255, 255, 255, 0) 100%);
                /* Opera 11.1 - 12.0 */
                background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, .3) 50%, rgba(255, 255, 255, 0) 100%);
                /* Firefox 3.6 - 15 */
                background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, .3) 50%, rgba(255, 255, 255, 0) 100%);
                /* 标准的语法 */
                background: linear-gradient(to right, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, .3) 50%, rgba(255, 255, 255, 0) 100%);
                transform: skewX(45deg);
                animation: div_light 1s;
                animation-delay: 0.5s;
            }

            // .div-ticket:hover:after {
            //     right: 150%;
            //     transition: 1s ease;
            // }

            p {
                width: 100%;
                margin: 0;
                padding: 0;
                color: #FCAB40;
                text-align: center;
                letter-spacing: 0.3px;
                font-size: 18px;
                font-weight: 700;

            }

            .time {
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 16px;

                img {
                    width: 22px;
                    height: 22px;
                    margin-right: 10px;
                }

                span {
                    font-weight: 800;
                    font-size: 28px;
                    color: #3F3F3F;
                }
            }



            .notification_switch {
                border-top: 1px solid #EFEFEF;
                justify-content: space-between;
                position: absolute;
                height: 48px;
                width: 100%;
                display: flex;
                align-items: center;
                bottom: 0;
                padding: 0 22px 0 16px;

            }
        }
    }



    .success {
        .header {

            min-height: 180px;
            align-content: flex-start;

            .success-title {
                color: #FFFFFF;
                font-weight: 800;
                font-size: 21px;
                line-height: 27px;
                margin-top: 28px;
                text-align: center;
                width: 100%;
            }

            .done {
                top: 130px;
            }
        }

        .luck-list-title {
            margin-top: 10px;
            border-bottom: 1px solid #ECECEC;
        }

        .header-custom-prize {
            align-items: flex-start;

            .success-title {
                line-height: 21px;
                margin-top: 23px;
                font-size: 18px;
            }
        }
    }

    .opened {
        filter: drop-shadow(0px 4px 94px rgba(0, 0, 0, 0.3));
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        border-radius: 11px;
        overflow: hidden;

        .header {
            text-align: center;
            min-height: 110px;
            width: 100%;
            background: #fff;
            // padding-top: 30px;
            background-size: 100% 100%;
            display: flex;
            flex-wrap: wrap;
            align-content: center;
            justify-content: center;

            img {
                width: 52px;
                height: 52px;
                margin-right: 14px;
            }

            .txt {
                color: #FFFFFF;
                font-weight: 700;
                font-size: 18px;
                letter-spacing: 0.3px;

                p {
                    margin: 0;
                    padding: 0;
                    text-align: left;
                }
            }
        }

        .list {
            overflow-y: auto;
            padding: 0 16px 0 16px;
            background: #ffffff;
            flex: 1;

            .item {
                display: flex;
                align-items: center;
                // min-height: 50px;
                border-bottom: 1px solid #f0f0f0;
                padding: 12px 0;
                box-sizing: border-box;

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

                .red-right {
                    width: 35px;
                    height: 24px;
                }

                .item-content {
                    width: 100%;
                    flex: 1;


                    .item-follow-title {
                        display: flex;
                        align-items: center;
                        margin-top: 20px;
                        margin-bottom: 11px;
                        position: relative;

                        .btn {
                            // position: absolute;
                            // right: 0;
                        }
                    }

                    .item-title {
                        flex: 1;
                        margin-left: 10px;
                        font-weight: 500;
                        font-size: 15px;
                        letter-spacing: 0.3px;
                        color: #000000;
                    }

                    .item-follow-area {
                        display: flex;
                        flex-wrap: wrap;

                        .item-follow {
                            cursor: pointer;
                            border: 1px solid #ebebeb;
                            border-radius: 1000px;
                            height: 26px;
                            margin-right: 5px;
                            margin-bottom: 5px;
                            display: flex;
                            align-items: center;

                            .finished {
                                text-decoration: line-through;
                                color: #949494;
                            }

                            span {
                                margin-left: 8px;
                                margin-right: 2px;
                                color: #1D9BF0;
                                opacity: 1;
                            }

                            img {
                                width: 16px;
                                height: 16px;
                                margin-right: 7px;
                            }
                        }
                    }

                    span {
                        font-weight: 400;
                        font-size: 11px;
                        line-height: 13px;
                        letter-spacing: 0.3px;

                        color: #000000;

                        opacity: 0.4;
                    }
                }

                .btn {
                    width: 90px;
                    height: 29px;
                    line-height: 29px;
                    background: rgba(56, 154, 255, 0.1);
                    border-radius: 500px;
                    text-align: center;
                    letter-spacing: 0.3px;
                    color: #1D9BF0;
                    cursor: pointer;
                }

                .loading-wrapper {
                    width: 90px;
                    text-align: center;

                    .icon-loading {
                        animation: loading 1s infinite linear;
                    }
                }
            }
        }

        .people {
            cursor: pointer;
            padding-left: 16px;
            height: 38px;
            line-height: 38px;
            background: #fff;
            box-shadow: 0px 1px 0px #f2f2f2;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .txt {
                width: 90%;
                font-weight: 400;
                font-size: 12px;
                line-height: 14px;
                letter-spacing: 0.3px;
                color: #000000;
                opacity: 0.4;
            }


        }

        .footer {
            background: #ffffff;
            display: flex;
            padding: 15px 22px 15px 17px;

            .btn {
                background: #1D9BF0;
                border-radius: 100px;
                color: #fff;
                width: 100%;
                height: 48px;
                font-weight: 600;
                font-size: 18px;
                line-height: 48px;
                text-align: center;
                cursor: pointer;
            }

            .grey {
                background: #DDDDDD;
                cursor: auto;
            }
        }
    }

    .not-open {
        width: 100%;
        height: 100%;
        filter: drop-shadow(0px 2px 20px rgba(0, 0, 0, 0.1));
        position: relative;
        overflow: hidden;
        border-radius: 11px;

        .customImg {
            width: 100%;
            min-height: 373px;
        }

        .customBottom {
            width: 100%;
            height: 125px;
            background: #111214;
            padding: 10px 16px;
            font-weight: 500;
            font-size: 12px;
            line-height: 14px;
            letter-spacing: 0.3px;
            color: #838383;
            line-height: 20px;

            .theme {
                display: flex;
                height: 20px;
                align-items: center;
                justify-content: flex-start;

                .icon {
                    width: 12px;
                }

                .time {
                    margin: 0 4px;
                    color: #1D9BF0;
                }
            }

            .winner-info {
                display: flex;
                height: 20px;
                align-items: center;
                justify-content: flex-start;
                margin-bottom: 13px;

                .count {
                    color: #1D9BF0;
                    margin-right: 4px;
                }

                .prize-name {
                    color: #1D9BF0;
                    margin-left: 4px;
                }
            }

            .open-red {
                height: 45px;
                background: linear-gradient(180deg, #4AB6FF 0%, #1D9BF0 100%, #1D9BF0 100%);
                border: 1.5px solid rgba(255, 255, 255, 0.15);
                border-radius: 52px;
                line-height: 45px;
                text-align: center;
                cursor: pointer;
                font-weight: 800;
                font-size: 16px;
                color: #FFFFFF;
            }
        }

        .money-area {
            width: 100%;
            position: absolute;
            top: 65px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;

            .time-area {
                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;
                width: 100%;
                height: 46px;

                div {
                    width: 100%;
                    height: 100%;
                    position: absolute;
                    background: #000000;
                    z-index: 0;
                    opacity: 0.15;
                }

                img {
                    z-index: 1;
                    width: 26px;
                    height: 26px;
                    margin-right: 10px;
                }

                span {
                    z-index: 1;
                    color: #FFCC4D;
                    font-weight: 900;
                    font-size: 26px;

                }
            }

            .mark-area {
                width: 100%;
                display: flex;
                justify-content: center;

                img {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }

                .time {
                    display: flex;
                    align-items: center;

                    span {
                        color: #FFFFFF;
                        font-weight: 800;
                        font-size: 17px;
                        letter-spacing: 0.05em;
                        line-height: 22px;


                    }

                }

                .win {
                    display: flex;
                    align-items: center;
                    margin-left: 12px;
                    color: #FFCC4D;
                    letter-spacing: 0.05em;
                    line-height: 22px;
                    font-size: 17px;
                    font-weight: 800;

                }
            }

            .txt {
                font-weight: 800;
                font-size: 16px;
                text-align: center;
                letter-spacing: 0.3px;
                color: #FFFFFF;
            }

            .coin {
                text-align: center;
                margin-top: 6px;
                /*margin-bottom: 7px;*/
                display: flex;
                justify-content: center;
                align-items: center;
                width: 90%;

                img {
                    width: 46px;
                    height: 46px;
                    border-radius: 50%;
                    border: 3px solid #FFFFFF;
                }

                span {
                    margin-left: 12px;
                    font-weight: 800;
                    font-size: 60px;
                    line-height: 76px;
                    color: #FFFFFF;
                }
            }

            .people {
                font-weight: 800;
                font-size: 13px;
                line-height: 16px;
                letter-spacing: 0.05em;
                text-align: center;
                color: #FFFFFF;
            }
        }

        .title {
            position: absolute;
            top: 15px;
            left: 15px;
            z-index: 3;
            display: flex;
            align-items: center;

            img {
                width: 24px;
                height: 24px;
                border: 2px solid #FFF;
                border-radius: 50%;
            }

            span {
                margin-left: 10px;
                font-weight: 600;
                font-size: 16px;
                letter-spacing: 0.3px;
                color: #fff;
            }
        }

        // .txt {
        //   width: 100%;
        //   position: absolute;
        //   font-style: normal;
        //   font-weight: 700;
        //   font-size: 42px;
        //   line-height: 50px;
        //   text-align: center;

        //   color: #FFF2D3;
        //   top: 90px;
        //   z-index: 3;
        // }

        img {
            width: 100%;
        }

        .up {
            position: absolute;
            top: 0;
            // box-shadow: 0px 4px 44px rgba(0, 0, 0, 0.1);
            z-index: 1;
        }

        .down {
            position: absolute;
            top: 253px;
        }

        .open {
            width: 335px;
            height: 50px;
            cursor: pointer;
            position: absolute;
            bottom: 28px;
            left: 50%;
            margin-left: -167.5px;
            z-index: 4;
        }

        .open-gif {
            width: 200px;
            height: 200px;
            text-align: center;
            position: absolute;
            bottom: 80px;
            left: 50%;
            margin-left: -100px;
            z-index: 3;
        }
    }

    @keyframes loading {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}


@keyframes div_light {
    0% {
        right: -100%;
    }



    100% {
        right: 150%;
    }
}

@keyframes myfirst {
    0% {
        width: 250px;
        height: 103px;
    }

    50% {
        width: 300px;
        height: 153px;
    }

    100% {
        width: 250px;
        height: 103px;
    }
}

.none {
    display: flex;
    align-item: center;
    justify-content: center;
    width: 100%;
    height: 100%;
}
</style>
