<template>
    <div class="captcha-container">
        <canvas ref="canvasRef" @click="refreshCaptcha" width="120" height="39"></canvas>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';

const canvasRef = ref(null);
const captchaText = ref('');

// 生成随机数字（默认4位）
const generateRandomDigits = (length = 4) => {
    return Array.from({ length }, () => Math.floor(Math.random() * 10)).join('');
};

// 绘制验证码
const drawCaptcha = () => {
    const canvas = canvasRef.value;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 生成新验证码
    captchaText.value = generateRandomDigits();

    // 背景色
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制文字（随机位置、颜色、旋转）
    for (let i = 0; i < captchaText.value.length; i++) {
        ctx.font = 'bold 24px Arial';
        ctx.fillStyle = getRandomColor();
        ctx.save();
        ctx.translate(10 + i * 30, 28);
        ctx.rotate((Math.random() - 0.5) * 0.4);
        ctx.fillText(captchaText.value[i], 0, 0);
        ctx.restore();
    }

    // 绘制干扰线
    for (let i = 0; i < 15; i++) {
        ctx.strokeStyle = getRandomColor(300);
        ctx.beginPath();
        ctx.moveTo(
            Math.random() * canvas.width,
            Math.random() * canvas.height
        );
        ctx.lineTo(
            Math.random() * canvas.width,
            Math.random() * canvas.height
        );
        ctx.stroke();
    }
};

// 随机颜色
const getRandomColor = (min = 50) => {
    const r = min + Math.floor(Math.random() * (100 - min));
    const g = min + Math.floor(Math.random() * (100 - min));
    const b = min + Math.floor(Math.random() * (100 - min));
    return `rgb(${r}, ${g}, ${b})`;
};

// 点击刷新
const refreshCaptcha = () => {
    drawCaptcha();
};

// 初始化
onMounted(() => {
    drawCaptcha();
});

// 暴露验证码文本（供父组件校验）
defineExpose({
    captchaText,
});
</script>

<style scoped>
.captcha-container {
  display: inline-block;
  cursor: pointer;
}
canvas {
  border: 1px solid #ddd;
  border-radius: 4px;
}
.hint {
  font-size: 12px;
  color: #999;
  text-align: center;
}
</style>