package api

import (
	"errors"
	"pay/db/repo"
	"pay/log"
	"time"

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

func PayPoint(r *GinRouter) {
	r.POST("/point/create", CreatePay)
	r.POSTJWT("/point/delete/:id", DeletePay)
	r.GET("/point/list", PayList)
	r.GET("/point/detail/:id", PayDetail)
	r.POSTJWT("/point/update", UpdatePay)

}

func CreatePay(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var pay pay.Point
	err := c.ShouldBindJSON(&pay)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	pay.CreateTime = time.Now()
	pay.UpdateTime = time.Now()
	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionPoint, &pay)
}

func DeletePay(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	_id := c.Param("id")
	id, _ := primitive.ObjectIDFromHex(_id)
	if id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionPoint, _id)
}

func PayList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	page, size, query := UtilQueryPageSize(c)
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionPoint,
		Page:        page,
		Size:        size,
		Query:       query,
		Sort:        bson.D{bson.E{Key: "sort", Value: 1}, bson.E{Key: "createTime", Value: -1}},
	})
}

func PayDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	_id := c.Param("id")

	id, _ := primitive.ObjectIDFromHex(_id)
	if id.IsZero() {
		return nil, errors.New("id错误")
	}
	query := repo.Map{"_id": id}
	pay := &pay.Point{}
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionPoint,
		Query:       query,
	}, pay)
	if err != nil {
		log.Error(err)
		return nil, err
	}

	if !found {
		return nil, errors.New("未找到该数据")
	}
	return pay, nil
}

func UpdatePay(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var pay pay.Point
	err := c.ShouldBindJSON(&pay)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if pay.Id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionPoint, pay.Id.Hex(), &pay)
}

func CreateQr(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// payId,

	return nil, nil
}
