package admin_agent

import (
	"context"
	"errors"

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

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

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

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

func (l *AdminGetAgentWalletTransactionListLogic) AdminGetAgentWalletTransactionList(req *types.AdminGetAgentWalletTransactionListReq) (resp *types.AdminGetAgentWalletTransactionListResp, err error) {
	builder := l.svcCtx.AgentWalletTransactionModel.SelectBuilder()

	// 必须传入代理ID
	if req.AgentId == 0 {
		return nil, errors.New("代理ID不能为空")
	}

	builder = builder.Where(squirrel.Eq{"agent_id": req.AgentId})

	// 可选条件
	if req.TransactionType != nil && *req.TransactionType != "" {
		builder = builder.Where(squirrel.Eq{"transaction_type": *req.TransactionType})
	}
	if req.CreateTimeStart != nil && *req.CreateTimeStart != "" {
		builder = builder.Where(squirrel.GtOrEq{"create_time": *req.CreateTimeStart})
	}
	if req.CreateTimeEnd != nil && *req.CreateTimeEnd != "" {
		builder = builder.Where(squirrel.LtOrEq{"create_time": *req.CreateTimeEnd})
	}

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

	items := make([]types.AgentWalletTransactionListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentWalletTransactionListItem{
			Id:                  v.Id,
			AgentId:             v.AgentId,
			TransactionType:     v.TransactionType,
			Amount:              v.Amount,
			BalanceBefore:       v.BalanceBefore,
			BalanceAfter:        v.BalanceAfter,
			FrozenBalanceBefore: v.FrozenBalanceBefore,
			FrozenBalanceAfter:  v.FrozenBalanceAfter,
			CreateTime:          v.CreateTime.Format("2006-01-02 15:04:05"),
		}
		if v.TransactionId.Valid {
			item.TransactionId = &v.TransactionId.String
		}
		if v.RelatedUserId.Valid {
			item.RelatedUserId = &v.RelatedUserId.Int64
		}
		if v.Remark.Valid {
			item.Remark = &v.Remark.String
		}
		items = append(items, item)
	}

	resp = &types.AdminGetAgentWalletTransactionListResp{
		Total: total,
		Items: items,
	}
	return
}
