import {
  getAllDesignUsage,
  recordDesignUsage
} from '../database';

// 颜色映射配置
const COLOR_MAPPING = [
  { code: '00', hex: '#3498db', name: '天空蓝' },
  { code: '01', hex: '#e74c3c', name: '热情红' },
  { code: '02', hex: '#2ecc71', name: '森林绿' },
  { code: '03', hex: '#f1c40f', name: '阳光黄' },
  { code: '04', hex: '#9b59b6', name: '紫罗兰' },
  { code: '05', hex: '#1abc9c', name: '碧波绿' },
  { code: '06', hex: '#e67e22', name: '落日橙' },
  { code: '07', hex: '#2c3e50', name: '午夜蓝' },
  { code: '08', hex: '#ecf0f1', name: '云朵白' },
  { code: '09', hex: '#e84393', name: '玫瑰粉' },
  { code: '0A', hex: '#ffeaa7', name: '奶油黄' },
  { code: '0B', hex: '#ffb6c1', name: '樱花粉' },
  { code: '0C', hex: '#98ff98', name: '薄荷绿' },
  { code: '0D', hex: '#b399d4', name: '薰衣草' },
  { code: '0E', hex: '#ff7f50', name: '珊瑚橙' },
  { code: '0F', hex: '#89cff0', name: '海洋蓝' },
];

class DesignService {
  // 保存设计选择
  async saveDesign(design: {
    part1: string;
    part2: string;
    part3: string;
    part4: string;
  }) {
    // 验证颜色代码
    const isValid = Object.values(design).every(
      color => /^[0-9A-Fa-f]{2}$/.test(color)
    );
    
    if (!isValid) {
      throw new Error('无效的颜色代码。必须是两位十六进制值 (00-FF)');
    }
    
    // 转换为大写确保一致性
    const normalizedDesign = {
      part1: design.part1.toUpperCase(),
      part2: design.part2.toUpperCase(),
      part3: design.part3.toUpperCase(),
      part4: design.part4.toUpperCase(),
    };
    
    await recordDesignUsage(normalizedDesign);
  }

  // 获取所有颜色统计数据
  async getAllColorsStatistics() {
    try {
      const allUsage = await getAllDesignUsage();
      
      // 按部件分组
      const byPart: Record<number, Array<{
        code: string;
        hex: string;
        name: string;
        usageCount: number;
      }>> = {};
      
      for (const item of allUsage) {
        if (!byPart[item.partId]) {
          byPart[item.partId] = [];
        }
        
        const colorInfo = this.getColorInfo(item.colorCode);
        byPart[item.partId].push({
          code: item.colorCode,
          hex: colorInfo.hex,
          name: colorInfo.name,
          usageCount: item.usageCount
        });
      }
      
      // 对每个部件的颜色按使用次数排序
      for (const partId in byPart) {
        byPart[partId].sort((a, b) => b.usageCount - a.usageCount);
      }
      
      return {
        byPart,
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      const err = error as Error;
      throw new Error(`获取颜色统计数据失败: ${err.message}`);
    }
  }
  
  // 根据颜色代码获取颜色信息
  getColorInfo(code: string) {
    const foundColor = COLOR_MAPPING.find(c => c.code === code);
    return foundColor || {
      code,
      hex: '#CCCCCC',
      name: '未知色'
    };
  }
}

export const designService = new DesignService();