import FlatTenDraw from '../shared/service/flatTenDraw';
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 FlatTenDraw | null,
    flatTenData: null as {
        problems: Array<{
            minuend: number; // 被减数
            subtrahend: number; // 减数
            result: number;
        }>;
    } | null,

    data: {
        pageTitle: '平十法练习',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    } as CanvasDataState,

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'flat-ten';
        this.initPageInfo(functionId, '平十法练习');
    },

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

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

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

    /**
     * 随机生成
     */
    onRandom() {
        // 先列出所有符合条件的题目组合
        const allValidProblems: Array<{
            minuend: number;
            subtrahend: number;
            result: number;
        }> = [];

        // 遍历所有可能的被减数（11-19）和减数（1-10）组合
        for (let minuend = 11; minuend < 20; minuend++) {
            const minuendOnes = minuend % 10; // 被减数的个位数

            for (let subtrahend = 1; subtrahend <= 10; subtrahend++) {
                // 检查条件：
                // 1. 减数 > 被减数的个位数（平十法的关键要求）
                // 2. 被减数 > 减数（确保结果大于0）
                if (subtrahend > minuendOnes && minuend > subtrahend) {
                    allValidProblems.push({
                        minuend,
                        subtrahend,
                        result: minuend - subtrahend,
                    });
                }
            }
        }

        // 从所有符合条件的组合中随机选择9个，确保分布均匀
        const problems: Array<{
            minuend: number;
            subtrahend: number;
            result: number;
        }> = [];

        // 如果符合条件的组合少于9个，使用所有组合
        const targetCount = Math.min(9, allValidProblems.length);

        // 使用 Fisher-Yates 洗牌算法随机选择
        const shuffled = [...allValidProblems];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }

        // 取前9个
        for (let i = 0; i < targetCount; i++) {
            problems.push(shuffled[i]);
        }

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