package api

import (
	"box-cost/db/model"
	"box-cost/db/repo"
	"box-cost/log"
	"errors"

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

var HistoryProject = []string{
	"_id",
	"path",
	"collection",
	"type",
	"userInfo",
	"createTime",
}

func BillHistoryList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// ?query={"targetId":"","collection":""}
	page, size, query := UtilQueryPageSize(c)
	if _, ok := query["targetId"]; !ok {
		return errors.New("目标id不能为空"), nil
	}
	if _, ok := query["collection"]; !ok {
		return errors.New("目标类型不能为空"), nil
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionBillHistory,
		Query:       query,
		Page:        page,
		Size:        size,
		Project:     HistoryProject,
		Sort:        bson.M{"createTime": -1},
	})
}

func GetBillHistory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	hid := c.Param("id")
	id, err := primitive.ObjectIDFromHex(hid)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var history model.History
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionBillHistory,
		Query:       repo.Map{"_id": id},
	}, &history)
	if !found || err != nil {
		log.Info(err)
		return nil, errors.New("数据未找到")
	}

	return history, nil

}

func PlanHistoryList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// ?query={"targetId":"","collection":""}
	page, size, query := UtilQueryPageSize(c)
	if _, ok := query["targetId"]; !ok {
		return errors.New("目标id不能为空"), nil
	}
	if _, ok := query["collection"]; !ok {
		return errors.New("目标类型不能为空"), nil
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionPlanHistory,
		Query:       query,
		Page:        page,
		Size:        size,
		Project:     HistoryProject,
		Sort:        bson.M{"createTime": -1},
	})
}

func GetPlanHistory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	hid := c.Param("id")
	id, err := primitive.ObjectIDFromHex(hid)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var history model.History
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionPlanHistory,
		Query:       repo.Map{"_id": id},
	}, &history)
	if !found || err != nil {
		log.Info(err)
		return nil, errors.New("数据未找到")
	}

	return history, nil

}