package agent

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

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

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

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

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

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

func (l *GetAgentCommissionLogic) GetAgentCommission(req *types.GetCommissionReq) (resp *types.GetCommissionResp, 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.AgentCommissionModel.SelectBuilder().Where(squirrel.Eq{
		"agent_id": agentModel.Id,
	})
	agentCommissionModelList, total, err := l.svcCtx.AgentCommissionModel.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.Commission, 0)

	if len(agentCommissionModelList) > 0 {
		for _, agentCommissionModel := range agentCommissionModelList {
			var commission types.Commission
			copyErr := copier.Copy(&commission, agentCommissionModel)
			if copyErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理佣金列表, %v", err)
			}
			product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, agentCommissionModel.ProductId)
			if findProductErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理佣金列表, %v", err)
			}
			commission.CreateTime = agentCommissionModel.CreateTime.Format("2006-01-02 15:04:05")
			commission.ProductName = product.ProductName
			list = append(list, commission)
		}
	}
	return &types.GetCommissionResp{
		Total: total,
		List:  list,
	}, nil
}
