package store

import (
	"context"
	"time"

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

// 店铺搜索
func Search(ctx context.Context, in *pb.MallSearchRequest) (reply *pb.MallSearchReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	var (
		cnt      int64 = 0
		pageNo   int64 = in.GetPageNo()
		pageSize int64 = in.GetPageSize()
		offset   int64 = (pageNo - 1) * pageSize
	)

	if pageNo < 1 {
		pageNo = 1
		offset = 0
	}
	if pageSize < 50 {
		pageSize = 50
		offset = (pageNo - 1) * pageSize
	}
	var data []*models.MallStore
	if err := impl.DBService.Model(&models.MallStore{}).Where("keyword = ?", in.GetKeyword()).Order("created_at desc").Count(&cnt).
		Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.MallSearchReply{
		Count: cnt,
		List:  ModelToReply(data),
	}, nil
}
func ModelToReply(data []*models.MallStore) (list []*pb.StoreBasic) {
	if len(data) == 0 {
		return
	}

	for _, in := range data {
		row := pb.StoreBasic{
			Id:        int64(in.ID),
			Identity:  in.Identity,
			Logo:      in.Logo,
			Title:     in.Title,
			Intro:     in.Intro,
			Template:  in.Template,
			Subdomain: in.Subdomain,
			Configs:   in.Configs,
			CreatedAt: in.CreatedAt.Format(time.DateTime),
			Approve:   int32(in.Approve),
			Keywords:  in.Keywords,
		}

		list = append(list, &row)
	}
	return
}
