package api

import (
	"3dshow-customer/db/model"
	"3dshow-customer/db/repo"
	"context"
	"errors"
	"fmt"
	"time"

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

func ShopCart(r *GinRouter) {
	r.POSTJWT("/shopCart/deleteBatch", ShopCartDeleteBatch)
	r.GETJWT("/shopCart/groupList", shopCartGroupList)

	CreateCRUD(r, "/shopCart", &CRUDOption{
		Collection: repo.CollectionShopCart,
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.ShopCart{}
			err := c.ShouldBindJSON(entity)
			if err != nil {
				return nil, errors.New("参数错误")
			}
			entity.CreateTime = time.Now()
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)
			entity.UserId = userId

			return entity, nil
		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.ShopCart{}
		},
		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
		},
		OnUpdate: func(_ *gin.Context, _ *ApiSession, entity interface{}) {
			ety := entity.(*model.ShopCart)
			ety.UpdateTime = time.Now()
		},
		SearchPostProcess: func(page *repo.PageResult, _ *gin.Context, apictx *ApiSession, _ map[string]interface{}) (interface{}, error) {
			// 查询组装数据
			if len(page.List) > 0 {
				for _, v := range page.List {
					// 查询产品信息
					supplyId := v["supplyId"].(primitive.ObjectID)
					supply := model.UserSmaple{}
					// 供应商信息
					repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
						Db:          "supply-user",
						CollectName: "users",
						Query:       repo.Map{"_id": supplyId},
						Project:     []string{"name", "avatar", "email"},
					}, &supply)
					v["supplyName"] = supply.Name
					v["supplyAvatar"] = supply.Avatar
					v["supplyEmail"] = supply.Email

				}
			}
			return page, nil
		},
	})
}

// 批量删除
type ShopCartDeleteBatchReq struct {
	Ids []string `json:"ids"`
}

func ShopCartDeleteBatch(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var form ShopCartDeleteBatchReq
	err := c.ShouldBindJSON(&form)
	if err != nil {
		fmt.Println(form)
		return nil, errors.New("参数错误")
	}
	if len(form.Ids) > 0 {
		// 批量删除
		for _, v := range form.Ids {
			// id 错误
			_, err := primitive.ObjectIDFromHex(v)
			if err != nil {
				continue
			}
			// 删除
			repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionShopCart, v)

		}
	}

	return true, nil
}

// 供应链分组列表 数据库分组
func shopCartGroupList(_ *gin.Context, apictx *ApiSession) (interface{}, error) {
	userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
	mongo := apictx.Svc.Mongo
	cond := []interface{}{
		bson.M{"$match": bson.M{"userId": userId}},
		bson.M{"$group": bson.M{"_id": "$supplyId", "products": bson.M{"$push": "$$ROOT"}}},
		bson.M{"$project": bson.M{"_id": 0, "supplyId": "$_id", "products": 1}},
	}
	tmp, err := mongo.GetCollection(repo.CollectionShopCart).Aggregate(context.Background(), cond)
	if err != nil {
		return nil, err
	}
	defer tmp.Close(context.Background())
	list := make([]map[string]interface{}, 0)
	tmp.All(context.Background(), &list)
	if len(list) > 0 {
		for _, item := range list {
			supply := model.UserSmaple{}
			supplyId := item["supplyId"].(primitive.ObjectID)
			// 供应商信息
			repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
				Db:          "supply-user",
				CollectName: "users",
				Query:       repo.Map{"_id": supplyId},
			}, &supply)
			item["supply"] = supply
			delete(item, "supplyId")

		}
	}

	return list, nil
}
