package com.ruoyi.web.job;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysUserService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@EnableScheduling
@Component
public class ToDoNumberJob {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 每五分钟更新一次待办事项数量
     *
     */
    @Scheduled(fixedDelay = 120000,initialDelay = 10000)
    public void updateToDoNumber(){
        logger.info("开始更新待办事项数量");
        //查询所有进行中的任务
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = engine.getRuntimeService();
        List<ProcessInstance> instances = runtimeService
                .createProcessInstanceQuery()
                .active()
                .list();
        //声明map记录用户和对应的代办数量
        Map<String,Integer> map = new HashMap<>();
        for (ProcessInstance instance : instances) {
           /* TaskQuery query = engine.getTaskService().createTaskQuery()
                    .processInstanceId(instance.getId());
            //获取对应的待处理用户记录代办数量+1
            String assignee = query.singleResult().getAssignee();*/
            List<Task> taskList = engine.getTaskService().createTaskQuery()
                    .processInstanceId(instance.getId())
                    .list();
            // 遍历所有任务，获取每个处理人
            for (Task task : taskList) {
                String assignee = task.getAssignee();
                // 处理每个处理人...
                if(assignee!=null && !"".equals(assignee)){
                    //根据用户id获取用户对象
                    SysUser userInfo= sysUserService.selectUserById(Long.parseLong(assignee));
                    if (map.containsKey(userInfo.getUserName())){
                        map.put(userInfo.getUserName(),map.get(userInfo.getUserName())+1);
                    }else {
                        map.put(userInfo.getUserName(),1);
                    }
                }
            }
        }
        //先清空redis中待办数量
        redisCache.deleteObject("toDoNumber");
        //将对应代办数量更新到redis当中
        if(map.size()>0){
            redisCache.setCacheObject("toDoNumber", map);
        }
    }
}
