package com.yeejoin.amos.knowledgebase.face.util;

import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeInteractionCount;
import com.yeejoin.amos.knowledgebase.face.service.DocAuditService;
import com.yeejoin.amos.knowledgebase.face.service.InteractionCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.exception.BaseException;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 定时刷新标签等引用数量
 *
 * @author tiantao
 */
@Component
public class QuoteCountFlushTiming {

    private static final AtomicBoolean needFlush = new AtomicBoolean(true);
    private static final AtomicBoolean needPush2Rule = new AtomicBoolean(false);

    @Autowired
    private InteractionCountService interactionCountService;
    @Autowired
    private DocAuditService docAuditService;
    @Autowired
    private ConfigLoader configLoader;

    public static void needFlushTag() {
        needFlush.set(true);
    }

    public static void needRulePush() {
        needPush2Rule.set(true);
    }

    @Scheduled(fixedRate = 5 * 1000)
    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public void flushTagQuoteCount() {
        if (needFlush.get()) {
            needFlush.set(false);
            interactionCountService.deleteAllTagQuote();
            List<KnowledgeInteractionCount> allTagQuoteRecords = interactionCountService.getAllTagQuoteRecords();
            if (!allTagQuoteRecords.isEmpty()) {
                allTagQuoteRecords.forEach(e -> e.setAgencyCode(configLoader.getAgencyCode()));
                boolean finished = interactionCountService.saveBatch(allTagQuoteRecords);
                System.out.println("定时-刷新标签引用数-" + (finished ? "完成" : "失败"));
            }
        }
    }

    @Scheduled(fixedRate = 3 * 1000)
    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public void pushDocs2Rule() {
        if (needPush2Rule.get()) {
            needPush2Rule.set(false);
            docAuditService.pushDocs2RuleByMQ();
            System.out.println("定时-同步规则-完成");
        }
    }

}
