package com.hz.pm.api.todocenter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ningdatech.basic.model.GenericResult;
import com.ningdatech.basic.util.NdDateUtils;
import com.ningdatech.file.entity.vo.result.FileResultVO;
import com.ningdatech.file.service.FileService;
import com.hz.pm.api.AppTests;
import com.hz.pm.api.projectlib.model.enumeration.ProjectTypeNewEnum;
import com.hz.pm.api.projectlib.manage.ProjectLibManage;
import com.hz.pm.api.projectlib.model.entity.Project;
import com.hz.pm.api.projectlib.model.vo.ProjectDetailVO;
import com.hz.pm.api.projectlib.service.IProjectService;
import com.hz.pm.api.staging.service.INdWorkNoticeStagingService;
import com.hz.pm.api.sys.manage.NoticeManage;
import com.hz.pm.api.todocenter.bean.entity.WorkNoticeInfo;
import com.hz.pm.api.todocenter.manage.TodoCenterManage;
import com.hz.pm.api.todocenter.model.dto.PdfGenerateDTO;
import com.hz.pm.api.todocenter.utils.PdfUtils;
import com.hz.pm.api.user.service.IUserInfoService;
import com.ningdatech.zwdd.client.ZwddClient;
import com.wflow.contants.ProcessConstant;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.history.NativeHistoricTaskInstanceQuery;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.*;
import static com.hz.pm.api.todocenter.constant.WorkNoticeConstant.PASS_MSG_TEMPLATE;

/**
 * 待办中心测试
 *
 * @author CMM
 * @since 2023/02/15 22:03
 */
@Slf4j
public class TodoCenterTest extends AppTests {
    @Autowired
    private TodoCenterManage todoCenterManage;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private ZwddClient zwddClient;
    @Autowired
    private INdWorkNoticeStagingService workNoticeStagingService;
    @Autowired
    private ProjectLibManage projectLibManage;
    @Autowired
    private FileService fileService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private PdfUtils pdfUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private NoticeManage handlerManage;

    @Test
    public void sendWorkNoticeTest() throws ExecutionException, InterruptedException {
        //String msg = String.format(PASS_MSG_TEMPLATE, "发改委", "0223-00-测试项目");
        //log.info("开始发送工作通知");
        //zwddClient.sendWorkNotice("846085", "0223-00", msg);
        //// zwddClient.sendWorkNotice("829728","0216-5",msg);
        //log.info("发送工作通知结束");

        //ApplicationContext ac = new AnnotationConfigApplicationContext(BeanConfig.class);
        //
        ////若没有指定属性名，则默认为方法名
        //TaskExecutor taskExecutor = (TaskExecutor) ac.getBean("executor");

        String userId = "4";
        // 获取发送浙政钉工作通知必要信息
        WorkNoticeInfo workNoticeInfo = handlerManage.getSendWorkNoticeInfo(userId);
        // workNoticeInfo.setBizMsgId("1");
        String msg = String.format(PASS_MSG_TEMPLATE, "发改委", "0223-02-测试项目");

        //// 先创建1个活动线程的线程池
        //ExecutorService executor = Executors.newFixedThreadPool(1);

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

        // 将发送工作通知交给异步任务Future
        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 = future.get();
        threadPool.shutdown();
        while (threadPool.isTerminated()) {
            log.info(s);
            break;
        }
    }

    @Test
    public void sendWorkNoticeTest2(){
        String userId = "2";
        // 获取发送浙政钉工作通知必要信息
        WorkNoticeInfo passWorkNoticeInfo = handlerManage.getSendWorkNoticeInfo(userId);
        String passMsg = String.format(PASS_MSG_TEMPLATE, passWorkNoticeInfo.getOrganizationName(), "测试项目0301-1");
        passWorkNoticeInfo.setMsg(passMsg);
        // 放入工作通知暂存表中，通过扫表异步发送
//        workNoticeStagingService.addByWorkNotice(passWorkNoticeInfo, MsgTypeEnum.AUDIT);
    }

    @Test
    public void GeneratePdf(){
        // 获取本地目录的pdf模板
        String fileName = "预审申请单";
        InputStream htmlInputStream =
            this.getClass().getClassLoader().getResourceAsStream("template/" + fileName + ".html");
        // 获取表单数据
        ProjectDetailVO projectDetail = projectLibManage.getProjectDetail(44L);
        PdfGenerateDTO pdfGenerateDTO = new PdfGenerateDTO();
        BeanUtils.copyProperties(projectDetail, pdfGenerateDTO);
        // 设置pdf模板参数
        JSONObject paramsMap = JSONObject.parseObject(JSONObject.toJSONString(pdfGenerateDTO));
        paramsMap.put("time", NdDateUtils.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm"));
        paramsMap.put("isTemporaryAugment", "否");
        String projectType = projectDetail.getProjectType();
        paramsMap.put("projectType", ProjectTypeNewEnum.getDesc(projectType));
        Integer isFirst = projectDetail.getIsFirst();
        paramsMap.put("isFirst", "是");
        Boolean isInnovateWholeProvinceShare = projectDetail.getIsInnovateWholeProvinceShare();
        paramsMap.put("isInnovateWholeProvinceShare", Boolean.TRUE.equals(isInnovateWholeProvinceShare) ? "是" : "否");
        String beginTime = projectDetail.getBeginTime();
        String endTime = projectDetail.getEndTime();
        String beginAndEndTime = beginTime + StrUtil.DASHED + endTime;
        paramsMap.put("beginAndEndTime", beginAndEndTime);
        Integer fourSystems = projectDetail.getFourSystems();
        paramsMap.put("fourSystems", "业务应用");
        Integer isDigitalReform = projectDetail.getIsDigitalReform();
        paramsMap.put("isDigitalReform", "否");
        Integer isCloud = projectDetail.getIsCloud();
        paramsMap.put("isCloud", "否");
        paramsMap.put("yearPlanInvest",null);
        paramsMap.put("bigDataBureauName",null);

        // 生成pdf字节数组
        byte[] pdf = pdfUtils.generatePdf(htmlInputStream, paramsMap);

        // 转换成MultipartFile
        MultipartFile multipartFile = new MockMultipartFile("file", fileName + ".pdf", "application/pdf", pdf);

        // 上传OSS
        FileResultVO resultVO = fileService.upload(multipartFile, "default");

        // 将返回的文件ID保存到项目库中
        Project project = projectService.getById(44L);
        project.setPretrialFileId(resultVO.getId());

        try {
            if (null != htmlInputStream) {
                htmlInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void todo(){
        //测试 有多少个
        TaskQuery taskQuery = taskService.createTaskQuery();
        taskQuery.active()
                .taskCandidateOrAssigned(String.valueOf(2));
        List<Task> taskList = taskQuery.list();

        System.out.println(taskList.size());
    }

    public void ido(){
        String userId = "2";
        // 自定义sql查询所有已办的任务实例
        String nativeSql = "SELECT\n" +
                "\taht.*\n" +
                "FROM\n" +
                "\tACT_HI_TASKINST AS aht\n" +
                "LEFT JOIN ACT_HI_VARINST AS ahv ON\n" +
                "\tSUBSTRING(ahv.NAME_, 9) = aht.ID_\n" +
                "\tAND ahv.NAME_ LIKE 'approve_%'\n" +
                "WHERE\n" +
                "\taht.ASSIGNEE_ = '" + userId +
                "'AND ahv.NAME_ IS NOT NULL\n" +
                "\tOR  aht.DELETE_REASON_ = '" + ProcessConstant.Field.CANCEL + "'";
        NativeHistoricTaskInstanceQuery taskInstanceQuery =
                historyService.createNativeHistoricTaskInstanceQuery().sql(nativeSql);
        List<HistoricTaskInstance> taskInstances = taskInstanceQuery.list();

        System.out.println(taskInstances.size());
    }
}
