package account

import (
	"context"
	"time"

	"bsm/full/module/base/passport/internal/impl"
	"bsm/full/module/base/passport/internal/models"
	pb "bsm/full/module/base/passport/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// 更新会员的信息数据
// 字段值为空或是0，将不更新此数据
func SetData(ctx context.Context, in *pb.SetDataRequest) (reply *pb.StatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	var birthday time.Time
	if in.Birthday != "" {
		birthday, err = time.Parse("2006-01-02", in.Birthday)
		if err != nil {
			return nil, errcode.ErrInvalidArgument
		}
	}

	var data = models.PassportData{
		Nickname:  in.Nickname,
		Avatar:    in.Avatar,
		Sex:       int8(in.Sex),
		Birthday:  birthday,
		Country:   in.Country,
		Province:  in.Province,
		City:      in.City,
		Area:      in.Area,
		Sign:      in.Sign,
		Cover:     in.Cover,
		UpdatedAt: time.Now(),
	}

	var cnt int64
	impl.DBService.Model(&models.PassportData{}).Where("passport_id=?", auth.ID).Count(&cnt)

	if cnt == 0 {
		data.PassportID = auth.ID
		data.PassportIdentity = auth.Identity
		err = impl.DBService.Create(&data).Error
	} else {
		impl.DBService.Where("passport_id=?", auth.ID).Updates(&data)
	}

	if err != nil {
		printer.Error("first or create  by passport_id %v error:%v", auth.ID, err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
