package admin_agent

import (
	"context"

	"bdqr-server/app/main/api/internal/svc"
	"bdqr-server/app/main/api/internal/types"

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentCommissionListLogic) AdminGetAgentCommissionList(req *types.AdminGetAgentCommissionListReq) (resp *types.AdminGetAgentCommissionListResp, err error) {
	builder := l.svcCtx.AgentCommissionModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}
	// 产品名称筛选功能已移除，如需可按product_id筛选

	list, total, err := l.svcCtx.AgentCommissionModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, err
	}

	// 批量查product_name
	productIds := make(map[string]struct{})
	for _, v := range list {
		productIds[v.ProductId] = struct{}{}
	}
	productNameMap := make(map[string]string)
	if len(productIds) > 0 {
		ids := make([]string, 0, len(productIds))
		for id := range productIds {
			ids = append(ids, id)
		}
		builder := l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"id": ids})
		products, _ := l.svcCtx.ProductModel.FindAll(l.ctx, builder, "")
		for _, p := range products {
			productNameMap[p.Id] = p.ProductName
		}
	}

	items := make([]types.AgentCommissionListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentCommissionListItem{}
		_ = copier.Copy(&item, v)
		item.ProductName = productNameMap[v.ProductId]
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		items = append(items, item)
	}
	resp = &types.AdminGetAgentCommissionListResp{
		Total: total,
		Items: items,
	}
	return
}
