package com.sifang.modules.flowpath.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.flowable.dao.ProcessDefAuditStepDao;
import com.sifang.modules.flowable.entity.ProcessDefAuditStep;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.vo.TaskVo;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexStaticApplyService extends BaseService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ProcessDefAuditStepDao processDefAuditStepDao;

    @Autowired
    private TaskService taskService;

    public Map<String,Integer> staticApplyCount(User user){
        Map<String,Integer> resultMap=new HashMap<>();

        //获取用户角色和部门
        String roleIds=user.getRoleIds();    //用户角色
        String departmentId=user.getDepartmentId();  //用户的部门

        Map<String,List<TaskVo>> map=new HashMap<>();
       /* if(StringUtil.isNotBlank(roleIds)){
            List<String> roles= Arrays.asList(roleIds.split(","));
            List<TaskVo> list=getTaskList(roles, departmentId);
           if(list!=null && list.size()>0) map=list.stream().collect(Collectors.groupingBy(TaskVo::getFormKey));
        }*/
        List<TaskVo> list=getTaskList2(user.getId(), departmentId);
        if(list!=null && list.size()>0) map=list.stream().collect(Collectors.groupingBy(TaskVo::getFormKey));
        for(int i=1;i<=12;i++){
            String str= i>=10? i+"" :"0"+i;
            List<TaskVo> list1=map.get(str);
            if(list1==null || list1.size()==0){
               resultMap.put("apply"+str, 0);
            }else {
                resultMap.put("apply"+str, list1.size());
            }
        }
        return resultMap;
    }


    /**
     * 获取所有待办任务
     * @param rootIdS 角色id
     *               新建人同一部门/上级部门 、、、下，同一角色的任务
     *               启动项目时，保存了当前人部门
     */
    public List<TaskVo> getTaskList(List<String> rootIdS, String deparId) {
             List<TaskVo> tasks = new ArrayList<>();

            List<Task> list = taskService.createTaskQuery().taskCandidateGroupIn(rootIdS).list();
            getTaskList(list, tasks, deparId);
        return tasks;
    }

    public List<TaskVo> getTaskList2(String userId, String deparId) {
        List<TaskVo> tasks = new ArrayList<>();

        List<Task> list = taskService.createTaskQuery().taskAssignee(userId).list();
        getTaskList(list, tasks, deparId);
        return tasks;
    }

    public List<TaskVo> getTaskList(List<Task> list, List<TaskVo> tasks, String deparId) {
        list.forEach(task -> {
            if(TaskVo.TYPE_THREE.equals(task.getCategory())){
                TaskVo taskBo = new TaskVo();
                taskBo.setApplicationId(task.getTenantId());
                taskBo.setFormKey(task.getFormKey());
                tasks.add(taskBo);
            }else {
                //获取流程自定义参数
                Map<String, Object> map = runtimeService.getVariables(task.getProcessInstanceId());
                TaskVo taskBo = new TaskVo();
                taskBo.setApplicationId(map.get("applicationId").toString());
                taskBo.setFormKey(map.get("formId").toString());
                tasks.add(taskBo);
            }
/*
           //不用判断部门，那么可以不用下面的
            if(map.get("departmentId")==null){
                return;
            }
            String depId = map.get("departmentId").toString();//提交人部门
            logger.info(">>>>>>>>>>>>>>getTaskList  task : {} , map :{} ,time:{}",task,map,task.getCreateTime());

            String topDepts=FormUtils.getTopDepart(depId);
            if(StringUtil.isBlank(topDepts)){
                topDepts=deparId;
            }

            logger.info(">>>>>>>>>>>>>>getTaskList 提交人所有上级部门信息  task : {} ，当前登录人 deparId：{}",task,deparId);
            String taskKey = task.getTaskDefinitionKey();
            if (StringUtil.isNotBlank(taskKey)) {
                String stepId = taskKey.substring(14);
                logger.info(">>>>>>>>>>>>getTaskList 获取审批 时  表单字段 stepId :{} ,taskKey : {}",stepId,taskKey);
                ProcessDefAuditStep step = processDefAuditStepDao.get(stepId);
                String trans = step.getTransDepartment();
                if ("1".equals(trans)) {
                    //可以跨部门审批
                    TaskVo taskBo = new TaskVo();
                    taskBo.setApplicationId(map.get("applicationId").toString());
                    taskBo.setFormKey(map.get("formId").toString());

                    tasks.add(taskBo);
                } else if (StringUtil.isBlank(depId) || topDepts.contains(deparId) || depId.equals(deparId)) {//如果当前人员部门相同就可以查看、审批
                    TaskVo taskBo = new TaskVo();
                    taskBo.setApplicationId(map.get("applicationId").toString());
                    taskBo.setFormKey(map.get("formId").toString());
                    tasks.add(taskBo);
                }

            }*/

        });
        return tasks;
    }


}
