package ink.wgink.module.activiti.service.oa.impl;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.interfaces.department.IDepartmentBaseService;
import ink.wgink.interfaces.department.IDepartmentUserBaseService;
import ink.wgink.interfaces.user.IUserBaseService;
import ink.wgink.module.activiti.enums.oa.ProcessTaskStatusEnum;
import ink.wgink.module.activiti.enums.oa.TaskCommentTypeEnum;
import ink.wgink.module.activiti.pojo.bos.oa.TaskCommentBO;
import ink.wgink.module.activiti.pojo.bos.oa.TaskTransferCommentBO;
import ink.wgink.module.activiti.pojo.dtos.oa.OaHistoryTaskDTO;
import ink.wgink.module.activiti.pojo.dtos.oa.OaProcdefDTO;
import ink.wgink.module.activiti.pojo.dtos.oa.OaProcessLogDTO;
import ink.wgink.module.activiti.pojo.dtos.oa.OaTaskDTO;
import ink.wgink.module.activiti.service.oa.IOaFormReportService;
import ink.wgink.module.activiti.service.oa.IOaService;
import ink.wgink.module.form.pojo.dtos.design.FormDTO;
import ink.wgink.module.form.service.design.IFormDesignService;
import ink.wgink.module.form.service.design.IFormService;
import ink.wgink.pojo.dtos.department.DepartmentDTO;
import ink.wgink.pojo.dtos.department.DepartmentUserDTO;
import ink.wgink.pojo.dtos.user.UserDTO;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.ArrayListUtil;
import ink.wgink.util.date.DateUtil;
import ink.wgink.util.string.WStringUtil;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName: OaServiceImpl
 * @Description: oa管理
 * @Author: wanggeng
 * @Date: 2022/3/23 09:55
 * @Version: 1.0
 */
@Service
public class OaServiceImpl extends DefaultBaseService implements IOaService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private FormService formService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IFormService iFormService;
    @Autowired
    private IUserBaseService userBaseService;
    @Autowired
    private IDepartmentBaseService departmentBaseService;
    @Autowired
    private IDepartmentUserBaseService departmentUserBaseService;
    @Autowired
    private IOaFormReportService oaFormReportService;

    @Override
    public List<OaProcdefDTO> listProcdef() {
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> processDefinitions = processDefinitionQuery.list();
        return listOaProcdef(processDefinitions);
    }

    @Override
    public SuccessResultList<List<OaProcdefDTO>> listPageProcdef(int page, int rows) {
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> processDefinitions = processDefinitionQuery.latestVersion().listPage(page - 1, rows);
        List<OaProcdefDTO> oaProcdefDTOs = listOaProcdef(processDefinitions);
        return new SuccessResultList<>(oaProcdefDTOs, page, processDefinitionQuery.count());
    }

    /**
     * 流程定义列表
     *
     * @param processDefinitions
     * @return
     */
    private List<OaProcdefDTO> listOaProcdef(List<ProcessDefinition> processDefinitions) {
        if (processDefinitions.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> formIds = new ArrayList<>();
        List<OaProcdefDTO> oaProcdefDTOs = new ArrayList<>();
        processDefinitions.forEach(processDefinition -> {
            String formKey = formService.getStartFormData(processDefinition.getId()).getFormKey();
            OaProcdefDTO oaProcdefDTO = new OaProcdefDTO();
            oaProcdefDTO.setId(processDefinition.getId());
            oaProcdefDTO.setDeploymentId(processDefinition.getDeploymentId());
            oaProcdefDTO.setName(processDefinition.getName());
            oaProcdefDTO.setProcessDefinitionId(processDefinition.getId());
            oaProcdefDTO.setVersion(processDefinition.getVersion());
            oaProcdefDTO.setFormKey(formKey);
            oaProcdefDTOs.add(oaProcdefDTO);
            if (StringUtils.isBlank(formKey)) {
                return;
            }
            formIds.add(formKey);
        });
        List<FormDTO> formDTOs = iFormService.listByIds(formIds);
        oaProcdefDTOs.forEach(oaProcdefDTO -> {
            formDTOs.forEach(formDTO -> {
                if (!StringUtils.equals(oaProcdefDTO.getFormKey(), formDTO.getFormId())) {
                    return;
                }
                oaProcdefDTO.setFormCode(formDTO.getFormCode());
                oaProcdefDTO.setFormVersion(formDTO.getFormVersion());
            });
        });
        return oaProcdefDTOs;
    }

    @Override
    public List<OaTaskDTO> listTaskOfMine() {
        String userId = securityComponent.getCurrentUser().getUserId();
        return listTaskByUserId(userId);
    }

    @Override
    public List<OaTaskDTO> listTaskOfMine(String token) {
        String userId = getAppTokenUser(token).getId();
        return listTaskByUserId(userId);
    }

    @Override
    public List<OaTaskDTO> listTaskByUserId(String userId) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId);
        List<Task> tasks = taskQuery.includeProcessVariables().list();
        return listOaTask(tasks);
    }

    @Override
    public Long countTaskOfMine() {
        String userId = securityComponent.getCurrentUser().getUserId();
        return countTaskByUserId(userId);
    }

    @Override
    public Long countTaskOfMine(String token) {
        String userId = getAppTokenUser(token).getId();
        return countTaskByUserId(userId);
    }

    @Override
    public Long countTaskByUserId(String userId) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId);
        return taskQuery.count();
    }

    @Override
    public SuccessResultList<List<OaTaskDTO>> listPageTaskOfMine(int page, int rows) {
        String userId = securityComponent.getCurrentUser().getUserId();
        return listPageTaskByUserId(userId, page, rows);
    }

    @Override
    public SuccessResultList<List<OaTaskDTO>> listPageTaskOfMine(String token, int page, int rows) {
        String userId = getAppTokenUser(token).getId();
        return listPageTaskByUserId(userId, page, rows);
    }

    @Override
    public SuccessResultList<List<OaTaskDTO>> listPageTaskByUserId(String userId, int page, int rows) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId);
        List<Task> tasks = taskQuery.includeProcessVariables().orderByTaskCreateTime().desc().listPage(page - 1, rows);
        List<OaTaskDTO> oaTaskDTOs = listOaTask(tasks);
        return new SuccessResultList<>(oaTaskDTOs, page, taskQuery.count());
    }

    /**
     * oa任务列表
     *
     * @param tasks
     * @return
     */
    private List<OaTaskDTO> listOaTask(List<Task> tasks) {
        List<OaTaskDTO> oaTaskDTOs = new ArrayList<>();
        // 流程实例列表
        Set<String> processInstanceIdSet = new HashSet<>();
        // 发起人列表
        Set<String> startUserIdSet = new HashSet<>();

        tasks.forEach(task -> {
            OaTaskDTO oaTaskDTO = new OaTaskDTO();
            oaTaskDTOs.add(oaTaskDTO);

            processInstanceIdSet.add(task.getProcessInstanceId());

            oaTaskDTO.setTaskId(task.getId());
            oaTaskDTO.setTaskName(task.getName());
            oaTaskDTO.setTaskDescription(task.getDescription());
            oaTaskDTO.setOwner(task.getOwner());
            oaTaskDTO.setTaskDefinitionKey(task.getTaskDefinitionKey());
            oaTaskDTO.setProcessDefinitionId(task.getProcessDefinitionId());
            oaTaskDTO.setProcessInstanceId(task.getProcessInstanceId());
            oaTaskDTO.setIsNeedClaim(StringUtils.isBlank(task.getAssignee()) ? 1 : 0);
            oaTaskDTO.setCreateTime(DateUtil.getDateTime(task.getCreateTime()));
            Map<String, Object> variables = task.getProcessVariables();
            if (variables.isEmpty()) {
                return;
            }
            String formCode = (String) variables.get(IOaFormReportService.KEY_FORM_CODE);
            Integer formVersion = (Integer) variables.get(IOaFormReportService.KEY_FORM_VERSION);
            String reportUid = (String) variables.get(IOaFormReportService.KEY_REPORT_UID);
            oaTaskDTO.setFormCode(formCode);
            oaTaskDTO.setFormVersion(formVersion);
            oaTaskDTO.setReportUid(reportUid);

            String mainTitle = getMainTitle(formCode, formVersion, reportUid);
            if (StringUtils.isBlank(mainTitle)) {
                oaTaskDTO.setMainTitle("新任务需要处理");
            } else {
                oaTaskDTO.setMainTitle(mainTitle);
            }
        });

        setProcessNameAndStartUserId(oaTaskDTOs, processInstanceIdSet, startUserIdSet);
        setStartUser(oaTaskDTOs, startUserIdSet);
        return oaTaskDTOs;
    }

    @Override
    public List<OaHistoryTaskDTO> listHistoryTaskOfMine() {
        String userId = securityComponent.getCurrentUser().getUserId();
        return listHistoryTaskByUserId(userId);
    }

    @Override
    public List<OaHistoryTaskDTO> listHistoryTaskOfMine(String token) {
        String userId = getAppTokenUser(token).getId();
        return listHistoryTaskByUserId(userId);
    }

    @Override
    public List<OaHistoryTaskDTO> listHistoryTaskByUserId(String userId) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId);
        List<HistoricTaskInstance> historicTaskInstances = historicTaskInstanceQuery.includeProcessVariables().finished().list();
        return listOaHistoryTask(historicTaskInstances);
    }

    @Override
    public SuccessResultList<List<OaHistoryTaskDTO>> listPageHistoryTaskOfMine(int page, int rows) {
        String userId = securityComponent.getCurrentUser().getUserId();
        return listPageHistoryTaskByUserId(userId, page, rows);
    }

    @Override
    public SuccessResultList<List<OaHistoryTaskDTO>> listPageHistoryTaskOfMine(String token, int page, int rows) {
        String userId = getAppTokenUser(token).getId();
        return listPageHistoryTaskByUserId(userId, page, rows);
    }

    @Override
    public SuccessResultList<List<OaHistoryTaskDTO>> listPageHistoryTaskByUserId(String userId, int page, int rows) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId);
        List<HistoricTaskInstance> historicTaskInstances = historicTaskInstanceQuery.includeProcessVariables().finished().orderByHistoricTaskInstanceEndTime().desc().listPage(page - 1, rows);
        List<OaHistoryTaskDTO> oaHistoryTaskDTOs = listOaHistoryTask(historicTaskInstances);
        return new SuccessResultList<>(oaHistoryTaskDTOs, page, historicTaskInstanceQuery.count());
    }

    @Override
    public List<OaProcessLogDTO> listProcessLog(String processInstanceId) {
        List<OaProcessLogDTO> oaProcessLogDTOs = new ArrayList<>();
        Set<String> userIdSet = new HashSet<>();
        // 批注列表
        List<Comment> processInstanceComments = taskService.getProcessInstanceComments(processInstanceId);
        // 已办
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().includeTaskLocalVariables().processInstanceId(processInstanceId).finished().orderByHistoricTaskInstanceEndTime().asc().list();
        historicTaskInstances.forEach(historicTaskInstance -> {
            String userIds = historicTaskInstance.getAssignee();
            userIdSet.add(userIds);

            OaProcessLogDTO oaProcessLogDTO = new OaProcessLogDTO();
            oaProcessLogDTO.setTaskId(historicTaskInstance.getId());
            oaProcessLogDTO.setTaskName(historicTaskInstance.getName());
            oaProcessLogDTO.setTaskStatus(ProcessTaskStatusEnum.ALREADY_DONE.getValue());
            oaProcessLogDTO.setUserIds(userIds);
            oaProcessLogDTO.setUserNames(userIds);
            oaProcessLogDTO.setStartTime(DateUtil.getDateTime(historicTaskInstance.getCreateTime()));
            oaProcessLogDTO.setEndTime(DateUtil.getDateTime(historicTaskInstance.getEndTime()));
            oaProcessLogDTO.setUsedTime(DateUtil.getUsedTime(historicTaskInstance.getDurationInMillis()));

            setTaskTransferComment(processInstanceComments, historicTaskInstance.getId(), oaProcessLogDTO);
            setTaskComment(processInstanceComments, historicTaskInstance.getId(), oaProcessLogDTO);
            oaProcessLogDTOs.add(oaProcessLogDTO);
        });
        // 待办
        List<Task> taskList = taskService.createTaskQuery().includeTaskLocalVariables().processInstanceId(processInstanceId).orderByTaskCreateTime().asc().list();
        taskList.forEach(task -> {
            List<String> userIds = listUserByTaskId(task.getId());
            userIdSet.addAll(userIds);

            OaProcessLogDTO oaProcessLogDTO = new OaProcessLogDTO();
            oaProcessLogDTO.setTaskId(task.getId());
            oaProcessLogDTO.setTaskName(task.getName());
            oaProcessLogDTO.setTaskStatus(ProcessTaskStatusEnum.NEED_TO_BE_DEALT_WITH.getValue());
            String userIdString = WStringUtil.listToStr(userIds, ",");
            oaProcessLogDTO.setUserIds(userIdString);
            oaProcessLogDTO.setUserNames(userIdString);
            oaProcessLogDTO.setStartTime(DateUtil.getDateTime(task.getCreateTime()));

            setTaskTransferComment(processInstanceComments, task.getId(), oaProcessLogDTO);
            setTaskComment(processInstanceComments, task.getId(), oaProcessLogDTO);
            oaProcessLogDTOs.add(oaProcessLogDTO);
        });
        // 查询用户
        List<UserDTO> userDTOs = userBaseService.listByUserIds(userIdSet.stream().collect(Collectors.toList()));
        oaProcessLogDTOs.forEach(oaProcessLogDTO -> {
            userDTOs.forEach(userDTO -> {
                if (StringUtils.contains(oaProcessLogDTO.getUserNames(), userDTO.getUserId())) {
                    oaProcessLogDTO.setUserNames(oaProcessLogDTO.getUserNames().replaceAll(userDTO.getUserId(), userDTO.getUserName()));
                }
            });
        });
        return oaProcessLogDTOs;
    }

    /**
     * 转交批注单独处理
     *
     * @param processInstanceComments
     * @param taskId
     * @param oaProcessLogDTO
     */
    private void setTaskTransferComment(List<Comment> processInstanceComments, String taskId, OaProcessLogDTO oaProcessLogDTO) {
        for (Comment comment : processInstanceComments) {
            if (!StringUtils.equals(comment.getTaskId(), taskId)) {
                continue;
            }
            if (!StringUtils.equals(TaskCommentTypeEnum.TRANSFER.getValue(), comment.getType())) {
                continue;
            }
            List<TaskTransferCommentBO> transferComments = oaProcessLogDTO.getTransferComments();
            transferComments.add(JSONObject.parseObject(comment.getFullMessage(), TaskTransferCommentBO.class));
            oaProcessLogDTO.setTransferComments(transferComments);
        }
    }

    /**
     * 非转交批注因不存在持续添加，取当前即可
     *
     * @param processInstanceComments
     * @param taskId
     * @param oaProcessLogDTO
     */
    private void setTaskComment(List<Comment> processInstanceComments, String taskId, OaProcessLogDTO oaProcessLogDTO) {
        for (Comment comment : processInstanceComments) {
            if (!StringUtils.equals(comment.getTaskId(), taskId)) {
                continue;
            }
            oaProcessLogDTO.setComment(JSONObject.parseObject(comment.getFullMessage(), TaskCommentBO.class));
            break;
        }
    }

    /**
     * 用户列表
     *
     * @param taskId 任务ID
     * @return
     */
    private List<String> listUserByTaskId(String taskId) {
        List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(taskId);
        return identityLinksForTask.stream().map(IdentityLink -> IdentityLink.getUserId()).collect(Collectors.toList());
    }

    private List<OaHistoryTaskDTO> listOaHistoryTask(List<HistoricTaskInstance> historicTaskInstances) {
        List<OaHistoryTaskDTO> oaHistoryTaskDTOs = new ArrayList<>();

        // 流程实例列表
        Set<String> processInstanceIdSet = new HashSet<>();
        // 发起人列表
        Set<String> startUserIdSet = new HashSet<>();

        historicTaskInstances.forEach(historicTaskInstance -> {
            OaHistoryTaskDTO oaHistoryTaskDTO = new OaHistoryTaskDTO();
            oaHistoryTaskDTOs.add(oaHistoryTaskDTO);

            processInstanceIdSet.add(historicTaskInstance.getProcessInstanceId());

            oaHistoryTaskDTO.setTaskId(historicTaskInstance.getId());
            oaHistoryTaskDTO.setTaskName(historicTaskInstance.getName());
            oaHistoryTaskDTO.setProcessInstanceId(historicTaskInstance.getProcessInstanceId());
            oaHistoryTaskDTO.setStartTime(DateUtil.getDateTime(historicTaskInstance.getStartTime()));
            oaHistoryTaskDTO.setEndTime(DateUtil.getDateTime(historicTaskInstance.getEndTime()));

            Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
            String formCode = (String) processVariables.get(IOaFormReportService.KEY_FORM_CODE);
            Integer formVersion = (Integer) processVariables.get(IOaFormReportService.KEY_FORM_VERSION);
            String reportUid = (String) processVariables.get(IOaFormReportService.KEY_REPORT_UID);
            String mainTitle = getMainTitle(formCode, formVersion, reportUid);
            oaHistoryTaskDTO.setFormCode(formCode);
            oaHistoryTaskDTO.setFormVersion(formVersion);
            oaHistoryTaskDTO.setReportUid(reportUid);
            if (StringUtils.isBlank(mainTitle)) {
                oaHistoryTaskDTO.setMainTitle("新任务需要处理");
            } else {
                oaHistoryTaskDTO.setMainTitle(mainTitle);
            }
        });

        // 流程定义列表
        setHistoryProcessNameAndStartUserId(oaHistoryTaskDTOs, processInstanceIdSet, startUserIdSet);
        setHistoryStartUser(oaHistoryTaskDTOs, startUserIdSet);
        return oaHistoryTaskDTOs;
    }

    /**
     * 设置流程名称和发起人
     *
     * @param oaTaskDTOs
     * @param processInstanceIds
     * @param startUserIdSet
     */
    private void setProcessNameAndStartUserId(List<OaTaskDTO> oaTaskDTOs, Set<String> processInstanceIdSet, Set<String> startUserIdSet) {
        if (oaTaskDTOs.isEmpty()) {
            return;
        }
        if (processInstanceIdSet.isEmpty()) {
            return;
        }
        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdSet).list();
        oaTaskDTOs.forEach(oaTaskDTO -> {
            processInstances.forEach(processInstance -> {
                if (!StringUtils.equals(oaTaskDTO.getProcessInstanceId(), processInstance.getProcessInstanceId())) {
                    return;
                }
                startUserIdSet.add(processInstance.getStartUserId());
                oaTaskDTO.setProcessName(processInstance.getProcessDefinitionName());
                oaTaskDTO.setProcessStartTime(DateUtil.getDateTime(processInstance.getStartTime()));
                oaTaskDTO.setStartUserId(processInstance.getStartUserId());
            });
        });
    }

    /**
     * 设置发起人
     *
     * @param oaTaskDTOs
     * @param startUserIdSet
     */
    private void setStartUser(List<OaTaskDTO> oaTaskDTOs, Set<String> startUserIdSet) {
        if (oaTaskDTOs.isEmpty()) {
            return;
        }
        if (startUserIdSet.isEmpty()) {
            return;
        }
        List<UserDTO> userDTOs = userBaseService.listByUserIds(startUserIdSet.stream().collect(Collectors.toList()));
        if (userDTOs.isEmpty()) {
            return;
        }
        List<String> userIds = ArrayListUtil.listBeanStringIdValue(userDTOs, "userId", UserDTO.class);
        List<DepartmentUserDTO> departmentUserDTOs = departmentUserBaseService.listByUserIds(userIds);
        List<String> departmentIds = ArrayListUtil.listBeanStringIdValue(departmentUserDTOs, "departmentId", DepartmentUserDTO.class);
        List<DepartmentDTO> departmentDTOs = departmentBaseService.listByIds(departmentIds);
        for (OaTaskDTO oaTaskDTO : oaTaskDTOs) {
            for (UserDTO userDTO : userDTOs) {
                if (!StringUtils.equals(oaTaskDTO.getStartUserId(), userDTO.getUserId())) {
                    continue;
                }
                oaTaskDTO.setStartUserName(userDTO.getUserName());
                break;
            }
            for (DepartmentUserDTO departmentUserDTO : departmentUserDTOs) {
                if (!StringUtils.equals(oaTaskDTO.getStartUserId(), departmentUserDTO.getUserId())) {
                    continue;
                }
                for (DepartmentDTO departmentDTO : departmentDTOs) {
                    if (!StringUtils.equals(departmentUserDTO.getDepartmentId(), departmentDTO.getDepartmentId())) {
                        continue;
                    }
                    String startUserDepartmentIds = oaTaskDTO.getStartUserDepartmentIds();
                    String startUserDepartmentNames = oaTaskDTO.getStartUserDepartmentNames();
                    if (!StringUtils.isBlank(startUserDepartmentIds)) {
                        startUserDepartmentIds += ",";
                        startUserDepartmentNames += ",";
                    }
                    startUserDepartmentIds += departmentDTO.getDepartmentId();
                    startUserDepartmentNames += departmentDTO.getDepartmentName();
                    oaTaskDTO.setStartUserDepartmentIds(startUserDepartmentIds);
                    oaTaskDTO.setStartUserDepartmentNames(startUserDepartmentNames);
                    break;
                }
                break;
            }
        }
    }

    /**
     * 设置流程名称和发起人
     *
     * @param oaHistoryTaskDTOs
     * @param processInstanceIdSet
     * @param startUserIdSet
     */
    private void setHistoryProcessNameAndStartUserId(List<OaHistoryTaskDTO> oaHistoryTaskDTOs, Set<String> processInstanceIdSet, Set<String> startUserIdSet) {
        if (oaHistoryTaskDTOs.isEmpty()) {
            return;
        }
        if (processInstanceIdSet.isEmpty()) {
            return;
        }

        List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery().processInstanceIds(processInstanceIdSet).list();
        oaHistoryTaskDTOs.forEach(oaHistoryTaskDTO -> {
            historicProcessInstances.forEach(historicProcessInstance -> {
                if (!StringUtils.equals(oaHistoryTaskDTO.getProcessInstanceId(), historicProcessInstance.getId())) {
                    return;
                }
                startUserIdSet.add(historicProcessInstance.getStartUserId());
                oaHistoryTaskDTO.setProcessName(historicProcessInstance.getProcessDefinitionName());
                oaHistoryTaskDTO.setProcessStartTime(DateUtil.getDateTime(historicProcessInstance.getStartTime()));
                oaHistoryTaskDTO.setProcessEndTime(historicProcessInstance.getEndTime() == null ? "" : DateUtil.getDateTime(historicProcessInstance.getEndTime()));
                historicProcessInstance.getEndTime();
                oaHistoryTaskDTO.setStartUserId(historicProcessInstance.getStartUserId());
            });
        });
    }

    /**
     * 设置发起人
     *
     * @param oaHistoryTaskDTOs
     * @param startUserIdSet
     */
    private void setHistoryStartUser(List<OaHistoryTaskDTO> oaHistoryTaskDTOs, Set<String> startUserIdSet) {
        if (oaHistoryTaskDTOs.isEmpty()) {
            return;
        }
        if (startUserIdSet.isEmpty()) {
            return;
        }
        List<UserDTO> userDTOs = userBaseService.listByUserIds(startUserIdSet.stream().collect(Collectors.toList()));
        if (userDTOs.isEmpty()) {
            return;
        }
        List<String> userIds = ArrayListUtil.listBeanStringIdValue(userDTOs, "userId", UserDTO.class);
        List<DepartmentUserDTO> departmentUserDTOs = departmentUserBaseService.listByUserIds(userIds);
        List<String> departmentIds = ArrayListUtil.listBeanStringIdValue(departmentUserDTOs, "departmentId", DepartmentUserDTO.class);
        List<DepartmentDTO> departmentDTOs = departmentBaseService.listByIds(departmentIds);
        for (OaHistoryTaskDTO oaHistoryTaskDTO : oaHistoryTaskDTOs) {
            for (UserDTO userDTO : userDTOs) {
                if (!StringUtils.equals(oaHistoryTaskDTO.getStartUserId(), userDTO.getUserId())) {
                    continue;
                }
                oaHistoryTaskDTO.setStartUserName(userDTO.getUserName());
                break;
            }
            for (DepartmentUserDTO departmentUserDTO : departmentUserDTOs) {
                if (!StringUtils.equals(oaHistoryTaskDTO.getStartUserId(), departmentUserDTO.getUserId())) {
                    continue;
                }
                for (DepartmentDTO departmentDTO : departmentDTOs) {
                    if (!StringUtils.equals(departmentUserDTO.getDepartmentId(), departmentDTO.getDepartmentId())) {
                        continue;
                    }
                    String startUserDepartmentIds = oaHistoryTaskDTO.getStartUserDepartmentIds();
                    String startUserDepartmentNames = oaHistoryTaskDTO.getStartUserDepartmentNames();
                    if (!StringUtils.isBlank(startUserDepartmentIds)) {
                        startUserDepartmentIds += ",";
                        startUserDepartmentNames += ",";
                    }
                    startUserDepartmentIds += departmentDTO.getDepartmentId();
                    startUserDepartmentNames += departmentDTO.getDepartmentName();
                    oaHistoryTaskDTO.setStartUserDepartmentIds(startUserDepartmentIds);
                    oaHistoryTaskDTO.setStartUserDepartmentNames(startUserDepartmentNames);
                    break;
                }
                break;
            }
        }
    }

    /**
     * 获取表单上报主标题
     *
     * @param formCode
     * @param formVersion
     * @param uid
     * @return
     */
    private String getMainTitle(String formCode, Integer formVersion, String uid) {
        Map<String, Object> reportFormMap = oaFormReportService.getPO(formCode, formVersion, uid);
        if (reportFormMap == null) {
            return null;
        }
        Object mainTitleObj = reportFormMap.get(IFormDesignService.FIELD_MAIN_TITLE);
        if (mainTitleObj == null) {
            return null;
        }
        String mainTitle = (String) mainTitleObj;
        if (StringUtils.isBlank(mainTitle)) {
            return null;
        }
        return mainTitle;
    }

}
