package api

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

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

// 包装管理
func Pack(r *GinRouter) {

	// 创建包装
	r.POST("/pack/create", CreatePack)

	// 获取包装详情
	r.GET("/pack/detail/:id", GetPack)

	// 获取包装列表
	r.GET("/pack/list", GetPacks)

	// 更新包装
	r.POST("/pack/update", UpdatePack)

	// 删除包装
	r.POST("/pack/delete/:id", DelPack)
}

// 创建包装
func CreatePack(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	var pack model.Pack

	err := c.ShouldBindJSON(&pack)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("参数错误！")
	}
	ctx := apictx.CreateRepoCtx()

	if pack.Name == "" {
		return nil, errors.New("包装名为空")
	}
	pack.CompCounts = len(pack.Components)
	pack.CreateTime = time.Now()
	pack.UpdateTime = time.Now()

	result, err := repo.RepoAddDoc(ctx, repo.CollectionPack, &pack)
	return result, err
}

// 获取包装信息
func GetPack(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	packId := c.Param("id")
	id, err := primitive.ObjectIDFromHex(packId)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var pack model.Pack
	option := &repo.DocSearchOptions{
		CollectName: repo.CollectionPack,
		Query:       repo.Map{"_id": id},
	}

	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &pack)
	if !found || err != nil {
		log.Info(err)
		return nil, errors.New("数据未找到")
	}

	return pack, nil
}

// 获取包装列表
func GetPacks(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	page, size, query := UtilQueryPageSize(c)
	if _name, ok := query["name"]; ok {
		delete(query, "name")
		query["name"] = bson.M{"$regex": _name.(string)}
	}

	option := &repo.PageSearchOptions{
		CollectName: repo.CollectionPack,
		Query:       query,
		Page:        page,
		Size:        size,
		Sort:        bson.M{"createTime": -1},
		Project:     []string{"_id", "name", "thumbnail", "compCounts", "designer", "updateTime"},
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
}

// 更新包装
func UpdatePack(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var pack model.Pack
	err := c.ShouldBindJSON(&pack)
	if err != nil {
		return nil, errors.New("参数错误")
	}
	if pack.Id.Hex() == "" {
		return nil, errors.New("id的为空")
	}
	pack.UpdateTime = time.Now()
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionPack, pack.Id.Hex(), &pack)
}

// 删除包装
func DelPack(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	packId := c.Param("id")
	if packId == "" {
		return nil, errors.New("id为空")
	}

	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionPack, packId)
}
