import NumberSortDraw from '../shared/service/numberSortDraw';
import {
    createMathPage,
    CanvasDataState,
} from '../shared/common/mathPageMixin';
import { NumberSortData } from '../shared/service/numberSortDraw';
import { NUMBER_COLORS, getNumberColors } from '../../constants/colors';

createMathPage({
    canvas: null as Canvas | null,
    ctx: null as RenderingContext | null,
    boxHeight: 0,
    boxWidth: 0,
    drawService: null as NumberSortDraw | null,
    sortData: null as NumberSortData | null,

    data: {
        pageTitle: '数字排序',
        functionId: '',
        hasContent: false,
        showShareDialog: false,
    } as CanvasDataState,

    onLoad(options: { id?: string }) {
        const functionId = options.id || 'number-sort';
        this.setData({
            functionId,
        });
        this.initPageInfo(functionId, '数字排序');
    },

    onReady() {
        this.initCanvas({
            createDrawService: (
                canvas: Canvas,
                ctx: RenderingContext,
                options?: Record<string, any>,
            ) => {
                return new NumberSortDraw(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.sortData) {
            return;
        }

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

    /**
     * 随机生成
     */
    onRandom() {
        const groups: NumberSortData['groups'] = [];
        const availableColors = getNumberColors();

        // 生成6组题目
        for (let i = 0; i < 6; i++) {
            // 随机选择4个不同的数字（范围1-9）
            const availableNumbers = Array.from({ length: 9 }, (_, i) => i + 1);
            const selectedNumbers: number[] = [];

            // 随机选择4个数字
            for (let j = 0; j < 4; j++) {
                const randomIndex = Math.floor(
                    Math.random() * availableNumbers.length,
                );
                selectedNumbers.push(
                    availableNumbers.splice(randomIndex, 1)[0],
                );
            }

            // 打乱顺序
            const shuffledNumbers = [...selectedNumbers];
            for (let j = shuffledNumbers.length - 1; j > 0; j--) {
                const k = Math.floor(Math.random() * (j + 1));
                [shuffledNumbers[j], shuffledNumbers[k]] = [
                    shuffledNumbers[k],
                    shuffledNumbers[j],
                ];
            }

            // 为每个数字分配颜色和倾斜角度
            const numbersWithColors = shuffledNumbers.map((number) => {
                // 使用数字对应的颜色，如果数字超出范围则随机选择
                const color =
                    NUMBER_COLORS[number as keyof typeof NUMBER_COLORS] ||
                    availableColors[
                        Math.floor(Math.random() * availableColors.length)
                    ];
                // 生成随机倾斜角度（-30度到+30度，转换为弧度）
                const angleDegrees = (Math.random() - 0.5) * 60; // -30到+30度
                const angle = (angleDegrees * Math.PI) / 180; // 转换为弧度
                return {
                    number,
                    color,
                    angle,
                };
            });

            groups.push({
                numbers: numbersWithColors,
            });
        }

        this.sortData = {
            groups,
        };

        this.drawCanvas();
    },
});
