package api

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

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

func Setting(router *GinRouter) {

	CreateCRUD(router, "/units", &CRUDOption{
		Collection: "units",
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Unit{}
			c.ShouldBindJSON(entity)
			entity.CreateTime = time.Now()
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Unit{}
		},
		JWT:           true,
		SearchProject: []string{"name", "createTime"},
	})

	CreateCRUD(router, "/cates", &CRUDOption{
		Collection: "cates",
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Category{}
			c.ShouldBindJSON(entity)
			entity.CreateTime = time.Now()
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Category{}
		},
		JWT:           true,
		SearchProject: []string{"name", "createTime", "letterName"},
	})

	CreateCRUD(router, "/info", &CRUDOption{
		Collection: "infos",
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Setting{}
			c.ShouldBindJSON(entity)
			entity.UpdateTime = time.Now()
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Setting{}
		},
		JWT:           true,
		SearchProject: []string{"companyName", "updateTime", "address", "phone"},
	})

	//计价策略
	CreateCRUD(router, "/calc", &CRUDOption{
		Collection: "calcs",
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.PriceCalc{}
			c.ShouldBindJSON(entity)
			entity.CreateTime = time.Now()
			entity.UpdateTime = time.Now()
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.PriceCalc{}
		},

		JWT: true,
		OnUpdate: func(c *gin.Context, apictx *ApiSession, entity interface{}) {
			calc := entity.(*model.PriceCalc)
			calc.UpdateTime = time.Now()
			if calc.IsDefault != nil && *calc.IsDefault { //设为默认把其他的所有默认清除
				repo.RepoUpdateSetDocsProps(apictx.CreateRepoCtx(),
					&repo.DocFilterOptions{
						CollectName: "calcs",
						Query:       repo.Map{"category": calc.Category},
					}, bson.M{"isDefault": false})
			}
		},
		SearchProject: []string{"name", "updateTime", "isDefault", "category", "remark", "param1", "param2", "param3", "param4", "param5"},
	})
}
