/**
 * 方位涂涂乐绘制服务
 */

import { BaseDrawService } from '../../../core/draw/baseDraw';
import { getImage } from '../../../utils/index';

/**
 * 方位涂涂乐数据
 */
export interface PositionColoringData {
    /** 参考网格（3x3），存储图片索引数组，按行优先顺序 */
    referenceGrid: number[];
    /** 任务数组，每个任务包含图片索引和位置 */
    tasks: Array<{
        imageIndex: number;
        position: { x: number; y: number };
    }>;
}

/**
 * 方位涂涂乐绘制服务
 */
class PositionColoringDraw extends BaseDrawService {
    gridData: PositionColoringData | null = null;

    constructor(
        canvas: Canvas,
        ctx: RenderingContext,
        options?: Record<string, any>,
    ) {
        super(canvas, ctx, options);
    }

    /**
     * 绘制方位涂涂乐内容
     */
    async draw(gridData: PositionColoringData) {
        if (!gridData || !gridData.referenceGrid || !gridData.tasks) {
            return;
        }

        this.gridData = gridData;
        this.prepareDraw();
        await this.drawHeaderAndDivider();
        await this.drawContent({
            canvas: this.canvas,
            ctx: this.ctx,
            gridData: this.gridData,
            canvasWidth: this.canvasWidth,
            startY: this.currentY,
        });
    }

    /**
     * 绘制内容区域
     */
    private async drawContent(params: {
        canvas: WechatMiniprogram.Canvas;
        ctx: RenderingContext;
        gridData: PositionColoringData;
        canvasWidth: number;
        startY: number;
    }): Promise<void> {
        const { ctx, gridData, canvasWidth } = params;
        let { startY } = params;

        startY = startY + 25;

        const margin = 40; // 左右边距
        const gridSize = 3; // 3x3网格
        const cellSize = 65; // 每个格子的宽度
        const gridWidth = cellSize * gridSize;
        const gridHeight = cellSize * gridSize;

        // 绘制参考网格（上面的九宫格）
        const referenceGridY = startY;
        const referenceGridX =
            margin + (canvasWidth - margin * 2 - gridWidth) / 2; // 居中

        // 绘制参考网格的网格线
        this.drawGridLines(
            referenceGridX,
            referenceGridY,
            cellSize,
            cellSize,
            gridSize,
            gridSize,
        );

        // 绘制参考网格中的图片
        for (let i = 0; i < 9; i++) {
            const row = Math.floor(i / 3);
            const col = i % 3;
            const imageIndex = gridData.referenceGrid[i];
            const imageX = referenceGridX + col * cellSize + cellSize / 2 - 25;
            const imageY = referenceGridY + row * cellSize + cellSize / 2 - 25;

            try {
                const imagePath = `/focusPages/shared/aeests/material/${imageIndex}.png`;
                const image = await getImage(this.canvas, imagePath);
                // @ts-ignore - 微信小程序图片对象有 width 和 height 属性
                const imageSize = 50;
                ctx.drawImage(image, imageX, imageY, imageSize, imageSize);
            } catch (error) {
                console.error(`加载图片失败: ${imageIndex}`, error);
            }
        }

        // 绘制虚线分隔
        const dividerY = referenceGridY + gridHeight + 30;
        this.drawDashedDivider(dividerY, margin);

        // 绘制任务区域（三行三列）
        const taskStartY = dividerY + 30;
        const taskImageSize = 40; // 任务图片大小
        const taskGridSize = 36; // 任务网格每个格子的大小
        const taskGridWidth = taskGridSize * gridSize;
        const taskGridHeight = taskGridSize * gridSize;
        const taskSpacing = 4; // 图片和网格之间的间距
        const taskGroupWidth = taskImageSize + taskSpacing + taskGridWidth;
        const taskGroupSpacing = 24; // 任务组之间的间距
        const taskRowSpacing = 40; // 行之间的间距

        // 计算每行的起始X位置（居中）
        const totalTaskRowWidth = 3 * taskGroupWidth + 2 * taskGroupSpacing;
        const taskRowStartX =
            margin + (canvasWidth - margin * 2 - totalTaskRowWidth) / 2;

        for (let rowIndex = 0; rowIndex < 3; rowIndex++) {
            const currentY =
                taskStartY + rowIndex * (taskGridHeight + taskRowSpacing);

            for (let colIndex = 0; colIndex < 3; colIndex++) {
                const taskIndex = rowIndex * 3 + colIndex;
                const task = gridData.tasks[taskIndex];
                if (!task) continue;

                const currentX =
                    taskRowStartX +
                    colIndex * (taskGroupWidth + taskGroupSpacing);

                // 绘制任务图片（左侧）
                try {
                    const imagePath = `/focusPages/shared/aeests/material/${task.imageIndex}.png`;
                    const image = await getImage(this.canvas, imagePath);
                    const imageX = currentX;
                    const imageY =
                        currentY + (taskGridHeight - taskImageSize) / 2; // 垂直居中
                    ctx.drawImage(
                        image,
                        imageX,
                        imageY,
                        taskImageSize,
                        taskImageSize,
                    );
                } catch (error) {
                    console.error(
                        `加载任务图片失败: ${task.imageIndex}`,
                        error,
                    );
                }

                // 绘制任务网格（右侧）
                const taskGridX = currentX + taskImageSize + taskSpacing;
                const taskGridY = currentY;

                // 绘制网格线
                this.drawGridLines(
                    taskGridX,
                    taskGridY,
                    taskGridSize,
                    taskGridSize,
                    gridSize,
                    gridSize,
                );

                // 第一行需要标记位置（涂深灰色）
                if (rowIndex === 0) {
                    const { x, y } = task.position;
                    const cellX = taskGridX + x * taskGridSize;
                    const cellY = taskGridY + y * taskGridSize;

                    // 填充深灰色
                    ctx.fillStyle = '#666666';
                    ctx.fillRect(
                        cellX + 1,
                        cellY + 1,
                        taskGridSize - 2,
                        taskGridSize - 2,
                    );
                }
            }
        }
    }
}

export default PositionColoringDraw;
