package service

import (
	"context"
	"fmt"
	"gitea.timerzz.com/kedaya_haitao/pusher/biz/dal/postgres"
	"gitea.timerzz.com/kedaya_haitao/pusher/kitex_gen/config"
	push "gitea.timerzz.com/kedaya_haitao/pusher/kitex_gen/push"
)

type ListService struct {
	ctx context.Context
} // NewListService new ListService
func NewListService(ctx context.Context) *ListService {
	return &ListService{ctx: ctx}
}

// Run create note info
func (s *ListService) Run(req *push.ListPusherRequest) (resp *push.ListPusherResponse, err error) {
	// Finish your business logic.
	tx := postgres.DB
	if req.Keyword != "" {
		tx = tx.Where("name LIKE ? or remark LIKE ?", fmt.Sprintf("%%%s%%", req.Keyword), fmt.Sprintf("%%%s%%", req.Keyword))
	}
	resp = new(push.ListPusherResponse)

	if err = tx.Model(&config.PusherConfig{}).Find(&resp.List).Error; err != nil {
		return nil, fmt.Errorf("查询总数失败:%v", err)
	}
	resp.Total = int64(len(resp.List))
	if req.All || resp.Total == 0 {
		return
	}

	// 查询列表
	if req.Page < 1 {
		req.Page = 1
	}
	if req.Size < 1 {
		req.Size = 10
	}
	offset := (req.Page - 1) * int64(req.Size)

	if err = tx.Order("created_at desc").Limit(int(req.Size)).Offset(int(offset)).
		Find(&resp.List).Error; err != nil {
		return nil, fmt.Errorf("查询列表失败:%v", err)
	}
	return
}