package pay_recharge

import (
	"context"

	"wechat-api/ent/payrecharge"
	"wechat-api/ent/predicate"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetPayRechargeListLogic) GetPayRechargeList(req *types.PayRechargeListReq) (*types.PayRechargeListResp, error) {
	var predicates []predicate.PayRecharge
	if req.UserId != nil {
		predicates = append(predicates, payrecharge.UserID(*req.UserId))
	}
	if req.OutTradeNo != nil {
		predicates = append(predicates, payrecharge.OutTradeNo(*req.OutTradeNo))
	}
	data, err := l.svcCtx.DB.PayRecharge.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.PayRechargeListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.PayRechargeInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:         &v.UserID,
				Number:         &v.Number,
				Status:         &v.Status,
				Money:          &v.Money,
				OutTradeNo:     &v.OutTradeNo,
				OrganizationId: &v.OrganizationID,
			})
	}

	return resp, nil
}
