import NumberFindDraw from '../shared/service/numberFindDraw';
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 NumberFindDraw | null,

    data: {
        pageTitle: '看数字，涂一涂', // 默认标题
        selectedNumber: 0, // 选中的数字
        functionId: '', // 功能ID，用于判断标题
        numberList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], // 数字列表
        hasContent: false,
        showShareDialog: false,
    } as CanvasDataState & {
        selectedNumber: number;
        numberList: number[];
    },

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'number-find';
        this.setData({
            functionId,
        });
        this.initPageInfo(functionId, '看数字，涂一涂');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new NumberFindDraw(canvas, ctx, options);
            },
            drawServiceOptions: {
                subTitle: '找一找下面相同的数字，涂上颜色',
                functionId: this.data.functionId,
            },
            onCanvasReady: () => {
                // 如果还没有选中数字，随机选择一个
                if (this.data.selectedNumber === 0) {
                    const randomNumber = Math.floor(Math.random() * 10) + 1;
                    this.setData({
                        selectedNumber: randomNumber,
                    });
                }

                // 绘制初始内容
                this.drawCanvas();
            },
        });
    },

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

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

    /**
     * 选择数字
     */
    onSelectNumber(e: WechatMiniprogram.TouchEvent) {
        const number = parseInt(e.currentTarget.dataset.number);
        this.setData({
            selectedNumber: number,
        });
        this.drawCanvas();
    },

    /**
     * 随机选择数字
     */
    onRandom() {
        const randomNumber = Math.floor(Math.random() * 10) + 1;
        this.setData({
            selectedNumber: randomNumber,
        });
        this.drawCanvas();
    },
});
