package service import ( "encoding/json" "fmt" "gorm.io/datatypes" "psi/database" "psi/models" systemReq "psi/models/request" systemRes "psi/models/response" "psi/utils" "time" ) type ProductBookService struct{} // List 获取商品反射列表 // List 获取商品反射列表 - 支持按售价+运费统计排序 // List 获取商品反射列表 - 支持按售价+运费统计排序 // List 获取商品反射列表 - 支持按售价+运费统计排序 func (s *ProductBookService) List(req systemReq.GetProductBookListRequest) (*systemRes.ProductBookListResponse, error) { db := database.DB fmt.Printf("【断点1】开始查询商品反射列表\n") if req.Page < 1 { req.Page = 1 } if req.PageSize < 1 || req.PageSize > 100 { req.PageSize = 20 } tableName := "product_book_00" if req.ISBN != "" { tableName = models.ProductBookTableName(req.ISBN) } else if req.Barcode != "" { tableName = models.ProductBookTableName(req.Barcode) } fmt.Printf("【断点2】使用表: %s\n", tableName) query := db.Table(tableName).Where("is_del = ?", 0) if req.ID > 0 { query = query.Where("id = ?", req.ID) } if req.CategoryID > 0 { query = query.Where("category_id = ?", req.CategoryID) } if req.AboutId > 0 { query = query.Where("about_id = ?", req.AboutId) } if req.WarehouseID > 0 { query = query.Where("warehouse_id = ?", req.WarehouseID) } if req.WarehouseName != "" { query = query.Where("warehouse_name LIKE ?", "%"+req.WarehouseName+"%") } if req.LocationID > 0 { query = query.Where("location_id = ?", req.LocationID) } if req.LocationName != "" { query = query.Where("location_name LIKE ?", "%"+req.LocationName+"%") } if req.StandardProductID > 0 { query = query.Where("standard_product_id = ?", req.StandardProductID) } if req.Fid > 0 { query = query.Where("fid = ?", req.Fid) } if req.Type != nil { query = query.Where("type = ?", *req.Type) } if req.ISBN != "" { query = query.Where("isbn = ?", req.ISBN) } if req.FISBN != "" { query = query.Where("f_isbn = ?", req.FISBN) } if req.BookName != "" { query = query.Where("book_name LIKE ?", "%"+req.BookName+"%") } if req.FBookName != "" { query = query.Where("f_book_name LIKE ?", "%"+req.FBookName+"%") } if req.Author != "" { query = query.Where("author LIKE ?", "%"+req.Author+"%") } if req.Publishing != "" { query = query.Where("publishing LIKE ?", "%"+req.Publishing+"%") } if req.PublicationTime > 0 { query = query.Where("publication_time = ?", req.PublicationTime) } if req.Binding != "" { query = query.Where("binding = ?", req.Binding) } if req.PagesCount > 0 { query = query.Where("pages_count = ?", req.PagesCount) } if req.WordsCount > 0 { query = query.Where("words_count = ?", req.WordsCount) } if req.Format > 0 { query = query.Where("format = ?", req.Format) } if req.Name != "" { query = query.Where("name LIKE ?", "%"+req.Name+"%") } if req.Appearance > 0 { query = query.Where("appearance = ?", req.Appearance) } if req.Barcode != "" { query = query.Where("barcode = ?", req.Barcode) } if req.Price > 0 { query = query.Where("price = ?", req.Price) } if req.SalePrice > 0 { query = query.Where("sale_price = ?", req.SalePrice) } if req.Cost > 0 { query = query.Where("cost = ?", req.Cost) } if req.Stock > 0 { query = query.Where("stock = ?", req.Stock) } if req.SelfID > 0 { query = query.Where("self_id = ?", req.SelfID) } if req.IsBatchManaged != nil { query = query.Where("is_batch_managed = ?", *req.IsBatchManaged) } if req.IsShelfLifeManaged != nil { query = query.Where("is_shelf_life_managed = ?", *req.IsShelfLifeManaged) } if req.Status != nil { query = query.Where("status = ?", *req.Status) } if req.StartCreatedAt > 0 { query = query.Where("created_at >= ?", req.StartCreatedAt) } if req.EndCreatedAt > 0 { query = query.Where("created_at <= ?", req.EndCreatedAt) } if req.Keyword != "" { query = query.Where("(book_name LIKE ? OR author LIKE ? OR isbn LIKE ? OR barcode LIKE ?)", "%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%") } fmt.Printf("【断点3】查询条件构建完成\n") var total int64 if err := query.Count(&total).Error; err != nil { fmt.Printf("【断点4】查询总数失败: %v\n", err) return nil, utils.NewError("查询总数失败") } fmt.Printf("【断点5】查询总数: %d\n", total) var books []models.ProductBook offset := (req.Page - 1) * req.PageSize orderClause := "created_at DESC" if req.SortByTotal == "asc" { orderClause = "(sale_price + cost) ASC" fmt.Printf("【断点6】按总价升序排序\n") } else if req.SortByTotal == "desc" { orderClause = "(sale_price + cost) DESC" fmt.Printf("【断点6】按总价降序排序\n") } else { fmt.Printf("【断点6】按创建时间降序排序(默认)\n") } if err := query.Order(orderClause).Offset(offset).Limit(req.PageSize).Find(&books).Error; err != nil { fmt.Printf("【断点7】查询列表失败: %v\n", err) return nil, utils.NewError("查询列表失败") } fmt.Printf("【断点8】查询到 %d 条记录\n", len(books)) items := make([]systemRes.ProductBookItem, 0, len(books)) for _, book := range books { item := systemRes.ConvertProductBookToItem(book) fmt.Printf(" - ID: %d, 书名: %s, 售价: %d, 运费: %d, 库存: %d, SaleID: %d, 总价: %d\n", item.ID, item.BookName, item.SalePrice, item.Cost, item.Stock, item.SelfID, item.TotalPrice) items = append(items, item) } fmt.Printf("【断点9】数据转换完成,准备返回\n") return &systemRes.ProductBookListResponse{ List: items, Total: total, Page: req.Page, PageSize: req.PageSize, }, nil } // Detail 获取商品反射详情 func (s *ProductBookService) Detail(id int64, isbn string) (*systemRes.ProductBookItem, error) { db := database.DB // 根据ISBN确定分表 tableName := models.ProductBookTableName(isbn) var book models.ProductBook if err := db.Table(tableName).Where("id = ? AND is_del = ?", id, 0).First(&book).Error; err != nil { return nil, utils.NewError("商品不存在") } item := systemRes.ConvertProductBookToItem(book) return &item, nil } // Create 创建商品反射 func (s *ProductBookService) Create(req systemReq.ProductBookRequest) (int64, error) { db := database.DB now := time.Now().Unix() var liveImage datatypes.JSON if len(req.LiveImage) > 0 { jsonBytes, _ := json.Marshal(req.LiveImage) liveImage = jsonBytes } else { liveImage = datatypes.JSON("[]") } var catID datatypes.JSON if req.CatID != "" { catID = datatypes.JSON(req.CatID) } else { catID = datatypes.JSON("{}") } tableName := models.ProductBookTableName(req.ISBN) book := models.ProductBook{ CategoryID: req.CategoryID, AboutId: req.AboutId, WarehouseID: req.WarehouseID, WarehouseName: req.WarehouseName, LocationID: req.LocationID, LocationName: req.LocationName, StandardProductID: req.StandardProductID, Fid: req.Fid, Type: req.Type, ISBN: req.ISBN, FISBN: req.FISBN, BookName: req.BookName, FBookName: req.FBookName, Author: req.Author, Publishing: req.Publishing, PublicationTime: req.PublicationTime, Binding: req.Binding, PagesCount: req.PagesCount, WordsCount: req.WordsCount, Format: req.Format, CatID: catID, Name: req.Name, Appearance: req.Appearance, Barcode: req.Barcode, Price: req.Price, SalePrice: req.SalePrice, Cost: req.Cost, Stock: req.Stock, SelfID: req.SelfID, LiveImage: liveImage, IsBatchManaged: req.IsBatchManaged, IsShelfLifeManaged: req.IsShelfLifeManaged, Status: req.Status, CreatedAt: now, UpdatedAt: now, IsDel: 0, } if err := db.Table(tableName).Create(&book).Error; err != nil { return 0, fmt.Errorf("创建商品反射失败: %w", err) } return book.ID, nil } // Update 更新商品反射 func (s *ProductBookService) Update(req systemReq.ProductBookRequest) error { db := database.DB if req.ID == 0 { return utils.NewError("商品ID不能为空") } now := time.Now().Unix() var existingBook models.ProductBook tableName := "" if req.ISBN != "" { tableName = models.ProductBookTableName(req.ISBN) if err := db.Table(tableName).Where("id = ? AND is_del = ?", req.ID, 0).First(&existingBook).Error; err != nil { return utils.NewError("商品不存在") } } else { allTables := models.ProductBookAllTableNames() found := false for _, tName := range allTables { if err := db.Table(tName).Where("id = ? AND is_del = ?", req.ID, 0).First(&existingBook).Error; err == nil { tableName = tName found = true break } } if !found { return utils.NewError("商品不存在") } } var liveImage datatypes.JSON if len(req.LiveImage) > 0 { jsonBytes, _ := json.Marshal(req.LiveImage) liveImage = jsonBytes } else { liveImage = existingBook.LiveImage } var catID datatypes.JSON if req.CatID != "" { catID = datatypes.JSON(req.CatID) } else { catID = existingBook.CatID } updates := map[string]interface{}{ "category_id": req.CategoryID, "about_id": req.AboutId, "warehouse_id": req.WarehouseID, "warehouse_name": req.WarehouseName, "location_id": req.LocationID, "location_name": req.LocationName, "standard_product_id": req.StandardProductID, "fid": req.Fid, "type": req.Type, "f_isbn": req.FISBN, "book_name": req.BookName, "f_book_name": req.FBookName, "author": req.Author, "publishing": req.Publishing, "publication_time": req.PublicationTime, "binding": req.Binding, "pages_count": req.PagesCount, "words_count": req.WordsCount, "format": req.Format, "cat_id": catID, "name": req.Name, "appearance": req.Appearance, "barcode": req.Barcode, "price": req.Price, "sale_price": req.SalePrice, "cost": req.Cost, "stock": req.Stock, "self_id": req.SelfID, "live_image": liveImage, "is_batch_managed": req.IsBatchManaged, "is_shelf_life_managed": req.IsShelfLifeManaged, "status": req.Status, "updated_at": now, } if err := db.Table(tableName).Model(&existingBook).Updates(updates).Error; err != nil { return fmt.Errorf("更新商品反射失败: %w", err) } return nil } // Del 删除商品反射(逻辑删除) func (s *ProductBookService) Del(id int64, isbn string) error { db := database.DB if id == 0 { return utils.NewError("商品ID不能为空") } now := time.Now().Unix() // 根据ISBN确定分表 tableName := models.ProductBookTableName(isbn) var book models.ProductBook if err := db.Table(tableName).Where("id = ? AND is_del = ?", id, 0).First(&book).Error; err != nil { return utils.NewError("商品不存在") } if err := db.Table(tableName).Model(&book).Updates(map[string]interface{}{ "is_del": 1, "updated_at": now, }).Error; err != nil { return fmt.Errorf("删除商品反射失败: %w", err) } return nil }