import AdditionDraw from '../shared/service/additionDraw';
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 AdditionDraw | null,
    calculationData: null as {
        problems: Array<{
            type: 'addition' | 'subtraction';
            left: number;
            right: number;
            result: number;
        }>;
    } | null,

    data: {
        pageTitle: '加减法计算',
        subTitle: '通过图形化方式学习加减法运算',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
        currentMode: 'addition-5', // 'addition-5', 'addition-10', 'subtraction-10', 'addition-subtraction-10'
        currentModeName: '5以内加法',
        typeActions: [
            { name: '5以内加法', value: 'addition-5' },
            { name: '10以内加法', value: 'addition-10' },
            { name: '10以内减法', value: 'subtraction-10' },
            { name: '10以内加减法', value: 'addition-subtraction-10' },
        ],
        imageType: 'twelve-animals', // 图片类型：twelve-animals 或 fruits
    } as CanvasDataState & {
        currentMode: string;
        currentModeName: string;
        typeActions: Array<{ name: string; value: string }>;
        imageType: string;
    },

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'addition-5';
        this.initPageInfo(functionId, '加减法计算');

        // 根据 functionId 设置默认类型
        if (functionId === 'addition-5') {
            this.setData({
                currentMode: 'addition-5',
                currentModeName: '5以内加法',
            });
        } else if (functionId === 'addition-10') {
            this.setData({
                currentMode: 'addition-10',
                currentModeName: '10以内加法',
            });
        } else if (functionId === 'subtraction-10') {
            this.setData({
                currentMode: 'subtraction-10',
                currentModeName: '10以内减法',
            });
        } else if (functionId === 'addition-subtraction-10') {
            this.setData({
                currentMode: 'addition-subtraction-10',
                currentModeName: '10以内加减法',
            });
        }
    },

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

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

        try {
            // 更新 Header 的 Title
            if (this.drawService) {
                this.drawService.options.title = this.data.currentModeName;
            }

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

    /**
     * 随机生成
     */
    onRandom() {
        const problems: Array<{
            type: 'addition' | 'subtraction';
            left: number;
            right: number;
            result: number;
        }> = [];

        const type = this.data.currentMode;

        // 生成5道题目
        for (let i = 0; i < 5; i++) {
            if (type === 'addition-5') {
                // 5以内加法：和 ≤ 5
                // left >= 1, right >= 1, left + right <= 5
                const maxSum = 5;
                const left = Math.floor(Math.random() * (maxSum - 1)) + 1; // 1 到 4
                const maxRight = maxSum - left; // 确保 left + right <= 5
                const right = Math.floor(Math.random() * maxRight) + 1; // 1 到 maxRight
                const result = left + right;
                problems.push({
                    type: 'addition',
                    left,
                    right,
                    result,
                });
            } else if (type === 'addition-10') {
                // 10以内加法：和 ≤ 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;
                problems.push({
                    type: 'addition',
                    left,
                    right,
                    result,
                });
            } else if (type === 'subtraction-10') {
                // 10以内减法：被减数 ≤ 10
                // left <= 10, left - right = result, result >= 1
                const maxLeft = 10;
                const left = Math.floor(Math.random() * maxLeft) + 1; // 1 到 10
                const maxRight = left - 1; // 确保 result >= 1
                const right = Math.floor(Math.random() * maxRight) + 1; // 1 到 maxRight
                const result = left - right;
                problems.push({
                    type: 'subtraction',
                    left,
                    right,
                    result,
                });
            } else if (type === 'addition-subtraction-10') {
                // 加减法混合
                if (Math.random() < 0.5) {
                    // 加法：和 ≤ 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;
                    problems.push({
                        type: 'addition',
                        left,
                        right,
                        result,
                    });
                } else {
                    // 减法：被减数 ≤ 10
                    const maxLeft = 10;
                    const left = Math.floor(Math.random() * maxLeft) + 1; // 1 到 10
                    const maxRight = left - 1; // 确保 result >= 1
                    const right = Math.floor(Math.random() * maxRight) + 1; // 1 到 maxRight
                    const result = left - right;
                    problems.push({
                        type: 'subtraction',
                        left,
                        right,
                        result,
                    });
                }
            }
        }

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

    /** 选择类型 */
    onSelectType(event: any) {
        const { name, value } = event.detail;
        this.setData({
            currentMode: value,
            currentModeName: name,
        });
        // 重新生成数据
        this.onRandom();
    },
});
