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"
)

// 修改地址
func Modify(ctx context.Context, in *pb.AddressItem) (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,
	}
	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.Where("id=?", in.Id).Updates(&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

}
