Browse Source

feat:增加前端上传

0235645 18 hours ago
parent
commit
1757671224

+ 24 - 15
cloth-design/src/app/modules/cloth/mobile/page-design/page-design.component.ts

@@ -1,4 +1,3 @@
-// page-design.component.ts
 import { Component, ChangeDetectorRef } from '@angular/core';
 import { FormsModule } from '@angular/forms';
 import { CommonModule } from '@angular/common';
@@ -47,7 +46,7 @@ export class PageDesignComponent {
   
   colorUsage: ColorUsage = new ColorUsage();
 
-  // 新增的AI助手相关变量
+  // 新增的AI助手相关变量(完全保持不变)
   aiMessages: { text: string | SafeHtml; isUser: boolean; isLoading?: boolean; isTrend?: boolean }[] = [
     { text: '您好!我是您的羽绒服设计助手。我可以根据您的喜好推荐颜色搭配,或者帮您分析当前设计的流行度。有什么我可以帮您的吗?', isUser: false }
   ];
@@ -101,7 +100,7 @@ export class PageDesignComponent {
     private sanitizer: DomSanitizer
   ) {}
 
-  // 原有设计界面的方法(保持不变
+  // 原有设计界面的方法(仅修改颜色处理部分
   selectPart(part: string) {
     this.activePart = part;
   }
@@ -134,25 +133,35 @@ export class PageDesignComponent {
   }
 
   private darkenColor(color: string, percent: number): string {
-    const num = parseInt(color.replace('#', ''), 16);
-    const amt = Math.round(2.55 * percent);
-    const R = (num >> 16) - amt;
-    const G = (num >> 8 & 0x00FF) - amt;
-    const B = (num & 0x0000FF) - amt;
+    // 更健壮的颜色变暗算法
+    const hex = color.replace('#', '');
     
-    return '#' + (
-      0x1000000 +
-      (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
-      (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
-      (B < 255 ? B < 1 ? 0 : B : 255)
-    ).toString(16).slice(1);
+    // 处理3位HEX格式
+    const fullHex = hex.length === 3 
+      ? hex.split('').map(c => c + c).join('')
+      : hex.padEnd(6, '0').substring(0, 6);
+    
+    // 解析RGB分量
+    const r = Math.max(0, Math.min(255, parseInt(fullHex.substring(0, 2), 16)));
+    const g = Math.max(0, Math.min(255, parseInt(fullHex.substring(2, 4), 16)));
+    const b = Math.max(0, Math.min(255, parseInt(fullHex.substring(4, 6), 16)));
+    
+    // 计算变暗值
+    const amount = Math.round(2.55 * percent);
+    const newR = Math.max(0, r - amount);
+    const newG = Math.max(0, g - amount);
+    const newB = Math.max(0, b - amount);
+    
+    // 转换回HEX
+    const toHex = (c: number) => c.toString(16).padStart(2, '0');
+    return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`;
   }
 
   getColorUsage(): { [key: string]: number } {
     return this.colorUsage.getAll();
   }
 
-  // 新增的AI助手方法
+  // 新增的AI助手方法(完全保持不变)
   toggleAIModal() {
     this.showAIModal = !this.showAIModal;
     if (this.showAIModal) {

+ 16 - 26
cloth-design/src/app/services/design-api.service.ts

@@ -1,38 +1,28 @@
 import { Injectable } from '@angular/core';
-import { HttpClient } from '@angular/common/http';
-import { Observable } from 'rxjs';
-import { environment } from '../../environments/environment';
+import { HttpClient, HttpErrorResponse } from '@angular/common/http';
+import { Observable, catchError, throwError } from 'rxjs';
 
 @Injectable({
   providedIn: 'root'
 })
 export class DesignApiService {
-  private apiUrl = `${environment.apiUrl}/designs`;
+  private apiUrl = 'http://localhost:3000/api/designs';
 
-  constructor(private http: HttpClient) {}
+  constructor(private http: HttpClient) { }
 
-  // 获取颜色统计数据
-  getAllColorsStatistics(): Observable<any> {
-    return this.http.get(`${this.apiUrl}/color-statistics`);
-  }
-
-  // 记录设计使用
-  saveDesign(design: {
-    part1: string;
-    part2: string;
-    part3: string;
-    part4: string;
-  }): Observable<any> {
-    return this.http.post(`${this.apiUrl}/record`, design);
+  recordDesignUsage(design: any): Observable<any> {
+    return this.http.post(`${this.apiUrl}/record`, design).pipe(
+      catchError((error: HttpErrorResponse) => {
+        // 提取更详细的错误信息
+        const errorMsg = error.error?.error || 
+                        error.message || 
+                        '保存设计时发生未知错误';
+        return throwError(() => new Error(errorMsg));
+      })
+    );
   }
 
-  // 生成测试数据
-  generateTestData(count: number): Observable<any> {
-    return this.http.post(`${this.apiUrl}/generate-test-data?count=${count}`, {});
-  }
-
-  // 重置统计数据
-  resetStatistics(): Observable<any> {
-    return this.http.post(`${this.apiUrl}/reset-statistics`, {});
+  getColorStatistics(): Observable<any> {
+    return this.http.get(`${this.apiUrl}/color-statistics`);
   }
 }

+ 41 - 21
end-b/src/controllers/design.controller.js

@@ -1,6 +1,6 @@
 const designService = require('../services/design.service');
 
-const designController = {
+module.exports = {
   // 获取颜色统计数据
   getColorStatistics: async (req, res) => {
     try {
@@ -20,25 +20,45 @@ const designController = {
   
   // 记录设计使用
   recordDesignUsage: async (req, res) => {
-    try {
-      const design = {
-        part1: req.body.part1,
-        part2: req.body.part2,
-        part3: req.body.part3,
-        part4: req.body.part4,
-      };
-      
-      await designService.saveDesign(design);
-      res.json({ success: true });
-    } catch (error) {
-      console.error('记录设计使用失败:', error);
-      res.status(400).json({ 
-        success: false,
-        error: error.message
-      });
+  try {
+    // 验证输入数据
+    const requiredParts = ['part1', 'part2', 'part3', 'part4'];
+    const missingParts = requiredParts.filter(part => !req.body[part]);
+    
+    if (missingParts.length > 0) {
+      throw new Error(`缺少必要的设计参数: ${missingParts.join(', ')}`);
     }
-  }
-};
 
-// 确保正确导出控制器对象
-module.exports = designController;
+    // 验证颜色代码格式 (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
+    });
+  }
+}
+};

+ 4 - 2
end-b/src/database.js

@@ -159,8 +159,10 @@ exports.getAllDesignUsage = async () => {
 exports.recordDesignUsage = async (design) => {
   await exports.executeInTransaction(async (client) => {
     const colors = [
-      design.part1, design.part2, 
-      design.part3, design.part4
+      design.part1.substring(0, 6), // 确保不超过6个字符
+      design.part2.substring(0, 6),
+      design.part3.substring(0, 6),
+      design.part4.substring(0, 6)
     ];
     
     for (let partId = 1; partId <= 4; partId++) {

+ 12 - 1
end-b/src/services/design.service.js

@@ -1,4 +1,4 @@
-const { getAllDesignUsage } = require('../database');
+const { getAllDesignUsage, recordDesignUsage } = require('../database');
 
 // 颜色映射配置
 const COLOR_MAPPING = [
@@ -70,6 +70,17 @@ class DesignService {
       throw error;
     }
   }
+
+  // 保存设计
+  async saveDesign(design) {
+    try {
+      await recordDesignUsage(design);
+      return true;
+    } catch (error) {
+      console.error('保存设计失败:', error);
+      throw error;
+    }
+  }
 }
 
 module.exports = new DesignService();