package api

import (
	"3dshow-customer/db/model"
	"3dshow-customer/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("参数错误")
			}
			entity.CreateTime = time.Now()
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)

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

			entity.UserId = userId
			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Collect{}
		},
		noUpdate: true,
		JWT:      true,
		SearchFilter: func(_ *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{} {
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)
			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.UserSmaple{}
					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{
						Db:          "supply-user",
						CollectName: "users",
						Query:       repo.Map{"_id": supplyId},
						Project:     []string{"name", "avatar", "email"},
					}, &supply)
					v["productName"] = product.Name
					v["productUnit"] = product.Unit
					v["productCover"] = product.Cover
					v["supplyName"] = supply.Name
					v["supplyAvatar"] = supply.Avatar
					v["supplyEmail"] = supply.Email

				}
			}
			return page, nil
		},
	})
}
