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"
	"infish.cn/comm"
	"infish.cn/comm/pay"
)

// 根据项目类型 获取支付列表
// query := map[string]interface{}{"project":"queenshow"}

func PayPointList() *comm.NatsMsgReplyer {
	qmap := make(map[string]interface{})
	utils.ConsoleFormat(pay.PayPointListApi)
	return &comm.NatsMsgReplyer{
		Subject: pay.PayPointListApi,
		Entity:  func() interface{} { return &qmap },
		Cb2: func(_ *nats.Msg, entity interface{}) (interface{}, error) {
			query := entity.(*map[string]interface{})
			ctx := context.Background()
			res, err := getPayPoints(ctx, *query)
			return res, err
		},
	}
}

func getPayPoints(ctx context.Context, query map[string]interface{}) (projects []*pay.Point, err error) {
	err = repo.RepoSeachDocs(&repo.RepoSession{Ctx: ctx, Client: db.GMongoDb}, &repo.DocSearchOptions{
		CollectName: repo.CollectionPoint,
		Query:       query,
		Sort:        bson.D{bson.E{Key: "sort", Value: 1}, bson.E{Key: "createTime", Value: -1}},
	}, &projects)
	return
}

// query := map[string]interface{}{"_id":"xxx"}
func PayPointDetail() *comm.NatsMsgReplyer {
	qmap := make(map[string]interface{})
	utils.ConsoleFormat(pay.PayPointDetailApi)
	return &comm.NatsMsgReplyer{
		Subject: pay.PayPointDetailApi,
		Entity:  func() interface{} { return &qmap },
		Cb2: func(_ *nats.Msg, entity interface{}) (interface{}, error) {
			query := entity.(*map[string]interface{})
			ctx := context.Background()
			res, err := getPayPoint(ctx, *query)
			return res, err
		},
	}
}

func getPayPoint(ctx context.Context, query map[string]interface{}) (project *pay.Point, err error) {
	_, err = repo.RepoSeachDoc(&repo.RepoSession{Ctx: ctx, Client: db.GMongoDb}, &repo.DocSearchOptions{
		CollectName: repo.CollectionPoint,
		Query:       query,
	}, &project)
	return
}

// 获取支付价格
// query := map[string]interface{}{"_id":"xxx"}
func GetPointAmount() *comm.NatsMsgReplyer {
	req := &pay.PointAmountReq{}
	utils.ConsoleFormat(pay.PayPointAmountApi)
	return &comm.NatsMsgReplyer{
		Subject: pay.PayPointAmountApi,
		Entity:  func() interface{} { return req },
		Cb2: func(_ *nats.Msg, entity interface{}) (interface{}, error) {
			req := entity.(*pay.PointAmountReq)
			ctx := context.Background()
			res, err := getPointAmount(ctx, req)
			return res, err
		},
	}
}

func getPointAmount(ctx context.Context, req *pay.PointAmountReq) (amount float64, err error) {
	point := pay.Point{}
	_, err = repo.RepoSeachDoc(&repo.RepoSession{Ctx: ctx, Client: db.GMongoDb}, &repo.DocSearchOptions{
		CollectName: repo.CollectionPoint,
		Query:       repo.Map{"_id": req.PointId},
		Project:     []string{"price"},
	}, &point)
	if err != nil {
		return amount, err
	}

	// 计算价格
	_amount := *point.Price * float64(*req.Quantity)
	amount, err = strconv.ParseFloat(fmt.Sprintf("%.2f", _amount), 64)

	return
}
