<template>
    <div class="editor-preview-wrapper">
        <div class="top">
            <div class="card-container">
                <!-- 安装之后的卡片样式 -->
                <div class="content-after" v-show="installStatus" :style="{ 'width': reviewCanvasParams.width + 'px' }">
                    <div class="head" :style="{ 'zoom': reviewCanvasParams.zoom }">
                        <img :src="userInfo.avatarUrl" class="avatar" />
                        <div class="article-wrapper">
                            <div class="nickname">
                                {{ userInfo.name }}
                            </div>
                            <div class="name">
                                @{{ userInfo.nickName }}
                            </div>
                        </div>
                    </div>
                    <div class="after-cover-wrapper" :style="{ 'zoom': reviewCanvasParams.zoom }">
                        <install-card :pre_view="true" :iframe_url="previewData.convertUrl"></install-card>
                    </div>
                </div>

                <!-- 安装之前的卡片样式 -->
                <div class="content-before" v-show="!installStatus"
                    :style="{ 'width': reviewCanvasParams.width + 'px' }">
                    <div class="head" :style="{ 'zoom': reviewCanvasParams.zoom }">
                        <img :src="userInfo.avatarUrl" class="avatar" />
                        <div class="article-wrapper">
                            <div class="nickname">
                                {{ userInfo.name }}
                            </div>
                            <div class="name">
                                @{{ userInfo.nickName }}
                            </div>
                        </div>
                    </div>
                    <div class="card-wrapper" :style="{ 'zoom': reviewCanvasParams.zoom }">
                        <img class="cover" v-if="previewData.linkImagePath && previewData.appId"
                            :src="previewData.linkImagePath" />
                        <iframe class="iframe" :src="previewData.convertUrl" scrolling="no" v-else></iframe>

                        <div class="bottom-bar">
                            <div class="site-url">DeNet.me</div>
                            <div class="desc">
                                <template v-if="previewData.appId">
                                    {{ previewData.currentApp.linkTitle }}
                                </template>
                                <template v-else>
                                    {{ previewData.currentApp.defaultTit ? defaultLinkTitle :
                                            previewData.currentApp.name
                                    }}
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="font">
                Preview: <span>{{ installStatus ? 'After' : 'Before' }}</span> DeNet Installed
            </div>
        </div>
        <div class="bottom">
            <div class="btn" @click="publishHandler">NEXT</div>
        </div>
    </div>
</template>

<script setup>
import { ref, defineEmits, reactive, defineProps, onMounted, nextTick, onUnmounted, watch } from "vue";
import { message } from "ant-design-vue";

import installCard from '@/view/content/tool-box/index.vue'
import { postPublish } from "@/http/publishApi";
import { getChromeStorage, setChromeStorage } from "@/uilts/chromeExtension"
import { getUser } from "@/http/publishApi"

let installStatus = ref(false);

let userInfo = ref({});
let submitIng = ref(false);

let reviewCanvasParams = reactive({
    width: 620,
    zoom: 1
});
let timer = ref(null);

let loadingHide = null;

const props = defineProps({
    previewData: {
        type: Object,
        default: () => {
            return {
                convertUrl: '',
                originUrl: '',
                appId: ''
            }
        }
    },
    screenshotWebsiteData: {
        type: Object,
        default: () => {
            return {
                url: '',
                status: ''
            }
        }
    },
    defaultLinkTitle: {
        type: String,
        default: ''
    },
    showCom: {
        type: String,
        default: 'EDITOR'
    }
})

watch(() => props.screenshotWebsiteData,
    (newVal) => {
        let { appId } = props.previewData;
        if (loadingHide && !appId && (newVal.url || newVal.status)) {
            loadingHide();
            loadingHide = null;
            submitPublish();
        }
    },
    {
        deep: true
    })

watch(() => props.showCom,
    (newVal) => {
        if (newVal == 'EDITOR' && loadingHide) {
            loadingHide();
            loadingHide = null;
        }
    },
    {
        deep: true
    })

const emits = defineEmits(["publishFinish"]);

const getUserInfo = (cb) => {
    getChromeStorage('userInfo', (res) => {
        if (res) {
            userInfo.value = res;
        }
        cb && cb(res);
    })
}

const getUserName = (screenName) => {
    getUser({
        params: {
            screenName
        }
    }).then(res => {
        console.log(res);
        if (res.code == 0) {
            userInfo.value.name = res.data.name || ''
        }
    });
}

const calcPreviewCanvasParams = () => {
    nextTick(() => {
        let containerDom = document.querySelector('.card-container');
        let domHeight = containerDom && containerDom.offsetHeight || 500;
        const canvasHeight = 780, canvasWidth = 620;
        if (domHeight < canvasHeight) {
            //比例: 高 / 宽
            let hWRatio = canvasHeight / canvasWidth;
            //缩小宽度 = 高度 / 比例  
            let width = domHeight / hWRatio;
            if (width > canvasWidth) {
                width = canvasWidth;
            }
            //缩小比例 
            let zoom = width / canvasWidth;
            if (zoom > 1) {
                zoom = 1;
            }
            reviewCanvasParams.width = width;
            reviewCanvasParams.zoom = zoom;
        } else {
            reviewCanvasParams.width = canvasWidth;
            reviewCanvasParams.zoom = 1;
        }
    });
}

const publishHandler = () => {
    let { appId } = props.previewData;
    if (loadingHide) {
        return;
    }

    if (!appId && !props.screenshotWebsiteData.url) {
        loadingHide = message.loading('loading...', 0);
        return;
    }

    submitPublish();
}

const submitPublish = () => {
    let { convertUrl, originUrl, appId, currentApp } = props.previewData;

    if (submitIng.value) {
        return;
    }

    setHistoryData(currentApp);

    let linkTitle = currentApp.defaultTit ? '' : currentApp.name;

    let postBizData = {
        convertUrl,
        originUrl,
        appId,
        linkTitle: !appId ? linkTitle : '',
        linkImagePath: props.screenshotWebsiteData.url
    };
    let data = {
        params: {
            postBizData: JSON.stringify(postBizData),
            postSrc: 1, // 1 twitter
            postType: 3, //3 Tool box
        },
    };

    submitIng.value = true;

    postPublish(data).then((res) => {
        submitIng.value = false;
        if (res.code == 0) {
            let publishRes = res.data;
            emits("publishFinish", { publishRes });
        } else {
        }
    }).catch((err) => {
        console.log(err);
    });
}

const setHistoryData = async (params) => {
    const maxLength = 9;
    let { list = [] } = await getChromeStorage('toolBoxAppHistoryData') || {};
    if (list.length) {
        let hasSite = list.find(item => item.defaultUrl == params.defaultUrl);
        if (hasSite) {
            return;
        }
        list.unshift(params);
        if (list.length > maxLength) {
            list.length = maxLength;
        }
        setChromeStorage({
            toolBoxAppHistoryData: JSON.stringify({
                list: list
            })
        })
    } else {
        setChromeStorage({
            toolBoxAppHistoryData: JSON.stringify({
                list: [params]
            })
        })
    }
};

onMounted(() => {
    calcPreviewCanvasParams();
    getUserInfo((res) => {
        if (res) {
            getUserName(res.nickName);
        }
        clearInterval(timer.value);
        // timer.value = setInterval(() => {
        // installStatus.value = !installStatus.value;
        // }, 3000)
    });
    window.addEventListener('resize', function () {
        calcPreviewCanvasParams();
    })
})

onUnmounted(() => {
    clearInterval(timer.value);
})

</script>

<style lang="scss" scoped>
.editor-preview-wrapper {
    width: 100%;
    height: 100%;

    .top {
        width: 100%;
        height: calc(100% - 80px);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow-y: auto;
        padding: 20px 0;
        box-sizing: border-box;

        .card-container {
            height: 100%;
            margin-right: 50px;

            .content-after,
            .content-before {
                position: relative;
            }

            .head {
                position: absolute;
                z-index: 1100;
                top: 20px;
                left: 17px;
                display: flex;

                .avatar {
                    width: 47px;
                    height: 47px;
                    border-radius: 50%;
                    object-fit: cover;
                    margin-right: 13px;
                }

                .article-wrapper {
                    display: flex;

                    .nickname {
                        font-weight: 500;
                    }

                    .nickname,
                    .name {
                        font-size: 15px;
                    }

                    .name {
                        color: #566370;
                        margin-left: 7px;
                    }
                }
            }

            .content-after {
                background: url('@/assets/img/img-tool-box-preview-after.png');
                width: 387px;
                height: 100%;
                background-size: contain;
                background-repeat: no-repeat;
                border: 1px solid #D1D9DD;
                border-radius: 13px;
                box-sizing: border-box;

                .after-cover-wrapper {
                    position: absolute;
                    z-index: 100;
                    top: 108px;
                    left: 78px;
                    width: 425px;
                    height: 458px;
                    border-radius: 10px;
                    // border: 1px solid #D1D9DD;
                }

            }

            .content-before {
                background: url('@/assets/img/img-tool-box-preview-before.png');
                background-size: contain;
                background-repeat: no-repeat;
                height: 100%;
                border: 1px solid #D1D9DD;
                border-radius: 13px;
                box-sizing: border-box;

                .card-wrapper {
                    width: 505px;
                    height: 338px;
                    border: 1px solid #D1D9DD;
                    background: #ffffff;
                    box-sizing: border-box;
                    overflow: hidden;
                    position: relative;
                    box-sizing: border-box;
                    border-radius: 16px;
                    left: 73px;
                    top: 90px;

                    .iframe {
                        height: calc(100% - 73px);
                        width: 100%;
                        border: none;
                        pointer-events: none;
                        cursor: default;
                    }

                    .cover {
                        height: calc(100% - 73px);
                        width: 100%;
                        object-fit: contain;
                    }

                    .bottom-bar {
                        width: 100%;
                        height: 73px;
                        padding: 10px 10px 0 13px;
                        border-top: 1px solid rgba(0, 0, 0, 0.3);

                        .site-url {
                            color: #566370;
                            font-size: 14px;
                            line-height: 20px;
                        }

                        .desc {
                            font-weight: 500;
                            font-size: 15px;
                            line-height: 21px;
                            font-weight: 500;
                        }
                    }
                }
            }
        }

        .font {
            width: 300px;
            font-weight: 600;
            font-size: 20px;

            span {
                color: #1D9BF0;
            }
        }
    }

    .bottom {
        width: 100%;
        height: 80px;
        box-shadow: 0px -1px 0px #ECECEC;
        box-sizing: border-box;
        border-bottom-left-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .btn {
            width: 200px;
            height: 50px;
            background: #1D9BF0;
            border-radius: 10000px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 18px;
            color: #fff;
            margin-right: 30px;
            cursor: pointer;
        }
    }

}
</style>
