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 AdminGetAgentPlatformDeductionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *AdminGetAgentPlatformDeductionListLogic) AdminGetAgentPlatformDeductionList(req *types.AdminGetAgentPlatformDeductionListReq) (resp *types.AdminGetAgentPlatformDeductionListResp, err error) {
	builder := l.svcCtx.AgentPlatformDeductionModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.Type != nil && *req.Type != "" {
		builder = builder.Where(squirrel.Eq{"type": *req.Type})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}

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

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