package api

import (
	"3dshow/db/model"
	"3dshow/db/repo"
	"errors"
	"time"

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

func Collect(r *GinRouter) {
	CreateCRUD(r, "/collect", &CRUDOption{
		Collection: repo.CollectionCollect,
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Collect{}
			err := c.ShouldBindJSON(entity)
			if err != nil {
				return nil, errors.New("参数错误")
			}
			if len(entity.SupplyId) < 12 {
				return nil, errors.New("供应链id错误")
			}
			if len(entity.ProductId) < 12 {
				return nil, errors.New("产品id错误")
			}
			entity.CreateTime = time.Now()
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)

			// 同一用户对同一产品只能有一条收藏记录
			// 联合唯一索引 db.collect.ensureIndex({userId:1,productId:1},{unique:true})
			opt := &repo.DocSearchOptions{
				CollectName: repo.CollectionCollect,
				Query:       repo.Map{"userId": userId, "productId": entity.ProductId},
			}
			collect := &model.Collect{}
			found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), opt, &collect)
			if found {
				return entity, errors.New("该物品已被收藏")
			}

			entity.UserId = userId
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Collect{}
		},
		JWT: true,
		SearchFilter: func(_ *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{} {
			_userId := apictx.User.ID
			userId, err := primitive.ObjectIDFromHex(_userId)
			if err != nil {

				// 6369f4b028c4bf8b14f47a6b
				invalidId, _ := primitive.ObjectIDFromHex("6369f4b028c4bf8b14f47a6b")
				query["userId"] = invalidId
				return query
			}

			query["userId"] = userId
			return query
		},
		SearchPostProcess: func(page *repo.PageResult, _ *gin.Context, apictx *ApiSession, _ map[string]interface{}) (interface{}, error) {
			// 查询组装数据
			if len(page.List) > 0 {
				for _, v := range page.List {
					// 查询产品信息
					productId := v["productId"].(primitive.ObjectID)
					supplyId := v["supplyId"].(primitive.ObjectID)
					product := model.Product{}
					supply := model.Supply{}
					repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
						CollectName: repo.CollectionProduct,
						Query:       repo.Map{"_id": productId},
						Project:     []string{"name", "unit", "cover"},
					}, &product)
					// 供应商信息
					repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
						CollectName: repo.CollectionSupply,
						Query:       repo.Map{"_id": supplyId},
						Project:     []string{"name", "avatar", "contact"},
					}, &supply)
					v["productName"] = product.Name
					v["productUnit"] = product.Unit
					v["productCover"] = product.Cover
					v["supplyName"] = supply.Name
					v["supplyAvatar"] = supply.Avatar
					v["supplyContact"] = supply.Contact

				}
			}
			return page, nil
		},
	})
}