const { getAllDesignUsage, recordDesignUsage } = require('../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: '海洋蓝' },
  { code: '10', hex: '#ff9aa2', name: '西瓜红' },
  { code: '11', hex: '#40e0d0', name: '蓝绿色' },
  { code: '12', hex: '#f0e68c', name: '卡其黄' },
  { code: '13', hex: '#c8a2c8', name: '丁香紫' },
];

// 根据颜色代码获取颜色信息
function getColorInfo(code) {
  return COLOR_MAPPING.find(c => c.code === code) || {
    code,
    hex: '#CCCCCC',
    name: '未知色'
  };
}

class DesignService {
  // 获取所有颜色统计数据
  async getAllColorsStatistics() {
    try {
      const allUsage = await getAllDesignUsage();
      
      // 按部件分组
      const byPart = {};
      
      for (const item of allUsage) {
        if (!byPart[item.partId]) {
          byPart[item.partId] = [];
        }
        
        const colorInfo = 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) {
      console.error('获取颜色统计数据失败:', error);
      throw error;
    }
  }

  // 保存设计
  async saveDesign(design) {
    try {
      await recordDesignUsage(design);
      return true;
    } catch (error) {
      console.error('保存设计失败:', error);
      throw error;
    }
  }
}

module.exports = new DesignService();