<template>
    <uni-popup ref="popup" type="center" borderRadius="12px 12px 0 0" @change="changePopup">
        <view class="popup-inner">
            <view class="title">请扫码上传附件</view>
            <view class="img-box">
                <!-- 加载状态 -->
                <view v-if="loading" class="loading-container">
                    <uni-load-more status="loading" :icon-size="24" :content-text="loadingText" />
                </view>
                <canvas canvas-id="qrcode" id="qrcode" />
            </view>
            <view class="tips" v-if="!loading">
                已上传
                <span class="num">{{ fileCount }}</span>
                个文件
            </view>
            <view class="tips" v-if="!loading">请使用手机扫描二维码上传文件</view>
            <view class="close-btn" @click="close"></view>
        </view>
    </uni-popup>
</template>

<script setup>
import { ref, inject, onUnmounted, watch, computed } from 'vue';
import uQRCode from '@/static/js/qrcode';
import config from '@/config';
import { onShow, onHide } from '@dcloudio/uni-app';
import { UUID } from '../../../lib/uuid-min';
const props = defineProps({
    sessionId: {
        type: [Number, String],
        default: '',
    },
});

const emit = defineEmits(['onSend', 'onClose']);
const { $api } = inject('globalFunction');

const popup = ref(null);
const loading = ref(false);
const pollingTimer = ref(null);
const isPolling = ref(false);
const isVisible = ref(false);
const uuid = ref(null);
const fileCount = ref(0);

// 计算加载文本
const loadingText = computed(() => ({
    contentdown: '二维码生成中',
    contentrefresh: '二维码生成中',
}));

onUnmounted(() => {
    stopPolling();
    clearResources();
});

function open() {
    uuid.value = UUID.generate();
    resetState();
    isVisible.value = true;
    popup.value.open();
    initQrCode();
}

function close() {
    isVisible.value = false;
    stopPolling();
    popup.value.close();
    resetState();
}

function changePopup(e) {
    if (e.show) {
    } else {
        stopPolling();
        emit('onClose');
    }
}

// 重置所有状态
function resetState() {
    loading.value = false;
    stopPolling();
}

async function initQrCode() {
    try {
        loading.value = true;
        // 清除之前的二维码
        clearCanvas();
        await makeQrcode();
        // 二维码生成成功后开始轮询
        if (isVisible.value) {
            startPolling();
        }
    } catch (error) {
        console.error('生成二维码失败:', error);
        uni.showToast({
            title: '生成二维码失败，请重试',
            icon: 'none',
        });
        close();
    } finally {
        loading.value = false;
    }
}

function makeQrcode() {
    const protocol = window.location.protocol;
    const host = window.location.host;
    const isLocal = host.includes('localhost') || host.includes('127.0.0.1');
    const pathPrefix = isLocal ? '' : '/rgpp-api/all-in-one';
    const htmlPath = `${protocol}//${host}${pathPrefix}/static/upload.html?sessionId=${uuid.value}&uploadApi=${config.baseUrl}/app/kiosk/upload`;

    // const htmlPath = `${window.location.host}/static/upload.html?sessionId=${uuid.value}&uploadApi=${
    //   config.baseUrl + '/app/kiosk/upload'
    // }`;
    //   const htmlPath = `${window.location.host}/static/upload.html?sessionId=${props.sessionId}&uploadApi=${
    //     config.baseUrl + '/app/kiosk/upload'
    //   }`;
    console.log(htmlPath);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            uQRCode.make({
                canvasId: 'qrcode',
                text: htmlPath,
                size: uni.upx2px(300),
                margin: 0,
                backgroundColor: '#ffffff',
                foregroundColor: '#1677ff',
                fileType: 'png',
                correctLevel: uQRCode.defaults.correctLevel,
            });
            resolve();
        }, 100);
    });
}

// 清除画布
function clearCanvas() {
    const ctx = uni.createCanvasContext('qrcode');
    ctx.clearRect(0, 0, uni.upx2px(300), uni.upx2px(300));
    ctx.draw();
}

function startPolling() {
    if (isPolling.value) return;

    isPolling.value = true;
    console.log('开始轮询');

    // 轮询检查上传状态
    const poll = async () => {
        if (!isPolling.value || !isVisible.value) return;
        const { data } = await $api.createRequest('/app/kiosk/list', { sessionId: uuid.value });
        // const { data } = await $api.createRequest('/app/kiosk/list',{sessionId:props.sessionId});
        if (data && data.length) {
            // 上传完成，触发事件
            fileCount.value = data.length;
            emit('onSend', data);
        }
        if (isPolling.value && isVisible.value) {
            pollingTimer.value = setTimeout(poll, 2000); // 每2秒轮询一次
        }
    };

    poll();
}

function stopPolling() {
    isPolling.value = false;
    if (pollingTimer.value) {
        clearTimeout(pollingTimer.value);
        pollingTimer.value = null;
    }
    console.log('停止轮询');
}

function clearResources() {
    stopPolling();
    clearCanvas();
}

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.popup-inner {
    padding: 40rpx 30rpx;
    padding-bottom: 50rpx;
    width: 440rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    border-radius: 20rpx;
    background: #fafafa;
}

.title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 30rpx;
    font-weight: bold;
    text-align: center;
}

.img-box {
    margin: 0 auto 30rpx;
    width: 300rpx;
    height: 300rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    overflow: hidden;
    position: relative;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
    padding: 20rpx;

    canvas {
        width: 100%;
        height: 100%;
        transition: opacity 0.3s ease;
    }
}

.loading-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
}

.tips {
    font-size: 24rpx;
    color: #666;
    text-align: center;
    line-height: 1.6;
    padding: 0 20rpx;
    .num {
        color: #4191fe;
        font-size: 28rpx;
    }
}

.close-btn {
    position: absolute;
    right: 20rpx;
    top: 20rpx;
    width: 56rpx;
    height: 56rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.2s;

    &:active {
        background-color: rgba(0, 0, 0, 0.1);
    }

    &::before {
        position: absolute;
        left: 50%;
        top: 50%;
        content: '';
        width: 4rpx;
        height: 28rpx;
        border-radius: 2rpx;
        background: #5a5a68;
        transform: translate(50%, -50%) rotate(-45deg);
    }

    &::after {
        position: absolute;
        left: 50%;
        top: 50%;
        content: '';
        width: 4rpx;
        height: 28rpx;
        border-radius: 2rpx;
        background: #5a5a68;
        transform: translate(50%, -50%) rotate(45deg);
    }
}
</style>
