package library

import (
	"context"

	"bsm/full/module/ec/address/internal/impl"
	"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 Fetch(ctx context.Context, in *pb.IdentRequest) (reply *pb.AddressListReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var (
		address = make([]*models.AddressLibrary, 0)
		result  = make([]*pb.AddressItem, 0)
	)

	err = impl.DBService.Where("owner_identity=?", auth.Identity).Find(&address).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	for _, item := range address {
		result = append(result, ReflectProtoAddress(item))
	}

	// TODO: add your logic code & delete this line.

	return
}

func ReflectProtoAddress(v *models.AddressLibrary) *pb.AddressItem {
	if nil == v {
		return nil
	}
	result := &pb.AddressItem{
		Id:       int64(v.ID),
		Identity: v.Identity,
		Country:  v.Country,
		Phone:    v.Phone,
		Province: v.Province,
		City:     v.City,
		Area:     v.Area,
		Detail:   v.Detail,
		Contact:  v.Contact,
		Name:     v.Name,
		Pics:     v.Pics,
		Status:   int32(v.Status),
	}
	return result
}
