<template>
    <view class="lottery-wheel-container relative">
        <view class="canvas-wrap relative" :style="{ width: size + 'px', height: size + 'px' }">
            <canvas canvas-id="canvasWheel" id="canvasWheel" :style="{ width: size + 'px', height: size + 'px' }"></canvas>
            <view class="click-area" @click="emit('spin-start')"></view>
        </view>
        <!--<button class="spin-button" @click="startSpin" :disabled="isSpinning">
            {{ isSpinning ? 'Spinning...' : 'Spin' }}
        </button>-->
    </view>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import config from '@/config/global.config';

const props = defineProps({
    prizes: {
        type: Array,
        required: true,
    },
    size: {
        type: Number,
        default: 300,
    },
    targetIndex: {
        type: Number,
        default: 0,
    },
    duration: {
        type: Number,
        default: 4000,
    },
    canSpin: {
        type: Boolean,
        default: false
    },
    spinCount: {
        type: Number,
        default: 0
    }
});
const emit = defineEmits(['spin-end', 'spin-start']);
const isSpinning = ref(false);

async function drawWheel(rotation = 0) {
    const context = uni.createCanvasContext('canvasWheel');
    const center = props.size / 2;
    const radius = center - 10;
    const sliceAngle = (2 * Math.PI) / props.prizes.length;
    context.clearRect(0, 0, props.size, props.size);
    context.save();
    context.translate(center, center);
    context.rotate(rotation);
    context.translate(-center, -center);
    context.drawImage(config.appImagePrefix() + '/spins/wheel_bg.png', 0, 0, props.size, props.size);
    // context.translate(center, center);
    // context.rotate(rotation);
    // context.translate(-center, -center);
    for (let index = 0, len = props.prizes.length; index < len; index++) {
        const prize = props.prizes[index];
        context.save();
        context.translate(center, center);
        // Rotate to the middle of the slice
        context.rotate(index * sliceAngle);
        // Rotate 90 degrees to make text perpendicular
        context.rotate(Math.PI / 2);

        // Text settings
        context.setTextAlign('center');
        context.setTextBaseline('bottom');
        context.setFillStyle('#fff');
        context.font = 'bold 14px sans-serif';

        // Split text into lines (for Chinese characters, split every character)
        const maxCharsPerLine = 16;
        let str = '₹' + prize.toString();
        if (prize == 0) {
            str = '₹0-10'
        }
        const chars = str.split('');
        let lines = [];
        let currentLine = '';

        // Character wrap logic
        chars.forEach((char, i) => {
            currentLine += char;
            if ((i + 1) % maxCharsPerLine === 0 || i === chars.length - 1) {
                lines.push(currentLine);
                currentLine = '';
            }
        });
        if (currentLine) {
            lines.push(currentLine);
        }

        // Calculate total height of text
        const lineHeight = 16;
        const totalHeight = lines.length * lineHeight;
        const startY = -radius * 0.75; // Start position from the center

        // Draw each line of text
        lines.forEach((line, lineIndex) => {
            const y = startY + lineIndex * lineHeight;
            context.fillText(line, 0, y);
        });
        // context.save()
        // context.translate(center, center)
        // context.restore();
        // context.rotate(index * sliceAngle + sliceAngle / 2);
        const currentImg = index % 2 === 0 ? '/spins/image_jinbi.png' : '/spins/image_zhibi.png'
        const img2 = await loadImg(config.appImagePrefix() + currentImg)
        // const imgX = Math.cos(index * sliceAngle) * center / 2
        // const imgY = Math.sin(index * sliceAngle) * center / 2
        // console.log('center', center);

        // console.log('imgX', imgX, 'imgY', imgY);
        // console.log('taggle', index * sliceAngle);

        // Rotate to the middle of the slice
        // context.rotate(index * sliceAngle - sliceAngle/2);
        // Rotate 90 degrees to make text perpendicular
        const _radius = center * 0.55;
        // context.rotate(Math.PI / 2);
        context.drawImage(
            img2.path,
            -img2.width / 6,  // Center horizontally 
            -_radius - img2.height / 6,  // Position at sector center, 
            img2.width / 3,
            img2.height / 3);
        // Rotate to the middle of the slice
        // context.rotate(index * sliceAngle);
        context.restore();
    }
    context.restore();
    context.translate(center, center)
    context.rotate(0)
    // Draw fixed pointer in center (after rotation restore)
    const img = await loadImg(config.appImagePrefix() + '/spins/btn_spin02.png')
    context.drawImage(img.path, -img.width / 4, -img.height / 4, img.width / 2, img.height / 2);
    context.save();

    // Draw spin count
    context.restore();
    // context.translate(center, center);
    context.rotate(0);
    context.setTextAlign('center');
    context.setTextBaseline('middle');
    context.setFillStyle('#fff');
    context.font = 'italic bold 16px sans-serif';
    context.fillText(`X${props.spinCount}`, 0, 12);
    context.draw();
}


const calculateTargetRotation = (targetIndex) => {
    // Calculate base rotation needed to align the target index
    const sliceAngle = (2 * Math.PI) / props.prizes.length;

    // Calculate the angle needed to rotate the target index to 12 o'clock
    // We add Math.PI/2 to start from 12 o'clock (instead of 3 o'clock)
    // We subtract the target index angle to rotate counterclockwise
    // We add sliceAngle/2 to center the slice
    const baseAngle = Math.PI - ((targetIndex - 2) * sliceAngle);

    // Add extra rotations (5-8 full spins)
    const extraRotations = Math.PI * 2 * (5 + Math.floor(Math.random() * 3));

    // Return total rotation (extra rotations + base angle)
    return extraRotations + baseAngle;
};

const startSpin = async () => {
    // if(!props.canSpin) return
    if (isSpinning.value) return;

    isSpinning.value = true;
    // If targetIndex is provided and valid, use it; otherwise random
    let finalIndex;
    if (props.targetIndex >= 0 && props.targetIndex < props.prizes.length) {
        finalIndex = props.targetIndex;
    } else {
        finalIndex = Math.floor(Math.random() * props.prizes.length);
    }
    console.log(finalIndex);

    const targetRotation = calculateTargetRotation(finalIndex);
    const startTime = Date.now();

    const animate = () => {
        const currentTime = Date.now();
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / props.duration, 1);

        const easedProgress = easeOut(progress);
        const rotation = targetRotation * easedProgress;

        drawWheel(rotation);

        if (progress < 1) {
            setTimeout(animate, 16.6);
        } else {
            isSpinning.value = false;
            console.log('Final Index:', finalIndex, 'Prize:', props.prizes[finalIndex]);
            emit('spin-end', props.prizes[finalIndex]);
        }
    };

    animate();
};

const easeOut = (t) => {
    return 1 - Math.pow(1 - t, 3);
};
async function loadImg(src) {
    return new Promise((resolve, reject) => {
        uni.getImageInfo({
            src,
            success: (res) => {
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            },
        });
    })
}
const reDraw = () => {
    drawWheel()
}
onMounted(async () => {
    drawWheel()
})
defineExpose({
    startSpin,
    reDraw
})
</script>
<style lang="scss">
.lottery-wheel-container {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 30rpx;
}

.canvasWheel {
    margin-top: 20rpx
}
.click-area{
    width: 180rpx;
    height: 180rpx;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000;
}
</style>