package bus

import (
	"context"
	"fmt"
	"pay/db"
	"pay/db/repo"
	"pay/utils"
	"strconv"

	"github.com/nats-io/nats.go"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"infish.cn/comm"
	"infish.cn/comm/pay"
)

// 创建订单
func PayOrderCreate() *comm.NatsMsgReplyer {
	order := pay.Order{}
	utils.ConsoleFormat(pay.PayOrderCreateApi)
	return &comm.NatsMsgReplyer{
		Subject: pay.PayOrderCreateApi,
		Entity:  func() interface{} { return &order },
		Cb2: func(_ *nats.Msg, entity interface{}) (interface{}, error) {
			order := entity.(*pay.Order)
			ctx := context.Background()
			res, err := createOrder(ctx, order)
			return res, err
		},
	}
}

func createOrder(ctx context.Context, order *pay.Order) (id primitive.ObjectID, err error) {
	_id, err := repo.RepoAddDoc(&repo.RepoSession{Ctx: ctx, Client: db.GMongoDb}, repo.CollectionOrder, &order)
	if err != nil {
		return primitive.NilObjectID, err
	}
	id, err = primitive.ObjectIDFromHex(_id)
	return
}

// 获取订单信息
// query := map[string]interface{}{"_id":"xxx"}
func PayOrderDetail() *comm.NatsMsgReplyer {
	qmap := make(map[string]interface{})
	utils.ConsoleFormat(pay.PayOrderDetailApi)
	return &comm.NatsMsgReplyer{
		Subject: pay.PayOrderDetailApi,
		Entity:  func() interface{} { return &qmap },
		Cb2: func(_ *nats.Msg, entity interface{}) (interface{}, error) {
			query := entity.(*map[string]interface{})
			ctx := context.Background()
			res, err := getPayOrder(ctx, *query)
			return res, err
		},
	}
}

func getPayOrder(ctx context.Context, query map[string]interface{}) (order *pay.Order, err error) {
	_, err = repo.RepoSeachDoc(&repo.RepoSession{Ctx: ctx, Client: db.GMongoDb}, &repo.DocSearchOptions{
		CollectName: repo.CollectionOrder,
		Query:       query,
	}, &order)
	amount, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", *order.RealAmount), 64)
	order.RealAmount = &amount
	return
}
