package admin_agent

import (
	"context"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"

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

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

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

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

func (l *AdminGetAgentRebateListLogic) AdminGetAgentRebateList(req *types.AdminGetAgentRebateListReq) (resp *types.AdminGetAgentRebateListResp, err error) {
	builder := l.svcCtx.AgentRebateModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.AgentId != nil {
		builder = builder.Where("agent_id = ?", *req.AgentId)
	}
	if req.SourceAgentId != nil {
		builder = builder.Where("source_agent_id = ?", *req.SourceAgentId)
	}
	if req.RebateType != nil {
		builder = builder.Where("rebate_type = ?", *req.RebateType)
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	rebates, total, err := l.svcCtx.AgentRebateModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询返佣列表失败, %v", err)
	}

	// 批量查询产品名称
	productIdSet := make(map[string]struct{})
	for _, rebate := range rebates {
		productIdSet[rebate.ProductId] = struct{}{}
	}
	productIdList := make([]string, 0, len(productIdSet))
	for id := range productIdSet {
		productIdList = append(productIdList, id)
	}
	productNameMap := make(map[string]string)
	if len(productIdList) > 0 {
		products, _ := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"id": productIdList}), "")
		for _, p := range products {
			productNameMap[p.Id] = p.ProductName
		}
	}

	// 组装响应
	items := make([]types.AgentRebateListItem, 0, len(rebates))
	for _, rebate := range rebates {
		items = append(items, types.AgentRebateListItem{
			Id:            rebate.Id,
			AgentId:       rebate.AgentId,
			SourceAgentId: rebate.SourceAgentId,
			OrderId:       rebate.OrderId,
			RebateType:    rebate.RebateType,
			Amount:        rebate.RebateAmount,
			CreateTime:    rebate.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

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