package admin_agent

import (
	"context"

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

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

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

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

func (l *AdminGetAgentRewardListLogic) AdminGetAgentRewardList(req *types.AdminGetAgentRewardListReq) (resp *types.AdminGetAgentRewardListResp, err error) {
	builder := l.svcCtx.AgentRewardsModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.RelationAgentId != nil {
		builder = builder.Where(squirrel.Eq{"relation_agent_id": *req.RelationAgentId})
	}
	if req.Type != nil && *req.Type != "" {
		builder = builder.Where(squirrel.Eq{"type": *req.Type})
	}
	list, total, err := l.svcCtx.AgentRewardsModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, err
	}
	items := make([]types.AgentRewardListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentRewardListItem{}
		_ = copier.Copy(&item, v)
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		if v.RelationAgentId.Valid {
			item.RelationAgentId = v.RelationAgentId.Int64
		}
		items = append(items, item)
	}
	resp = &types.AdminGetAgentRewardListResp{
		Total: total,
		Items: items,
	}
	return
}
