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

	// 新增材料
	r.POST("/material/create", CreateMaterial)

	// 获取材料信息
	r.GET("/material/detail/:id", GetMaterial)

	// 获取材料列表
	r.GET("/material/list", GetMaterials)

	// 材料列表
	r.POST("/material/update", UpdateMaterial)

	r.POST("/material/delete/:id", DelMaterial)
}

func CreateMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	var material model.Material

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

	if len(material.Name) < 1 {
		return nil, errors.New("材料名为空")
	}
	if len(material.Category) < 1 {
		return nil, errors.New("材料类型为空")
	}

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

	result, err := repo.RepoAddDoc(ctx, repo.CollectionMaterial, &material)
	return result, err
}

// 获取材料信息
func GetMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	materialId := c.Param("id")
	id, err := primitive.ObjectIDFromHex(materialId)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var material model.Material
	option := &repo.DocSearchOptions{
		CollectName: repo.CollectionMaterial,
		Query:       repo.Map{"_id": id},
	}

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

	return material, nil
}

// 获取材料列表
func GetMaterials(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.CollectionMaterial,
		Query:       query,
		Page:        page,
		Size:        size,
		Sort:        bson.M{"createTime": -1},
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
}

func UpdateMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var mat model.Material
	err := c.ShouldBindJSON(&mat)
	if err != nil {
		return nil, errors.New("参数错误")
	}
	if mat.Id == primitive.NilObjectID {
		return nil, errors.New("id的为空")
	}
	mat.UpdateTime = time.Now()
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionMaterial, mat.Id.Hex(), &mat)
}

// 删除材料
func DelMaterial(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	materialId := c.Param("id")
	if materialId == "" {
		return nil, errors.New("id为空")
	}

	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionMaterial, materialId)
}
