package com.hz.pm.api.common.util;

import com.hz.pm.api.todocenter.bean.entity.WorkNoticeInfo;
import com.ningdatech.basic.model.GenericResult;
import com.ningdatech.zwdd.client.ZwddClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步发送工作通知工具类
 *
 * @author CMM
 * @since 2023/02/23 13:50
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SendWorkNoticeUtil {

    private final ZwddClient zwddClient;

    /**
     * 初始化线程池
     */
    public static final ThreadPoolTaskExecutor EXECUTOR;

    static {
        EXECUTOR = new ThreadPoolTaskExecutor();
        EXECUTOR.setCorePoolSize(2);
        EXECUTOR.setMaxPoolSize(4);
        EXECUTOR.setQueueCapacity(200);
        EXECUTOR.setKeepAliveSeconds(120);
        EXECUTOR.setThreadNamePrefix("sendWorkNotice-");
        EXECUTOR.setWaitForTasksToCompleteOnShutdown(true);
        EXECUTOR.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        EXECUTOR.initialize();
    }

    public Boolean sendWorkNotice(WorkNoticeInfo workNoticeInfo) {

        // 将发送工作通知交给异步任务Future
        String msg = workNoticeInfo.getMsg();
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 调用浙政钉的接口发送工作通知
            long startTime = System.currentTimeMillis();
            GenericResult<Void> result =
                    zwddClient.sendWorkNotice(workNoticeInfo.getReceiverUserId(), workNoticeInfo.getBizMsgId(), msg);
            String resultMsg = result.getMsg();
            if ("success".equals(resultMsg)) {
                log.info("异步任务执行完成, " + workNoticeInfo.getBizMsgId() + " 当前线程：" + Thread.currentThread().getName());
                long endTime = System.currentTimeMillis();
                log.info("方法执行完成返回，耗时：" + (endTime - startTime));
            } else {
                return "发送工作通知失败!";
            }
            return "发送工作通知成功!";
        }, EXECUTOR);
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("获取异步线程处理结果失败!", e);
            Thread.currentThread().interrupt();
        }
        return Boolean.TRUE;
    }

}
