interface GradientConfig {
  direction: string;
  startColor: string;
  endColor: string;
}


// -----------gradient转换逻辑------------
// 定义方向枚举和映射
export enum Orientation {
  TOP_BOTTOM = "t2b",
  TR_BL = "tr2bl", 
  LEFT_RIGHT = "l2r",
  BR_TL = "br2tl",
  BOTTOM_TOP = "b2t",
  RIGHT_LEFT = "r2l",
  TL_BR = "tl2br",
  BL_TR = "bl2tr"
}

interface ColorStop {
  color: string;
  position: string;
}

interface SimplifiedGradient {
  original: string;
  simplified: string;
  firstColor: string;
  lastColor: string;
  originalColorCount: number;
  removedColorCount: number;
}


export class GradientConverter {
  // 匹配 linear-gradient(角度deg, rgba(r,g,b,a) 位置%, rgba(r,g,b,a) 位置%)
  private static readonly CSS_GRADIENT_REGEX = 
    /linear-gradient\((\d+)deg,\s*rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)\s*(\d+)%,\s*rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)\s*(\d+)%\)/;

  /**
   * 将角度转换为 Android Orientation 枚举对应的字符串
   */
  private static angleToDirection(angle: number): string {
    // 标准化角度到 0-360 范围
    const normalizedAngle = ((angle % 360) + 360) % 360;
    
    // 根据 Android Orientation 枚举映射
    if (normalizedAngle >= 337.5 || normalizedAngle < 22.5) {
      return Orientation.TOP_BOTTOM;      // 0° - 上到下
    } else if (normalizedAngle >= 22.5 && normalizedAngle < 67.5) {
      return Orientation.TL_BR;           // 45° - 左上到右下
    } else if (normalizedAngle >= 67.5 && normalizedAngle < 112.5) {
      return Orientation.LEFT_RIGHT;      // 90° - 左到右
    } else if (normalizedAngle >= 112.5 && normalizedAngle < 157.5) {
      return Orientation.BL_TR;           // 135° - 左下到右上
    } else if (normalizedAngle >= 157.5 && normalizedAngle < 202.5) {
      return Orientation.BOTTOM_TOP;      // 180° - 下到上
    } else if (normalizedAngle >= 202.5 && normalizedAngle < 247.5) {
      return Orientation.BR_TL;           // 225° - 右下到左上
    } else if (normalizedAngle >= 247.5 && normalizedAngle < 292.5) {
      return Orientation.RIGHT_LEFT;      // 270° - 右到左
    } else { // 292.5 - 337.5
      return Orientation.TR_BL;           // 315° - 右上到左下
    }
  }
  
  /**
   * 将 RGBA 颜色转换为 8 位 HEX 颜色 (带透明度)
   */
  private static rgbaToHex8(r: number, g: number, b: number, a: number): string {
    const toHex = (value: number): string => {
      const hex = Math.round(value).toString(16);
      return hex.length === 1 ? '0' + hex : hex;
    };
    if(a == 1){
        return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();
    }
    // 将透明度从 0-1 转换为 0-255
    const alpha = Math.round(a * 255);
    return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(alpha)}`.toUpperCase();
  }

  /**
   * 解析 CSS 渐变字符串并转换为自定义格式
   */
  public static convertToCustomFormat(cssGradient: string): string {
    if (!cssGradient?.trim()) {
      throw new Error('渐变字符串不能为空');
    }
    const gradient = this.simplifyGradient(cssGradient).simplified;
    const match = gradient.trim().match(this.CSS_GRADIENT_REGEX);
    
    if (!match) {
      throw new Error("无效的 CSS 渐变格式 : "+cssGradient);
    }

    try {
      // 提取参数
      const angle = parseInt(match[1], 10);
      
      // 起始颜色
      const startR = parseInt(match[2], 10);
      const startG = parseInt(match[3], 10);
      const startB = parseInt(match[4], 10);
      const startA = parseFloat(match[5]);
      
      // 结束颜色
      const endR = parseInt(match[7], 10);
      const endG = parseInt(match[8], 10);
      const endB = parseInt(match[9], 10);
      const endA = parseFloat(match[10]);

      // 转换为目标格式
      const direction = this.angleToDirection(angle);
      const startColorHex = this.rgbaToHex8(startR, startG, startB, startA);
      const endColorHex = this.rgbaToHex8(endR, endG, endB, endA);

      return `\${gradient:linear("${direction}","${startColorHex}","${endColorHex}")}`;
    } catch (error) {
      throw new Error(`解析渐变字符串失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 批量转换多个渐变字符串
   */
  static convertMultiple(gradients: string[]): { original: string; converted: string }[] {
    return gradients.map(original => {
      try {
        const converted = this.convertToCustomFormat(original);
        return { original, converted };
      } catch (error) {
        return { 
          original, 
          converted: `错误: ${error instanceof Error ? error.message : '转换失败'}`
        };
      }
    });
  }



  //

   /**
   * 高级渐变解析，支持各种边界情况
   */
  static parseGradientStopsAdvanced(gradientString: string): ColorStop[] {
    if (!gradientString.includes('gradient')) {
      throw new Error('不是有效的渐变字符串');
    }
    
    // 清理字符串，移除多余空格但保留必要的空格
    const cleaned = gradientString.replace(/\s+/g, ' ').trim();
    
    // 匹配颜色停止点，支持 rgba 和 rgb
    const colorStopRegex = /(rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*[\d.]+)?\s*\))\s*(\d+(?:\.\d+)?%)/gi;
    
    const colorStops: ColorStop[] = [];
    let match;
    
    colorStopRegex.lastIndex = 0;
    
    while ((match = colorStopRegex.exec(cleaned)) !== null) {
      colorStops.push({
        color: match[1].replace(/\s*,\s*/g, ', '), // 标准化颜色格式
        position: match[2]
      });
    }
    
    // 验证解析结果
    if (colorStops.length === 0) {
      console.warn('警告：未解析到任何颜色停止点', gradientString);
    }
    
    return colorStops;
  }
  
  /**
   * 简化渐变，支持任意数量的颜色
   */
  public static simplifyGradient(gradientString: string): SimplifiedGradient {
    const colorStops = this.parseGradientStopsAdvanced(gradientString);
    const originalColorCount = colorStops.length;
    
    if (originalColorCount === 0) {
      return {
        original: gradientString,
        simplified: gradientString,
        firstColor: '',
        lastColor: '',
        originalColorCount: 0,
        removedColorCount: 0
      };
    }
    
    // 提取渐变信息
    const gradientInfo = this.extractGradientInfo(gradientString);
    
    // 如果颜色数量 <= 2，不需要简化
    if (originalColorCount <= 2) {
      return {
        original: gradientString,
        simplified: gradientString,
        firstColor: colorStops[0].color,
        lastColor: colorStops[colorStops.length - 1].color,
        originalColorCount,
        removedColorCount: 0
      };
    }
    
    // 取第一个和最后一个颜色
    const firstStop = colorStops[0];
    const lastStop = colorStops[colorStops.length - 1];
    
    // 构建简化后的渐变
    const simplifiedGradient = this.buildSimplifiedGradient(
      gradientInfo.type,
      gradientInfo.direction,
      firstStop,
      lastStop
    );
    
    return {
      original: gradientString,
      simplified: simplifiedGradient,
      firstColor: firstStop.color,
      lastColor: lastStop.color,
      originalColorCount,
      removedColorCount: originalColorCount - 2
    };
  }
  
  /**
   * 提取渐变类型和方向信息
   */
  private static extractGradientInfo(gradientString: string): { type: string; direction: string } {
    const typeMatch = gradientString.match(/^([a-zA-Z-]+)\(/);
    const type = typeMatch ? typeMatch[1] : 'linear-gradient';
    
    // 提取方向参数
    const content = gradientString.substring(gradientString.indexOf('(') + 1);
    const firstComma = content.indexOf(',');
    const direction = firstComma !== -1 ? content.substring(0, firstComma).trim() : '180deg';
    
    return { type, direction };
  }
  
  /**
   * 构建简化后的渐变字符串
   */
  private static buildSimplifiedGradient(
    type: string, 
    direction: string, 
    firstStop: ColorStop, 
    lastStop: ColorStop
  ): string {
    return `${type}(${direction}, ${firstStop.color} ${firstStop.position}, ${lastStop.color} ${lastStop.position})`;
  }
  
  /**
   * 批量处理渐变数组
   */
  static simplifyGradients(gradients: string[]): SimplifiedGradient[] {
    return gradients.map(gradient => this.simplifyGradient(gradient));
  }
  
  /**
   * 检查渐变是否需要简化
   */
  static needsSimplification(gradientString: string): boolean {
    try {
      const colorStops = this.parseGradientStopsAdvanced(gradientString);
      return colorStops.length > 2;
    } catch {
      return false;
    }
  }
  
  /**
   * 获取渐变统计信息
   */
  static getGradientStats(gradientString: string): {
    colorCount: number;
    needsSimplification: boolean;
    type: string;
  } {
    try {
      const colorStops = this.parseGradientStopsAdvanced(gradientString);
      const gradientInfo = this.extractGradientInfo(gradientString);
      
      return {
        colorCount: colorStops.length,
        needsSimplification: colorStops.length > 2,
        type: gradientInfo.type
      };
    } catch (error) {
      return {
        colorCount: 0,
        needsSimplification: false,
        type: 'unknown'
      };
    }
  }
}