import ColorShapeMatchDraw from '../shared/service/colorShapeMatchDraw';
import { createFocusPage } from '../shared/common/focusPageMixin';
import { ColorShapeMatchData } from '../shared/service/colorShapeMatchDraw';
import { SHAPE_SYMBOL_SHAPES } from '../shared/shapes/shapeSymbolShapes';
import { getRandomUniqueNumberColors } from '../../constants/colors';

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

    data: {
        pageTitle: '根据颜色画图形',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    },

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'color-shape-match';
        this.setData({
            functionId,
        });
        this.initPageInfo(functionId, '根据颜色画图形');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new ColorShapeMatchDraw(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() {
        // 从所有图形中随机选择4个
        const shapes = [...SHAPE_SYMBOL_SHAPES].filter(
            (shape) => shape.id !== 'cross',
        );
        const selectedShapes = shapes
            .sort(() => Math.random() - 0.5)
            .slice(0, 4);

        // 获取4个不重复的颜色
        const colors = getRandomUniqueNumberColors(4);

        // 创建阅览区域的数据，过滤掉 cross
        const legendItems = selectedShapes.map((shape, index) => ({
            shapeId: shape.id,
            color: colors[index],
        }));

        // 创建练习区域的数据（5行5列，共25个格子）
        // 随机填充这4种颜色，确保每种颜色至少出现一次
        const practiceGrid: Array<Array<string | null>> = [];
        const allColors: (string | null)[] = new Array(25).fill(null);

        // 先随机选择4个位置，每个位置分配一种颜色（确保每种颜色至少出现一次）
        const positions: number[] = [];
        for (let i = 0; i < 25; i++) {
            positions.push(i);
        }
        const shuffledPositions = [...positions].sort(
            () => Math.random() - 0.5,
        );

        // 前4个位置分配4种颜色
        for (let i = 0; i < 4; i++) {
            allColors[shuffledPositions[i]] = colors[i];
        }

        // 剩余21个位置随机分配这4种颜色
        for (let i = 4; i < 25; i++) {
            const randomColor =
                colors[Math.floor(Math.random() * colors.length)];
            allColors[shuffledPositions[i]] = randomColor;
        }

        // 转换为5x5的二维数组
        for (let row = 0; row < 5; row++) {
            const practiceRow: Array<string | null> = [];
            for (let col = 0; col < 5; col++) {
                const index = row * 5 + col;
                practiceRow.push(allColors[index]);
            }
            practiceGrid.push(practiceRow);
        }

        this.gridData = {
            legendItems,
            practiceGrid,
        };

        this.drawCanvas();
    },
});
