import PositionColoringDraw from '../shared/service/positionColoringDraw';
import { createFocusPage } from '../shared/common/focusPageMixin';
import { PositionColoringData } from '../shared/service/positionColoringDraw';

createFocusPage({
    canvas: null as Canvas | null,
    ctx: null as RenderingContext | null,
    boxHeight: 0,
    boxWidth: 0,
    drawService: null as PositionColoringDraw | null,
    gridData: null as PositionColoringData | null,

    data: {
        pageTitle: '方位涂涂乐',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    },

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'position-coloring';
        this.setData({
            functionId,
        });
        this.initPageInfo(functionId, '方位涂涂乐');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new PositionColoringDraw(canvas, ctx, options);
            },
            drawServiceOptions: {
                title: this.data.pageTitle,
                subTitle: '观察卡片位置，在对应的方格中涂上颜色',
                functionId: this.data.functionId,
            },
            onCanvasReady: () => {
                // 初始随机生成
                this.onRandom();
            },
        });
    },

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

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

    /**
     * 随机生成
     */
    onRandom() {
        // 生成9张不重复的图片索引（1-33）,33 是图片总数
        const allImageIndices = Array.from({ length: 33 }, (_, i) => i + 1);
        const shuffled = [...allImageIndices].sort(() => Math.random() - 0.5);
        const selectedImages = shuffled.slice(0, 9);

        // 创建3x3网格的图片位置映射
        const referenceGrid: number[] = [];
        for (let i = 0; i < 9; i++) {
            referenceGrid[i] = selectedImages[i];
        }

        // 创建任务组：9个任务，每个任务包含一个图片和对应的位置
        // 第一行需要标记位置（涂色），其他行不标记
        const tasks: Array<{
            imageIndex: number;
            position: { x: number; y: number };
        }> = [];

        // 打乱顺序选择图片用于任务
        const taskImageIndices = [...selectedImages].sort(
            () => Math.random() - 0.5,
        );

        for (let i = 0; i < 9; i++) {
            const imageIndex = taskImageIndices[i];
            // 找到这个图片在参考网格中的位置
            const gridIndex = referenceGrid.indexOf(imageIndex);
            const x = gridIndex % 3;
            const y = Math.floor(gridIndex / 3);
            tasks.push({
                imageIndex,
                position: { x, y },
            });
        }

        this.gridData = {
            referenceGrid,
            tasks,
        };

        this.drawCanvas();
    },
});
