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 Craft(r *GinRouter) {

	// 创建工艺
	r.POST("/craft/create", CreateCraft)

	// 获取工艺详情
	r.GET("/craft/detail/:id", GetCraft)

	// 获取工艺列表
	r.GET("/craft/list", GetCrafts)

	// 更新工艺
	r.POST("/craft/update", UpdateCraft)

	// 删除工艺
	r.POST("/craft/delete/:id", DelCraft)
}

// 创建工艺
func CreateCraft(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	var craft model.Craft

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

	if craft.Name == "" {
		return nil, errors.New("工艺名为空")
	}

	craft.CreateTime = time.Now()
	craft.UpdateTime = time.Now()

	result, err := repo.RepoAddDoc(ctx, repo.CollectionCraft, &craft)
	return result, err
}

// 获取工艺信息
func GetCraft(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	craftId := c.Param("id")
	id, err := primitive.ObjectIDFromHex(craftId)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var craft model.Craft
	option := &repo.DocSearchOptions{
		CollectName: repo.CollectionCraft,
		Query:       repo.Map{"_id": id},
	}

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

	return craft, nil
}

// 获取工艺列表
func GetCrafts(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)}
	}
	if _norm, ok := query["norm"]; ok {
		delete(query, "norm")
		query["norm"] = bson.M{"$regex": _norm.(string)}
	}

	option := &repo.PageSearchOptions{
		CollectName: repo.CollectionCraft,
		Query:       query,
		Page:        page,
		Size:        size,
		Sort:        bson.M{"createTime": -1},
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
}

// 更新工艺
func UpdateCraft(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var craft model.Craft
	err := c.ShouldBindJSON(&craft)
	if err != nil {
		return nil, errors.New("参数错误")
	}
	if craft.Id.Hex() == "" {
		return nil, errors.New("id的为空")
	}

	// if remark = ""
	if craft.Remark == "" {
		craft.Remark = " "
	}
	craft.UpdateTime = time.Now()
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionCraft, craft.Id.Hex(), &craft)
}

// 删除工艺
func DelCraft(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	craftId := c.Param("id")
	if craftId == "" {
		return nil, errors.New("id为空")
	}

	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionCraft, craftId)
}
