package com.fs.app.mq;


import com.fs.common.core.redis.RedisCache;
import com.fs.qw.domain.QwCourseFinishRemarkRty;
import com.fs.qw.service.IQwCourseFinishRemarkRtyService;
import com.fs.qwApi.domain.QwExternalContactRemarkResult;
import com.fs.qwApi.param.QwExternalContactRemarkParam;
import com.fs.qwApi.service.QwApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

@Component
@Slf4j
public class courseFinishRtyTaskOne {

    @Autowired
    private IQwCourseFinishRemarkRtyService finishRemarkRtyService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 完课打备注失败的 重复打 一直到失败 （这个 是销售1的 启动项）
     */

    @Scheduled(cron = "0 0/15 * * * ?") // 每15分钟
//    @Scheduled(cron = "0/1 * * * * ? ") // 每15分钟
    public void selectSopUserLogsListByTimeOne() {

        System.out.println("schedule.task1-enabled111111111");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算10分钟前
        LocalDateTime tenMinutesBefore = now.minusMinutes(10);

        // 创建线程池
        int threadCount = Math.min(8, Runtime.getRuntime().availableProcessors() * 2);
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        try {
            // 使用线程安全的List来收集需要批量更新的数据
            List<Long> batchUpdateList = Collections.synchronizedList(new ArrayList<>());

            // 存储Future对象以便检查所有任务完成情况
            List<Future<?>> futures = new ArrayList<>();

            // 1. 批量查询所有用户数据
            List<QwCourseFinishRemarkRty> remarkRtyList=new ArrayList<>();
            try {
                remarkRtyList = finishRemarkRtyService.selectQwCourseFinishRemarkRtyListByTime(tenMinutesBefore,1);
                if (remarkRtyList == null || remarkRtyList.isEmpty()) {
                     return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("批量查询用户数据失败:" + e.getMessage());
            }

            // 直接遍历contacts而不是userIds
            for (QwCourseFinishRemarkRty remarkRty : remarkRtyList) {
                futures.add(executor.submit(() -> {
                    try {

                        QwExternalContactRemarkParam remarkParam = new QwExternalContactRemarkParam();
                        remarkParam.setRemark(remarkRty.getRemark().trim());
                        remarkParam.setUserid(remarkRty.getQwUserId().trim());
                        remarkParam.setExternal_userid(remarkRty.getExternalUserId().trim());

                        QwExternalContactRemarkResult qwResult = qwApiService.externalcontactRemark(remarkParam, remarkRty.getCorpId());
                        if (qwResult.getErrcode() == 0) {
                            // 添加到批量更新列表
                            batchUpdateList.add(remarkRty.getId());
                        }else {
                            log.error("客户添加备注失败task，userId: {}{}{}", remarkRty.getQwUserId(), remarkRty.getExternalUserId(), qwResult.getErrmsg());
                        }
                    } catch (Exception e) {
                        log.error("客户添加备注失败task，userId: " + remarkRty.getQwUserId() +
                                ", externalUserId: " + remarkRty.getExternalUserId() +
                                ", 错误信息: " + e.getMessage());
                    }
                }));
            }


            // 等待所有任务完成
            for (Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    log.error("任务执行异常: " + e.getMessage());
                    Thread.currentThread().interrupt();
                }
            }

            // 批量更新数据库
            if (!batchUpdateList.isEmpty()) {
                try {
                    // 分批处理，避免单次批量过大
                    int batchSize = 500; // 根据数据库性能调整
                    for (int i = 0; i < batchUpdateList.size(); i += batchSize) {
                        int end = Math.min(i + batchSize, batchUpdateList.size());
                        List<Long> subList = batchUpdateList.subList(i, end);

                        finishRemarkRtyService.deleteQwCourseFinishRemarkRtyByIds(subList.toArray(new Long[0]));
                    }
                } catch (Exception e) {
                    log.error("批量更新失败: " + e.getMessage());
                }
            }

            // 关闭线程池
            executor.shutdown();

        } catch (Exception e) {
            log.error("打备注任务执行异常: " + e.getMessage());
        } finally {
            // 7. 确保线程池关闭
            try {
                // 先尝试正常关闭
                executor.shutdown();
                if (!executor.awaitTermination(15, TimeUnit.SECONDS)) {
                    // 超时后强制关闭
                    executor.shutdownNow();
                    log.warn("线程池强制关闭");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                executor.shutdownNow();
            }
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
            log.info("线程被中断");
        }



    }




    /**
     * 批量删除 掉 前一天的没打上标签的
     */
    @Scheduled(cron = "0 30 0 * * ?")
    public void deleteFinishCourseRemark() {
        long startTimeMillis = System.currentTimeMillis();
        log.info("====== 批量删除 掉 前一天的没打上标签的 ======");

        List<Long> batchUpdateList = finishRemarkRtyService.selectQwCourseFinishRemarkRtyListByOutTime();

        // 批量更新数据库
        if (!batchUpdateList.isEmpty()) {
            try {
                // 分批处理，避免单次批量过大
                int batchSize = 500; // 根据数据库性能调整
                for (int i = 0; i < batchUpdateList.size(); i += batchSize) {
                    int end = Math.min(i + batchSize, batchUpdateList.size());
                    List<Long> subList = batchUpdateList.subList(i, end);

                    finishRemarkRtyService.deleteQwCourseFinishRemarkRtyByIds(subList.toArray(new Long[0]));
                }
            } catch (Exception e) {
                log.error("批量更新失败: " + e.getMessage());
            }
        }

        long endTimeMillis = System.currentTimeMillis();
        log.info("====== 更批量删除 掉 前一天的没打上标签的，耗时 {} 毫秒 ======", (endTimeMillis - startTimeMillis));
    }

}

