package com.fs.app.service;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.company.param.ExecutionContext;
import com.fs.company.service.*;
import com.fs.company.service.impl.call.node.AiCallTaskNode;
import com.fs.course.config.RedisKeyScanner;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class CallTaskService {


    @Value("${cid-group-no}")
    private Integer cidGroupNo;

    private final RedisCacheT<String> redisCache;

    private final RedisCache redisCache2;
    private final CompanyWorkflowEngine companyWorkflowEngine;
    private final ExecutorService cidExcutor = new ThreadPoolExecutor(
            32,
            64,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000),
            r -> new Thread(r, "callPool-" + System.currentTimeMillis()),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );
    private final RedisKeyScanner redisKeyScanner;

    /**
     * 扫描工作流延时任务
     */
    public void cidWorkflowCallRun() {
        log.info("===========工作流延时任务开始扫描===========");
        String delayCallKeyPrefix = AiCallTaskNode.getDelayCallKeyPrefix(cidGroupNo,null) + "*";
        Set<String> keys = redisKeyScanner.scanMatchKey(delayCallKeyPrefix);
        log.info("共扫描到 {} 个待处理键", keys.size());
        keys.parallelStream().forEach(key -> {
            try {
                //doExec
                CompletableFuture.runAsync(() -> {
                    try {
                        ExecutionContext context = redisCache2.getCacheObject(key);
                        context.setVariable("callRedisKey", key);
                        context.setVariable("callSource", "callTaskTimer");
                        companyWorkflowEngine.timeDoExecute(context.getWorkflowInstanceId(), context.getCurrentNodeKey(), context.getVariables());
                    } catch (Exception e) {
                        log.error("处理工作流延时任务异常 - key: {}", key, e);
                    }
                }, cidExcutor).thenRun(()->{
                    redisCache2.deleteObject(key);
                });
            } catch (Exception ex) {
                log.error("处理工作流延时任务异常 - key: {}", key, ex);
            }
        });
        log.info("===========工作流延时任务扫描结束===========");
    }
}
