import type { ChartOption } from '../../types/index';

interface LineValue {
  type: 'line' | 'dashline';
  value: number | [{ name: string; coord: number[]; label: { show: boolean } }, { name: string; coord: number[]; label: { show: boolean } }];
}

export class DrawingTools {
  private readonly lineValues = new Map<string, LineValue>();
  private readonly buttons = new Map<string, any>();
  private startPoint: number[] | null = null;
  private lineId: string | null = null;
  private enableDrawLine = false;
  private enableDrawDashedLine = false;

  constructor(private chart: any) {}

  // 添加标记线
  private addMutiLine(lineId: string, lineValue: LineValue): void {
    this.lineValues.set(lineId, lineValue);

    const markLine = {
      series: [{
        type: 'candlestick',
        markLine: {
          symbol: ['none', 'none'],
          lineStyle: {
            color: 'black',
            width: 2,
            type: 'solid'
          },
          data: [...this.lineValues.values()].map(lineValue => {
            if (lineValue.type === 'line') {
              return { yAxis: lineValue.value };
            } else {
              return lineValue.value;
            }
          })
        }
      }]
    };

    this.chart.setOption(markLine);
  }

  // 坐标转换
  private convertFromPixel(params: { offsetX: number; offsetY: number }, seriesIndex = 0): number[] {
    const pointInPixel = [params.offsetX, params.offsetY];
    return this.chart.convertFromPixel({ seriesIndex }, pointInPixel);
  }

  // 清除标记线
  clearMarkLine(): void {
    this.lineValues.clear();
    this.chart.setOption({ series: [{ markLine: { data: [] } }] });
  }

  // 添加水平线绘制功能
  addDrawLineButton(): any {
    const button = {
      name: 'drawLineButton',
      type: 'rect',
      shape: {
        x: 10,
        y: 10,
        width: 60,
        height: 30
      },
      style: {
        fill: this.enableDrawLine ? 'gray' : '#f00',
        text: this.enableDrawLine ? '取消绘制' : '绘制横线',
        font: 'bold 12px sans-serif'
      },
      onclick: () => this.toggleDrawLine()
    };

    return button;
  }

  // 添加斜线绘制功能
  addDrawDashedLineButton(): any {
    const button = {
      name: 'drawDashedLineButton',
      type: 'rect',
      shape: {
        x: 80,
        y: 10,
        width: 60,
        height: 30
      },
      style: {
        fill: this.enableDrawDashedLine ? 'gray' : '#f00',
        text: this.enableDrawDashedLine ? '取消绘制' : '绘制斜线',
        font: 'bold 12px sans-serif'
      },
      onclick: () => this.toggleDrawDashedLine()
    };

    return button;
  }

  // 添加清除按钮
  addClearLinesButton(): any {
    const button = {
      name: 'clearLinesButton',
      type: 'rect',
      shape: {
        x: 150,
        y: 10,
        width: 60,
        height: 30
      },
      style: {
        fill: '#f00',
        text: '清除线条',
        font: 'bold 12px sans-serif'
      },
      onclick: () => this.clearMarkLine()
    };

    return button;
  }

  // 更新图形元素
  private updateGraphics(name: string, graphic: any): void {
    this.buttons.set(name, graphic);

    const option = {
      graphic: {
        elements: Array.from(this.buttons.values())
      }
    };

    this.chart.setOption(option, { replaceMerge: 'graphic' });
  }

  // 切换水平线绘制状态
  private toggleDrawLine(): void {
    this.enableDrawLine = !this.enableDrawLine;
    this.updateGraphics('drawLineButton', this.addDrawLineButton());
  }

  // 切换斜线绘制状态
  private toggleDrawDashedLine(): void {
    this.enableDrawDashedLine = !this.enableDrawDashedLine;
    this.updateGraphics('drawDashedLineButton', this.addDrawDashedLineButton());
  }

  // 处理鼠标事件
  handleMouseEvent(event: string, params: any): void {
    if (event === 'click' && this.enableDrawLine) {
      this.handleDrawLineClick(params);
    } else if (this.enableDrawDashedLine) {
      if (event === 'mousedown') {
        this.handleDrawDashedLineMouseDown(params);
      } else if (event === 'mousemove') {
        this.handleDrawDashedLineMouseMove(params);
      }
    }
  }

  private handleDrawLineClick(params: any): void {
    const pointInGrid = this.convertFromPixel(params);
    if (pointInGrid) {
      const yValue = pointInGrid[1];
      this.lineId = crypto.randomUUID();
      this.addMutiLine(this.lineId, { type: 'line', value: yValue });
    }
  }

  private handleDrawDashedLineMouseDown(params: any): void {
    if (!this.startPoint) {
      this.startPoint = this.convertFromPixel(params);
      this.lineId = crypto.randomUUID();
    } else {
      this.startPoint = null;
      this.lineId = null;
    }
  }

  private handleDrawDashedLineMouseMove(params: any): void {
    if (!this.startPoint || !this.lineId) return;

    const endPoint = this.convertFromPixel(params);
    this.addMutiLine(this.lineId, {
      type: 'dashline',
      value: [
        {
          name: 'startPoint',
          coord: this.startPoint,
          label: { show: false }
        },
        {
          name: 'endPoint',
          coord: endPoint,
          label: { show: false }
        }
      ]
    });
  }

  public initDrawingTools(): void {
    
    // 创建并缓存所有按钮
    const drawLineButton = this.addDrawLineButton();
    const drawDashedLineButton = this.addDrawDashedLineButton();
    const clearLinesButton = this.addClearLinesButton();

    this.buttons.set('drawLineButton', drawLineButton);
    this.buttons.set('drawDashedLineButton', drawDashedLineButton);
    this.buttons.set('clearLinesButton', clearLinesButton);

    // 使用所有按钮更新图表
    const option = {
      graphic: {
        elements: Array.from(this.buttons.values())
      }
    };

    this.chart.setOption(option, { replaceMerge: 'graphic' });
  }
} 