import OneDigitAdditionDraw from '../shared/service/oneDigitAdditionDraw';
import {
    createMathPage,
    CanvasDataState,
} from '../shared/common/mathPageMixin';

createMathPage({
    canvas: null as Canvas | null,
    ctx: null as RenderingContext | null,
    boxHeight: 0,
    boxWidth: 0,
    drawService: null as OneDigitAdditionDraw | null,
    oneDigitAdditionData: null as {
        problems: Array<{
            left: number;
            right: number;
            result: number;
        }>;
    } | null,

    data: {
        pageTitle: '一位数加法',
        subTitle: '通过圆点学习一位数加法运算',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    } as CanvasDataState,

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'one-digit-addition';
        this.initPageInfo(functionId, '一位数加法');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new OneDigitAdditionDraw(canvas, ctx, options);
            },
            drawServiceOptions: {
                subTitle: this.data.subTitle,
            },
            onCanvasReady: () => {
                // 初始随机生成
                this.onRandom();
            },
        });
    },

    /**
     * 绘制Canvas内容
     */
    async drawCanvas() {
        if (!this.ctx || !this.drawService || !this.oneDigitAdditionData) {
            return;
        }

        try {
            await this.drawService.draw(this.oneDigitAdditionData);
            this.setData({ hasContent: true });
        } catch (error) {
            console.error('绘制失败:', error);
            this.setData({ hasContent: false });
        }
    },

    /**
     * 随机生成
     */
    onRandom() {
        const problems: Array<{
            left: number;
            right: number;
            result: number;
        }> = [];
        const usedProblems = new Set<string>(); // 用于记录已生成的题目，避免重复

        // 生成6道不重复的题目（6行1列）
        let attempts = 0;
        const maxAttempts = 1000; // 最大尝试次数，避免无限循环

        while (problems.length < 6 && attempts < maxAttempts) {
            attempts++;
            // 两个加数的和 <= 10
            // left >= 1, right >= 1, left + right <= 10
            const maxSum = 10;
            const left = Math.floor(Math.random() * (maxSum - 1)) + 1; // 1 到 9
            const maxRight = maxSum - left; // 确保 left + right <= 10
            const right = Math.floor(Math.random() * maxRight) + 1; // 1 到 maxRight
            const result = left + right;

            // 使用 "left,right" 作为唯一标识，避免重复
            const problemKey = `${left},${right}`;
            if (usedProblems.has(problemKey)) {
                continue;
            }

            usedProblems.add(problemKey);
            problems.push({
                left,
                right,
                result,
            });
        }

        if (problems.length < 6) {
            console.warn(
                `只生成了 ${problems.length} 道题目，可能符合条件的题目组合不足`,
            );
        }

        this.oneDigitAdditionData = { problems };
        this.drawCanvas();
    },
});
