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

	CreateCRUD(r, "/address", &CRUDOption{
		Collection: repo.CollectionAddress,
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			entity := &model.Address{}
			c.ShouldBindJSON(entity)
			entity.CreateTime = time.Now()
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)

			if entity.Addr == "" {
				return nil, errors.New("地址不能为空")
			}
			if entity.Contact == "" {
				return nil, errors.New("联系人不能为空")
			}
			entity.UserId = userId
			// 默认设置第一条数据为默认数据
			first, _ := repo.RepoCountDoc(apictx.CreateRepoCtx(), repo.CollectionAddress, repo.Map{"userId": userId})
			if first > 0 {
				entity.Defualt = -1
			} else {
				entity.Defualt = 1
			}
			return entity, nil
		},
		OnUpdate: func(_ *gin.Context, apictx *ApiSession, entity interface{}) {
			address := entity.(*model.Address)
			_userId := apictx.User.ID
			userId, _ := primitive.ObjectIDFromHex(_userId)

			// 更改默认地址的流程
			if address.Defualt == 1 {
				// 将已有的默认地址更改为非默认
				opt := repo.PageSearchOptions{
					CollectName: repo.CollectionAddress,
					Query:       repo.Map{"userId": userId, "defualt": 1},
					Project:     []string{"_id"},
				}
				defs := make([]*model.Address, 0)
				repo.RepoDocsSearch(apictx.CreateRepoCtx(), &opt, &defs)
				if len(defs) > 0 {
					for _, v := range defs {
						// 设置为非默认
						repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionAddress, v.Id.Hex(), &model.Address{Defualt: -1})
					}
				}

			}

		},
		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.Address{}
		},
		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
		},
		SearchProject: []string{"province", "city", "area", "addr", "contact", "phone", "defualt", "createTime"},
		DetailProject: []string{"province", "city", "area", "addr", "contact", "phone", "defualt", "createTime"},
	})
}
