import ColorPatternDraw from '../shared/service/colorPatternDraw';
import { createFocusPage } from '../shared/common/focusPageMixin';
import { ColorPatternData } from '../shared/service/colorPatternDraw';
import { SHAPE_SYMBOL_SHAPES } from '../shared/shapes/shapeSymbolShapes';
import { getNumberColors } from '../../constants/colors';

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

    data: {
        pageTitle: '颜色找规律',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    },

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'color-pattern';
        this.setData({
            functionId,
        });
        this.initPageInfo(functionId, '颜色找规律');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new ColorPatternDraw(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种图形中随机选择8个不同的图形（每组使用不同的图形）
        const allShapes = [...SHAPE_SYMBOL_SHAPES];
        const shuffledShapes = allShapes.sort(() => Math.random() - 0.5);
        const selectedShapes = shuffledShapes.slice(0, 8); // 选择8个不同的图形

        // 获取所有可用颜色
        const allColors = getNumberColors();

        // 生成8组数据
        const groups: Array<{
            shapeId: string;
            colors: Array<string | null>; // 前4个有颜色，后6个为null
        }> = [];

        for (let groupIndex = 0; groupIndex < 8; groupIndex++) {
            // 每一组使用不同的图形
            const selectedShape = selectedShapes[groupIndex];

            // 每一行独立选择2种或3种颜色
            const colorCount = 2;
            const shuffledColors = [...allColors].sort(
                () => Math.random() - 0.5,
            );
            const selectedColors = shuffledColors.slice(0, colorCount);

            // 生成前4个图形的颜色规律
            // 从选中的颜色中随机选择，形成规律（可以重复）
            // 但至少保证有两种不同的颜色，不能4个都相同
            const patternColors: string[] = [];
            for (let i = 0; i < 4; i++) {
                // 随机从选中的颜色中选择一种
                const randomColor =
                    selectedColors[
                        Math.floor(Math.random() * selectedColors.length)
                    ];
                patternColors.push(randomColor);
            }

            // 检查是否只有一种颜色，如果是则确保至少有两种颜色
            const uniqueColors = new Set(patternColors);
            if (uniqueColors.size === 1) {
                // 如果4个都是同一种颜色，随机选择一个位置替换为另一种颜色
                const currentColor = patternColors[0];
                const otherColors = selectedColors.filter(
                    (c) => c !== currentColor,
                );
                if (otherColors.length > 0) {
                    const randomIndex = Math.floor(
                        Math.random() * patternColors.length,
                    );
                    const randomOtherColor =
                        otherColors[
                            Math.floor(Math.random() * otherColors.length)
                        ];
                    patternColors[randomIndex] = randomOtherColor;
                }
            }

            // 后6个图形留空（null）
            const emptyColors: Array<string | null> = new Array(6).fill(null);

            groups.push({
                shapeId: selectedShape.id,
                colors: [...patternColors, ...emptyColors],
            });
        }

        this.gridData = {
            groups,
        };

        this.drawCanvas();
    },
});
