package admin_product

import (
	"context"
	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetProductListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetProductListLogic {
	return &AdminGetProductListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetProductListLogic) AdminGetProductList(req *types.AdminGetProductListReq) (resp *types.AdminGetProductListResp, err error) {
	// 1. 构建查询条件
	builder := l.svcCtx.ProductModel.SelectBuilder()

	// 2. 添加查询条件
	if req.ProductName != nil && *req.ProductName != "" {
		builder = builder.Where("product_name LIKE ?", "%"+*req.ProductName+"%")
	}
	if req.ProductEn != nil && *req.ProductEn != "" {
		builder = builder.Where("product_en LIKE ?", "%"+*req.ProductEn+"%")
	}

	// 3. 执行分页查询
	list, total, err := l.svcCtx.ProductModel.FindPageListByPageWithTotal(
		l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询产品列表失败, err: %v, req: %+v", err, req)
	}

	// 4. 构建响应列表
	items := make([]types.ProductListItem, 0, len(list))
	for _, item := range list {
		listItem := types.ProductListItem{
			Id:          item.Id,
			ProductName: item.ProductName,
			ProductEn:   item.ProductEn,
			Description: item.Description,
			Notes:       item.Notes.String,
			CostPrice:   item.CostPrice,
			SellPrice:   item.SellPrice,
			CreateTime:  item.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:  item.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		items = append(items, listItem)
	}

	// 5. 返回结果
	return &types.AdminGetProductListResp{
		Total: total,
		Items: items,
	}, nil
}
