package api

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

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

func Product(r *GinRouter) {

	// 获取生产计划详情
	r.GET("/product/detail/:id", ProductDetail)

	CreateCRUD(r, "/product", &CRUDOption{
		Collection: "product",
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Product{}
			c.ShouldBindJSON(entity)
			entity.CreateTime = time.Now()
			entity.UpdateTime = time.Now()
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Product{}
		},
		SearchFilter: func(c *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{} {
			if _name, ok := query["name"]; ok {
				delete(query, "name")
				query["name"] = bson.M{"$regex": _name.(string)}
			}
			if _norm, ok := query["norm"]; ok {
				delete(query, "norm")
				query["norm"] = bson.M{"$regex": _norm.(string)}
			}

			return query
		},

		JWT: true,
		OnUpdate: func(c *gin.Context, apictx *ApiSession, entity interface{}) {
			product := entity.(*model.Product)
			product.UpdateTime = time.Now()
		},
		SearchProject: []string{"name", "unit", "norm", "price", "category", "remark"},
	})
}

func ProductDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	productId := c.Param("id")
	id, err := primitive.ObjectIDFromHex(productId)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var product model.Product
	option := &repo.DocSearchOptions{
		CollectName: repo.CollectionProduct,
		Query:       repo.Map{"_id": id},
	}

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

	return product, nil

}
