package library

import (
	"context"
	"time"

	"bsm/full/module/ec/address/internal/models"
	pb "bsm/full/module/ec/address/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 新增地址
func Create(ctx context.Context, in *pb.AddressCreateRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	address := &models.AddressLibrary{
		Country:  in.Country,
		Phone:    in.Phone,
		Province: in.Province,
		City:     in.City,
		Area:     in.Area,
		Detail:   in.Detail,
		Contact:  in.Contact,
		Name:     in.Name,
		Pics:     in.Pics,
	}
	address.Identity = utils.UUID()
	address.OwnerID = auth.ID
	address.OwnerIdentity = auth.Identity
	address.Status = int8(in.Status)

	if address.Status == 2 {
		models.DBService.Model(&models.AddressLibrary{}).Where("owner_id = ? and status=2", auth.ID).UpdateColumn("status", "1")
	}

	err = models.DBService.Create(address).Error

	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Code:    0,
		Message: "OK",
		Timeseq: time.Now().UnixNano(),
	}, nil

}
