package admin_agent

import (
	"context"

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

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

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

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

func (l *AdminGetAgentMembershipRechargeOrderListLogic) AdminGetAgentMembershipRechargeOrderList(req *types.AdminGetAgentMembershipRechargeOrderListReq) (resp *types.AdminGetAgentMembershipRechargeOrderListResp, err error) {
	builder := l.svcCtx.AgentMembershipRechargeOrderModel.SelectBuilder()
	if req.UserId != nil {
		builder = builder.Where(squirrel.Eq{"user_id": *req.UserId})
	}
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.OrderNo != nil && *req.OrderNo != "" {
		builder = builder.Where(squirrel.Eq{"order_no": *req.OrderNo})
	}
	if req.PlatformOrderId != nil && *req.PlatformOrderId != "" {
		builder = builder.Where(squirrel.Eq{"platform_order_id": *req.PlatformOrderId})
	}
	if req.Status != nil && *req.Status != "" {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}
	if req.PaymentMethod != nil && *req.PaymentMethod != "" {
		builder = builder.Where(squirrel.Eq{"payment_method": *req.PaymentMethod})
	}
	list, total, err := l.svcCtx.AgentMembershipRechargeOrderModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, err
	}
	items := make([]types.AgentMembershipRechargeOrderListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentMembershipRechargeOrderListItem{}
		_ = copier.Copy(&item, v)
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		items = append(items, item)
	}
	resp = &types.AdminGetAgentMembershipRechargeOrderListResp{
		Total: total,
		Items: items,
	}
	return
}
