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

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

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;

      @Autowired(required = false)
      org.redisson.api.RedissonClient redisson;

    @Value("${spring.redis.mode}")
    private String cluster;

      @Autowired
      private RedisUtils redisUtils;


    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("cluster".equals(cluster)){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time=format.format(new Date());
        String jobName = "knowledgeBase-1" +time;


        RLock lock = redisson.getLock(jobName);
        try {
            //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
            lock.tryLock(10, 20, TimeUnit.SECONDS);
            System.out.println("获取锁成功============");
            //为了防止重复
            if (!redisUtils.hasKey(jobName + "_redisson_key")) {
                redisUtils.set(jobName + "_redisson_key", "1");//

                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 ? "完成" : "失败"));
            }
        }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //释放锁
        }
        }else{
            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("cluster".equals(cluster)) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = format.format(new Date());
            String jobName = "knowledgeBase-2" + time;


            RLock lock = redisson.getLock(jobName);
            try {
                //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
                lock.tryLock(10, 20, TimeUnit.SECONDS);
                System.out.println("获取锁成功============");
                //为了防止重复
                if (!redisUtils.hasKey(jobName + "_redisson_key")) {
                    redisUtils.set(jobName + "_redisson_key", "1");//

                    if (needPush2Rule.get()) {
                        needPush2Rule.set(false);
                        docAuditService.pushDocs2RuleByMQ();
                        System.out.println("定时-同步规则-完成");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); //释放锁
            }
        }else{
            if (needPush2Rule.get()) {
                needPush2Rule.set(false);
                docAuditService.pushDocs2RuleByMQ();
                System.out.println("定时-同步规则-完成");
            }
        }
    }

}
