<script setup>
import { watch, ref, onUnmounted } from "vue";
import XModal from "./XModal.vue";
import Api from "../api/index.js";
import { useUserStore } from "../pinia/UserStore/index.js";

const UserStore = useUserStore();
const show = defineModel('show');
const qrCode = ref(null);
let old_openid = "";
let max_timer = 50;
let timer = null;

const cancel = () => {
    show.value = false;
    if (timer) clearInterval(timer);
}

const check = async () => {
    max_timer--;
    if (max_timer <= 0 && timer) clearInterval(timer);
    await UserStore.getUserInfo();
    if (old_openid !== UserStore.userInfo.openid) {
        cancel();
    }
}

watch(
    () => show.value,
    (val) => {
        if (val) {
            Api.system.createQrcode().then(async ({ data }) => {
                await UserStore.getUserInfo();
                old_openid = UserStore.userInfo.openid;
                qrCode.value = data.url;
                timer = setInterval(check, 5000);
            });
        }
    }
)

onUnmounted(() => {
    if (timer) clearInterval(timer);
});
</script>

<template>
    <view @click="show = true">
        <slot></slot>
    </view>

    <x-modal v-model:show="show" @cancel="cancel">
        <view class="px-[30rpx] py-[40rpx] relative">
            <image @click="show = false" class="!w-[52rpx] !h-[52rpx] absolute top-[-110rpx] right-[calc(-100%-10rpx)]"
                src="/static/icons/close.png"></image>

            <view class="title">绑定</view>
            <view class="!mt-[24rpx] w-[320rpx] !mx-auto aspect-square">
                <image v-if="qrCode" class="!size-full" :src="qrCode"></image>
                <tui-loading v-else type="row"></tui-loading>
            </view>
            <view class="desc !mt-[24rpx]">截图保存后，使用微信扫码并关注</view>
        </view>
    </x-modal>
</template>

<style lang="scss" scoped>
.title {
    color: rgb(29, 33, 41);
    font-size: 34rpx;
    font-weight: 500;
    line-height: 48rpx;
    letter-spacing: 0;
    text-align: center;
}

.desc {
    color: rgb(78, 89, 105);
    font-size: 28rpx;
    font-weight: 500;
    letter-spacing: 0;
    text-align: center;
}
</style>
