// Package domain generated by 'freedom new-project investment'
package domain

import (
	"fmt"
	"investment/adapter/repository"
	"investment/adapter/spider"
	"investment/domain/po/custom"
	"time"

	"github.com/8treenet/freedom"
)

func init() {
	freedom.Prepare(func(initiator freedom.Initiator) {
		initiator.BindService(func() *ClsService {
			return &ClsService{}
		})
		initiator.InjectController(func(ctx freedom.Context) (service *ClsService) {
			initiator.FetchService(ctx, &service)
			return
		})
	})
}

// ClsService 财联社服务  .
type ClsService struct {
	Worker        freedom.Worker
	ClsRepository *repository.CLSRepository
}

// PrepareData 抓取数据到数据库
func (service *ClsService) PrepareData() {
	list, e := spider.GetClsDepthList()
	if e != nil {
		service.Worker.Logger().Error(e)
		return
	}
	time.Sleep(3 * time.Second)

	for _, v := range list {
		article, err := service.ClsRepository.GetArticle(v.ArticleID)
		fmt.Println(article)
		if err != nil {
			service.Worker.Logger().Error(err)
			time.Sleep(10 * time.Second)
		}
		if article.Content != "" {
			continue
		}
		content, err := spider.GetClsDepth(article.ArticleID)
		if err != nil {
			service.Worker.Logger().Error(err)
			time.Sleep(10 * time.Second)
		}
		obj := &custom.ClsDepthArticle{
			ArticleID: article.ArticleID,
			Ctime:     time.Unix(int64(v.Ctime), 0),
			Created:   time.Now(),
			SortScore: v.SortScore,
			Title:     v.Title,
			Brief:     v.Brief,
			Content:   content.Content,
		}
		if err := service.ClsRepository.SaveArticle(obj); err != nil {
			service.Worker.Logger().Error(err)
		}
		time.Sleep(10 * time.Second)
	}
}
