package agent

import (
	"context"
	"ycc-server/common/ctxdata"
	"ycc-server/common/xerr"

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

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

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

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

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

func (l *GetAgentRewardsLogic) GetAgentRewards(req *types.GetRewardsReq) (resp *types.GetRewardsResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理奖励列表, %v", err)
	}
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理奖励列表, %v", err)
	}
	builder := l.svcCtx.AgentRewardsModel.SelectBuilder().Where(squirrel.Eq{
		"agent_id": agentModel.Id,
	})
	agentRewardsModelList, total, err := l.svcCtx.AgentRewardsModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理奖励列表, 查找列表错误, %v", err)
	}

	var list = make([]types.Rewards, 0)
	if len(agentRewardsModelList) > 0 {
		for _, agentRewardsModel := range agentRewardsModelList {
			var rewards types.Rewards
			copyErr := copier.Copy(&rewards, agentRewardsModel)
			if copyErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理奖励列表, %v", err)
			}

			rewards.CreateTime = agentRewardsModel.CreateTime.Format("2006-01-02 15:04:05")
			list = append(list, rewards)
		}
	}
	return &types.GetRewardsResp{
		Total: total,
		List:  list,
	}, nil

	return
}
