package api

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

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

// 产品管理
func Product(r *GinRouter) {
	r.POSTJWT("/product/create", ProductAdd)
	r.GETJWT("/product/list", ProductList)
	r.GETJWT("/product/detail/:id", ProductDetail)
	r.GET("/product/share/detail/:id", ProductDetail)
}

// 新增产品
func ProductAdd(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var form model.Product
	err := c.ShouldBindJSON(&form)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("参数错误！")
	}
	ctx := apictx.CreateRepoCtx()
	if form.SupplyId.Hex() == "" {
		return nil, errors.New("供应链id不能为空")
	}
	if form.Name == "" {
		return nil, errors.New("产品名不能为空")
	}
	form.CreateTime = time.Now()
	// 状态默认为下架
	if form.Status == 0 {
		form.Status = -1
	}

	result, err := repo.RepoAddDoc(ctx, repo.CollectionProduct, &form)
	return result, err

}

// 产品列表
func ProductList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	page, size, query := UtilQueryPageSize(c)
	// asc:升序1  desc:降序-1
	// 默认排序
	onsaleTimeSort := repo.Map{"onsaleTime": -1}
	if _, ok := query["sort"]; ok {
		if query["sort"].(string) == "asc" {
			onsaleTimeSort = repo.Map{"onsaleTime": 1}
		}
		delete(query, "sort")
	}

	// selectTime
	selectTime := time.Now().Format("2006-01")

	// now.AddDate(0, int(-now.Month()) + month + 1, -now.Day()).Format("200612")
	if _, ok := query["selectTime"]; ok {
		timeSlice := strings.Split(query["selectTime"].(string), ".")
		selectTime = strings.Join(timeSlice, "-")
		delete(query, "selectTime")
	}
	timeStr := fmt.Sprintf("%s%s", selectTime, "-01 00:00:00")
	formatTime, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	// 下个月第一天之前的数据
	addOneMothTime := formatTime.AddDate(0, 1, 0)
	query["onsaleTime"] = bson.M{"$lte": addOneMothTime}

	// 查询数据
	if _, ok := query["supplyId"]; !ok {
		return nil, errors.New("供应链id不能为空")
	}
	supplyId, err := primitive.ObjectIDFromHex(query["supplyId"].(string))
	if err != nil {
		return nil, errors.New("供应链id错误")
	}
	query["supplyId"] = supplyId
	// 只展示上架商品
	query["status"] = 1

	option := &repo.PageSearchOptions{
		CollectName: repo.CollectionProduct,
		Page:        page,
		Size:        size,
		Query:       query,
		// Project:     []string{},
		Sort: onsaleTimeSort,
	}
	pageResult, err := repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
	if err != nil {
		return nil, err
	}
	// 查询收藏状态
	var collects []*model.Collect
	_userId := apictx.User.ID
	userId, err := primitive.ObjectIDFromHex(_userId)
	if err != nil {
		return nil, errors.New("非法用户")
	}
	option1 := &repo.PageSearchOptions{
		CollectName: repo.CollectionCollect,
		Query:       repo.Map{"userId": userId, "supplyId": supplyId},
		Project:     []string{"_id", "productId"},
	}
	err1 := repo.RepoDocsSearch(apictx.CreateRepoCtx(), option1, &collects)

	if len(pageResult.List) > 0 {
		for _, v := range pageResult.List {
			v["isCollect"] = false
			v["collectId"] = ""
			if len(collects) > 0 && err1 == nil {
				for _, col := range collects {
					if v["_id"].(primitive.ObjectID) == col.ProductId { // productId唯一
						v["isCollect"] = true
						v["collectId"] = col.Id.Hex()
						break
					}
				}
			}
		}
	}
	return pageResult, err
}

// 产品信息
type ProudctDetailRes struct {
	model.Product
	IsCollect bool                 `json:"isCollect"`
	CollectId string               `json:"collectId"`
	Asset     model.Asset360Fake3d `json:"asset"`
}

func ProductDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	_id := c.Param("id")
	if len(_id) < 1 {
		return nil, errors.New("id不能为空")
	}
	productId, err := primitive.ObjectIDFromHex(_id)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var product model.Product
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionProduct,
		Query:       repo.Map{"_id": productId},
	}, &product)

	if !found || err != nil {
		log.Info(err)
		return nil, errors.New("数据未找到")
	}

	// 素材
	asset := model.Asset360Fake3d{}
	repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionAssets,
		Query:       repo.Map{"_id": product.AssetId},
	}, &asset)

	// 用户登录状态 是否收藏
	if apictx.User != nil {
		_userId := apictx.User.ID
		userId, _ := primitive.ObjectIDFromHex(_userId)
		var collect model.Collect
		found, _ = repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionCollect,
			Query:       repo.Map{"userId": userId, "productId": productId},
		}, &collect)
		return ProudctDetailRes{Product: product, IsCollect: found, CollectId: collect.Id.Hex(), Asset: asset}, nil
	}

	return ProudctDetailRes{Product: product, Asset: asset}, nil
}
