const designService = require('../services/design.service');

module.exports = {
  // 获取颜色统计数据
  getColorStatistics: async (req, res) => {
    try {
      const stats = await designService.getAllColorsStatistics();
      res.json({
        success: true,
        data: stats
      });
    } catch (error) {
      console.error('获取颜色统计失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取颜色统计数据失败'
      });
    }
  },
  
  // 记录设计使用
  recordDesignUsage: async (req, res) => {
  try {
    // 验证输入数据
    const requiredParts = ['part1', 'part2', 'part3', 'part4'];
    const missingParts = requiredParts.filter(part => !req.body[part]);
    
    if (missingParts.length > 0) {
      throw new Error(`缺少必要的设计参数: ${missingParts.join(', ')}`);
    }

    // 验证颜色代码格式 (2-6位十六进制)
    const colorCodeRegex = /^[0-9A-F]{2,6}$/i;
    const invalidParts = [];
    
    const design = {};
    for (const part of requiredParts) {
      const code = req.body[part].toString().toUpperCase().substring(0, 6);
      if (!colorCodeRegex.test(code)) {
        invalidParts.push(part);
      }
      design[part] = code;
    }
    
    if (invalidParts.length > 0) {
      throw new Error(`无效的颜色代码格式: ${invalidParts.join(', ')}`);
    }
    
    console.log('验证通过的设计数据:', design);
    
    await designService.saveDesign(design);
    res.json({ 
      success: true,
      message: '设计已成功保存'
    });
  } catch (error) {
    console.error('记录设计使用失败:', error);
    res.status(400).json({ 
      success: false,
      error: error.message
    });
  }
}
};