package com.ningdatech.pmapi.common.util;

import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.model.GenericResult;
import com.ningdatech.pmapi.todocenter.bean.entity.WorkNoticeInfo;
import com.ningdatech.zwdd.client.ZwddClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

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

    private final ZwddClient zwddClient;

    /**
     * 初始化线程池
     */
    public static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 10,
            60, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());

    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 (resultMsg.equals("success")) {
                log.info("异步任务执行完成, " + workNoticeInfo.getBizMsgId() + " 当前线程：" + Thread.currentThread().getName());
                long endTime = System.currentTimeMillis();
                log.info("方法执行完成返回，耗时：" + (endTime - startTime));
            }else {
                return "发送工作通知失败!";
            }
            return "发送工作通知成功!";
            }, threadPool);
            String s;
            try {
                s = future.get();
            }  catch (Exception e) {
                throw new BizException("获取异步线程处理结果失败!");
            }
            threadPool.shutdown();
            while (!threadPool.isTerminated()) {
                log.info(s);
                return Boolean.FALSE;
            }
            log.info(s);
            return Boolean.TRUE;
    }
}
