<template>
    <BasePage>
        <!-- v-if="data.Icon" -->
        <div class="ewm_bg" style="font-family: 'PingFang SC'">
            <div class="d1">
                <div class="w100">
                    <img id="invite_bg" :src="bgSrc" crossorigin="anonymous" />
                    <!-- <img id="invite_bg" src="/img/invite_bg.jpg" crossorigin="anonymous"> -->
                </div>
                <img class="icon" :src="$file(data.Avatar) + '?t=1'" crossorigin="anonymous">
                <div class="name">
                    <b>{{ $substring(data.NickName, 0, 8) }}</b>
                </div>
                <p class="tips">邀请你使用泰古润平台<br>积分带卡消费，享受更多实惠</p>
                <div class="ewm_test box box-tb box-align-center">
                    <vue-qr v-if="!loading" :text="link" backgroundColor="rgb(255,255,255)"
                        colorLight="rgb(255,255,255)"></vue-qr>
                    <!-- <span>扫码立即注册</span> -->
                </div>

            </div>
        </div>
        <div id="sc_ewm" class="b_l_w bx" style="font-family: 'PingFang SC'"></div>

    </BasePage>
</template>

<script>
import { toDataURL } from '@/utils/html2image';

export default {
    name: 'Invite',
    data() {
        return {
            loading: true,
            data: {
                Icon: '',
                Avatar: '',
                NickName: '',
            },
            link: '',
            userStore: null,
            bgSrc: '',
        };
    },
    mounted() {
        this.loading = false;
        this.preloadBackground().then(() => {
            this.init().then(() => {
                this.$nextTick(() => {
                    this.CreatePoster(".ewm_bg > div", "#sc_ewm");
                });
            });
        });
    },
    methods: {
        async preloadBackground() {
            const bgUrl = this.$file(this.$datadic.getContent('code_yqmbj'));
            const cacheKey = 'invite_bg_cache';
            const cached = localStorage.getItem(cacheKey);
            if (cached) {
                this.bgSrc = cached;
                return;
            }
            try {
                const response = await fetch(bgUrl, { mode: 'cors' });
                const blob = await response.blob();
                const reader = new FileReader();
                return new Promise((resolve) => {
                    reader.onloadend = () => {
                        localStorage.setItem(cacheKey, reader.result);
                        this.bgSrc = reader.result;
                        resolve();
                    };
                    reader.readAsDataURL(blob);
                });
            } catch (e) {
                console.error('Background preload failed:', e);
                this.bgSrc = bgUrl;
                resolve();
            }
        },
        async init() {
            try {
                // 获取用户信息
                const userInfo = await this.$get('/v1/client/DUsersClient');
                if (userInfo?.data) {
                    this.data.Avatar = userInfo.data.userimg || '';
                    this.data.NickName = userInfo.data.nickname || '';
                    this.data.Icon = userInfo.data.Icon || '';
                }
                // 生成包含邀请码的链接
                const inviteCode = userInfo?.data?.cellphone || '';
                this.link = `${location.origin}${location.pathname}#/Login?invite=${inviteCode}`;
            } catch (err) {
                console.error('获取用户信息失败:', err);
            }
        },
        async CreatePoster(divID, targetID) {
            var shareContent = document.querySelector(divID);

            try {
                // Wait for background and avatar images to load
                const promises = [];
                const bgImg = shareContent.querySelector('#invite_bg');
                if (bgImg && !bgImg.complete) {
                    promises.push(new Promise(resolve => {
                        bgImg.onload = resolve;
                        bgImg.onerror = resolve;
                    }));
                }
                const avatarImg = shareContent.querySelector('.icon');
                if (avatarImg && !avatarImg.complete) {
                    promises.push(new Promise(resolve => {
                        avatarImg.onload = resolve;
                        avatarImg.onerror = resolve;
                    }));
                }
                if (promises.length > 0) {
                    await Promise.all(promises);
                }
                // Extra delay for Safari/WeChat compatibility
                await new Promise(resolve => setTimeout(resolve, 300));

                var dataUrl = await toDataURL(shareContent, { format: 'png', pixelRatio: 2, useCORS: true });
                var newImg = document.createElement("img");
                newImg.src = dataUrl;
                newImg.width = shareContent.offsetWidth;
                newImg.height = shareContent.offsetHeight;
                document.querySelector(targetID).appendChild(newImg);
            } catch (err) {
                console.error('生成海报失败', err);
            }
        },
    },
};
</script>

<style lang="less">
.ewm_bg {
    opacity: 0;
    position: fixed;
    left: 0;
    top: 12.267vw;
    z-index: 0;
    height: 0px;
    overflow: hidden;

    .d1 {
        position: relative;

        .name {
            position: absolute;
            left: 34vw;
            bottom: 46vw;
            // line-height: 6vw;
            width: 100%;

            b {
                font-size: 3.47vw;
            }

        }

        .tips {
            font-size: 3.2vw;
            color: #3a0a05;
            position: absolute;
            left: 20.27vw;
            bottom: 34vw;
        }

        .icon {
            position: absolute;
            width: 10.67vw;
            height: 10.67vw;
            left: 20.27vw;
            bottom: 42vw;
            border-radius: 50%;
        }

        .ewm_test {
            position: absolute;
            left: 23.73vw;
            bottom: 57.47vw;
            white-space: nowrap;

            img {
                width: 52.53vw;
                height: 52.53vw;
            }
        }
    }
}
</style>