package admin_product

import (
	"context"

	"bdqr-server/app/main/api/internal/svc"
	"bdqr-server/app/main/api/internal/types"
	"bdqr-server/common/xerr"
	"github.com/Masterminds/squirrel"
	"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. 构建产品查询条件
	productBuilder := l.svcCtx.ProductModel.SelectBuilder()

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

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

	if len(productList) == 0 {
		return &types.AdminGetProductListResp{
			Total: total,
			Items: []types.ProductListItem{},
		}, nil
	}

	// 4. 统计每个产品关联功能的成本价之和
	// 4.1 收集产品ID列表
	productIdList := make([]string, 0, len(productList))
	for _, p := range productList {
		productIdList = append(productIdList, p.Id)
	}

	// 4.2 查询 product_feature 记录
	productFeatureBuilder := l.svcCtx.ProductFeatureModel.SelectBuilder().
		Where(squirrel.Eq{"product_id": productIdList})
	productFeatureList, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, productFeatureBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询产品功能关联失败, err: %v, productIds: %+v", err, productIdList)
	}

	// 4.3 没有关联功能时直接返回（成本置 0）
	if len(productFeatureList) == 0 {
		items := make([]types.ProductListItem, 0, len(productList))
		for _, item := range productList {
			listItem := types.ProductListItem{
				Id:          item.Id,
				ProductName: item.ProductName,
				ProductEn:   item.ProductEn,
				Description: item.Description,
				Notes:       item.Notes.String,
				SellPrice:   item.SellPrice,
				CostPrice:   0,
				CreateTime:  item.CreateTime.Format("2006-01-02 15:04:05"),
				UpdateTime:  item.UpdateTime.Format("2006-01-02 15:04:05"),
			}
			items = append(items, listItem)
		}

		return &types.AdminGetProductListResp{
			Total: total,
			Items: items,
		}, nil
	}

	// 4.4 收集 featureId 列表
	featureIdList := make([]string, 0, len(productFeatureList))
	for _, pf := range productFeatureList {
		featureIdList = append(featureIdList, pf.FeatureId)
	}

	// 4.5 查询功能表，取出每个功能的成本价
	featureBuilder := l.svcCtx.FeatureModel.SelectBuilder().
		Where(squirrel.Eq{"id": featureIdList})
	featureList, err := l.svcCtx.FeatureModel.FindAll(l.ctx, featureBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询功能成本价失败, err: %v, featureIds: %+v", err, featureIdList)
	}

	// 4.6 构建 featureId -> cost_price 映射
	featureCostMap := make(map[string]float64, len(featureList))
	for _, f := range featureList {
		featureCostMap[f.Id] = f.CostPrice
	}

	// 4.7 计算每个产品的成本价（所有关联 feature 的 cost_price 之和）
	productCostMap := make(map[string]float64, len(productList))
	for _, pf := range productFeatureList {
		cost, ok := featureCostMap[pf.FeatureId]
		if !ok {
			continue
		}
		productCostMap[pf.ProductId] += cost
	}

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

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