<template>
    <div class="nft" :class="{ border: isShare }">
        <template v-if="!isLoading">
            <div class="title">
                <div class="tag" :class="{ share: !isShare }">
                    <img class="logo" :src="saleData.nftProjectAvatar" />
                    <font class="text" :class="{ share: !isShare }">{{saleData.nftProjectName}}</font>
                    <img class="tagImg" :src=" require('@/assets/img/icon-nft.png') " />
                </div>
                <div class="share" v-if="!isShare" @click="share">
                    <img :src=" require('@/assets/img/icon-ntf-share.png') " />
                </div>
            </div>
            <div
                class="content"
                v-show-log="{
                    pageSource: isShare ? Report.pageSource.nft_post_page : Report.pageSource.nft_sales_window,
                    nftProjectId: nftProjectId,
                    redPacketType: Report.redPacketType.nftSale,
                }">
                <img :src="saleData.windowImagePath" />
            </div>
            <div
                v-if="saleData.purchaseStatus === 0"
                class="buy disabled">
                <img class="guide" v-if="isShowGuide" :src=" require('@/assets/img/icon-arrow.png') " />
                <button>Buy NFT</button>
            </div>
            <div
                v-else
                class="buy"
                @click="buy"
                v-click-log="{
                    pageSource: isShare ? Report.pageSource.nft_post_page : Report.pageSource.nft_sales_window,
                    objectType: Report.objectType.buy_nft_button,
                    nftProjectId: nftProjectId,
                    redPacketType: Report.redPacketType.nftSale,
                }">
                <img class="guide" v-if="isShowGuide" :src=" require('@/assets/img/icon-arrow.png') " />
                <button>Buy NFT</button>
            </div>
        </template>
    </div>
</template>

<script setup>
import Report from "@/log-center/log"
import { onBeforeMount, ref, onMounted, onBeforeUnmount } from 'vue'
import { getTwitterSaleNftProjectInfo, getNftProjectInfo } from '@/http/nft'
import { pageUrl } from "@/http/configAPI.js"
import { getChromeStorage, setChromeStorage } from '@/uilts/chromeExtension.js'
const saleData = ref({});
const isShare = ref(false);
const isLoading = ref(true);
const isShowGuide = ref(false);
const nftProjectId = ref('');

const getSaleInfo = () => {
    chrome.tabs.getCurrent((tab) => {
        let url = new URL(tab.url);
        let pathname = url.pathname;
        let pathArr, account;
        if (pathname) {
            pathname = decodeURIComponent(pathname);
            pathname = pathname.slice(1);
            pathArr = pathname.split('/');
            account = pathArr[0];
            getSaleProjectInfo(account);
        }
    })
}

const getSaleData = (projectId) => {
    getNftProjectInfo({
        params: {
            nftProjectId: projectId
        }
    }).then(res => {
        let { data } = res;
        if (data !== null) {
            // setData
            saleData.value = data;
            isLoading.value = false;
        }
    })
}

const getSaleProjectInfo = (account) => {
    getTwitterSaleNftProjectInfo({
        params: {
            twitterAccount: account
        }
    }).then(res => {
        let { data } = res;
        if (data !== null) {
            // setData
            saleData.value = data;
            isLoading.value = false;
            // postMessage
            chrome.tabs.getCurrent((tab) => {
                chrome.tabs.sendMessage(tab.id, { actionType: "IFRAME_NFT_SHOW_SALE" });
            })
            getChromeStorage('nft_guide', (info) => {
                if (!info) {
                    isShowGuide.value = true
                    setTimeout(() => {
                        setChromeStorage({ nft_guide: Date.now() })
                    }, 2000)
                }
            })
        }
    })
}

const share = () => {
    chrome.tabs.getCurrent((tab) => {
        let tagUrl = new URL(tab.url);
        let tagPathName = tagUrl.pathname.slice(1);
        let tagSearch = ``;
        if (tagPathName) {
            let tagArr = tagPathName.split('/');
            tagSearch = `${btoa(tagArr[0])}`
        }
        let url = pageUrl + `/nft/${saleData.value.nftProjectId}/${tagSearch}`
        let content = `#DNFT\r\r${url}`
        chrome.tabs.getCurrent((tab) => {
            chrome.tabs.sendMessage(tab.id, { actionType: "IFRAME_TWITTER_PUBLISH", publishRes: { srcContent: content }  });
        });
    });
}

const buy = () => {
    getChromeStorage('userInfo', (_userInfo) => {
        if (!_userInfo) {
            setChromeStorage({ buyNFTCardData: JSON.stringify({ action: 'buy' })});
            chrome.runtime.sendMessage(
                { actionType: "POPUP_LOGIN", data: "" },
                (response) => {
                    console.log("res", response);
                }
            )
        } else {
            chrome.tabs.getCurrent((tab) => {
                chrome.tabs.sendMessage(tab.id, {
                    actionType: "IFRAME_TWITTER_SHOW_BUY_NFT",
                    data: {
                        nft_project_Id: saleData.value.nftProjectId
                    }
                }, (res) => { });
            })
        }
    })
}

const loginSuccessHandler = async () => {
    let {action = ''} = await getChromeStorage('buyNFTCardData') || {};
    if(action == 'buy') {
        chrome.storage.local.remove("buyNFTCardData");
        buy();
    }
} 

onBeforeMount(() => {
    let urlParams = new URL(window.location.href);
    let searchParmas = new URLSearchParams(urlParams.search);
    let projectId = searchParmas.get('projectId') || '';
    if (projectId) {
        isShare.value = true;
        nftProjectId.value = projectId;
        getSaleData(projectId)
    } else {
        getSaleInfo()
    }
})

const onRuntimeMsg = () => {
    chrome.runtime.onMessage.addListener(msgListener)
}


const msgListener = (req, sender, sendResponse) => {
    switch (req.actionType) {
        case 'BG_LOGIN_SET_USERINFO_CB':
            loginSuccessHandler();
            break;
    }
    sendResponse && sendResponse();
}

onMounted(() => {
    onRuntimeMsg();
})


onBeforeUnmount(() => {
    chrome.runtime.onMessage.removeListener(msgListener);
})
</script>

<style lang='scss'>
body {
    margin: 0;
    padding: 0;
}

.nft {
    width: 100%;
    height: 290px;
    user-select:none;
    border-radius:20px;
    background:#F7F9F9;
    &.border {
        box-sizing: border-box;
        border: solid 1px #DCDCDC;
    }
    .title {
        height: 46px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .tag {
            display: flex;
            max-width: 93%;
            align-items: center;
            padding-left: 15px;
            &.share {
                max-width: 84%;
            }

            .logo {
                overflow: hidden;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background-color: #eee;
            }

            .text {
                font-size: 18px;
                font-weight: bold;
                max-width: calc(100% - 80px);
                margin: 0 7px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                &.share {
                    max-width: calc(100% - 80px);
                }
            }

            .tagImg {
                width: 37px;
                height: 22px;
            }
        }

        .share {
            cursor: pointer;
            padding-right: 10px;

            img {
                width: 19px;
                height: 18px;
            }
        }
    }

    .content {
        height: 190px;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .buy {
        position: relative;
        height: 54px;
        display: flex;
        justify-content: center;
        &.disabled {
            opacity: .1;
        }
        .guide {
            position: absolute;
            top: 6px;
            right: 30%;
            width: 26px;
            animation: fade 1s infinite;
        }
        button {
            width: 100%;
            height: 34px;
            margin: 0 20px;
            cursor: pointer;
            color: #ffffff;
            font-size: 15px;
            font-weight: bold;
            background: #000;
            border: 0;
            border-radius: 44px;
        }
    }
}

@keyframes fade {
    0%, 100% {
        opacity: .5;
        transform: scale(1);
    }
    50% {
        opacity: 1;
        transform: scale(1.4);
    }
}
</style>
