package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.hygf.api.dto.WorkflowResultDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.BasicGridAcceptance;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkFlowFeignService;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.workflow.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
@Slf4j
public class WorkFlowService {
    @Autowired
    private WorkFlowFeignService workFlowFeignService;

    /***
     * 开启并执行一步 支持批量
     *
     * */
    public List<ProcessTaskDTO> startBatch(ActWorkflowBatchDTO params) {
        List<ProcessTaskDTO> processTasks;
        try {
            log.info("开始前请求工作流启动接口:/start/batch,请求参数：{}", JSONObject.toJSONString(params));
            processTasks = workFlowFeignService.startForBatch(params).getResult();
        } catch (Exception e) {
            log.error("调用工作流批量启动失败", e);
            throw new RuntimeException("调用工作流批量启动失败");
        }
        return processTasks;
    }

    /***
     * 开启并执行一步 支持批量
     *
     * */
    public List<ProcessTaskDTO> startBatchNew(String appKey, String product, String token, ActWorkflowBatchDTO params) {
        List<ProcessTaskDTO> processTasks;
        try {
            log.info("开始前请求工作流启动接口:/start/batch,appKey:{},product:{},token:{}请求请求参数：{}", appKey, product, token, JSONObject.toJSONString(params));
            processTasks = workFlowFeignService.startForBatchNew(appKey, product, token, params).getResult();
        } catch (Exception e) {
            log.error("调用工作流批量启动失败", e);
            throw new RuntimeException("调用工作流批量启动失败");
        }
        return processTasks;
    }

    public ProcessInstanceDTO stopProcess(String processInstanceId) {
        ProcessInstanceDTO processInstanceDTO ;
        try {
            log.info("开始前请求工作流停止接口:stopProcess,请求参数：{}", processInstanceId);
            processInstanceDTO = workFlowFeignService.stopProcess(processInstanceId,null).getResult();
        } catch (Exception e) {
            log.error("调用工作流批量停止失败", e);
            throw new RuntimeException("调用工作流批量停止失败");
        }
        return processInstanceDTO;
    }


    public ProcessTaskDTO standard(BasicGridAcceptance basicGridAcceptance, TaskResultDTO taskResultDTO, String userid) {
        ProcessTaskDTO processTaskDTO;
        if (taskResultDTO.getResult() != null) {
            taskResultDTO.setResultCode("approvalStatus");
            processTaskDTO = complete(taskResultDTO.getTaskId(), taskResultDTO);
        } else {
            processTaskDTO = complete(taskResultDTO.getTaskId(), taskResultDTO);
        }
        this.getBasicGridAcceptanceone(basicGridAcceptance, processTaskDTO, userid);
        return processTaskDTO;
    }

    /***
     * 执行
     *
     * */
    public ProcessTaskDTO rollBackTask(String processInstanceId) {
        ProcessTaskDTO processTaskDTO;
        try {
            log.info("工作流撤回任务接口:/rollBackTask},请求参数：{}", processInstanceId);
            processTaskDTO = workFlowFeignService.rollBackTask(processInstanceId).getResult();
        } catch (Exception e) {
            log.error("调用工作流撤回任务接口失败", e);
            throw new RuntimeException("调用工作流撤回任务接口失败");
        }
        return processTaskDTO;
    }


    /***
     * 执行
     *
     * */
    public ProcessTaskDTO complete(String taskId, TaskResultDTO data) {
        ProcessTaskDTO processTaskDTO;
        try {
            log.info("开始前请求工作流完成任务接口:/complete/standard/{taskId},请求参数：{},{}", taskId, JSONObject.toJSONString(data));
            processTaskDTO = workFlowFeignService.completeByTaskFroStandard(taskId, data).getResult();
        } catch (Exception e) {
            log.error("调用工作流完成任务接口失败", e);
            throw new RuntimeException("调用工作流完成任务接口失败");
        }
        return processTaskDTO;
    }


    public List<WorkflowResultDto> buildWorkFlowInfo(List<ProcessTaskDTO> processTaskDTOS) {
        List<WorkflowResultDto> workflowResultDtoList = new ArrayList<>();
        processTaskDTOS.forEach(item -> {
            WorkflowResultDto workflowResultDto = new WorkflowResultDto();
            if (null != item.getProcessInstance()){
                workflowResultDto.setInstanceId(item.getProcessInstance().getId());
            }
         //   workflowResultDto.setNextExecutorIds(String.join(",", item.getCandidateGroups()));
            if (!CollectionUtils.isEmpty(item.getNextTask())) {
                ActTaskDTO actTaskDTO = item.getNextTask().get(0);
                workflowResultDto.setTaskName(actTaskDTO.getName());
                workflowResultDto.setNextTaskId(actTaskDTO.getId());
                workflowResultDto.setNextNodeKey(actTaskDTO.getKey()); // 工作流字段还未添加
                workflowResultDto.setNextNodeName(actTaskDTO.getName());
                List<String> nextGroups = item.getNextCandidateGroups().get(actTaskDTO.getId());
                String join = String.join(",", nextGroups);
                workflowResultDto.setNextExecutorIds(join);
                List<String> nextUserIds = item.getNextTaskExecutor().get(actTaskDTO.getId()).stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
                String nextUserIdsString = String.join(",", nextUserIds);
                workflowResultDto.setNextExecuteUserIds(nextUserIdsString);
            }
            if (!Objects.isNull(item.getStartUser())) {
                workflowResultDto.setStartDate(new Date());
                workflowResultDto.setStartUserId(item.getStartUser().getUserId());
                workflowResultDto.setStartUser(item.getStartUser().getUserName());
                List<CompanyModel> companys = item.getStartUser().getCompanys();
                if (!CollectionUtils.isEmpty(companys) && companys.size() >= 1) {
                    workflowResultDto.setStartUserCompanyName(companys.get(0).getCompanyName());
                }
            }
            workflowResultDtoList.add(workflowResultDto);
        });
        return workflowResultDtoList;
    }

    public List<WorkflowResultDto> buildWorkFlowInfos(List<ProcessTaskDTO> processTaskDTOS) {
        List<WorkflowResultDto> workflowResultDtoList = new ArrayList<>();
        processTaskDTOS.forEach(item -> {
            if (null != item.getProcessInstance()){
            }
            //   workflowResultDto.setNextExecutorIds(String.join(",", item.getCandidateGroups()));
            if (!CollectionUtils.isEmpty(item.getNextTask())) {

                item.getNextTask().forEach(actTaskDTO->{
                    WorkflowResultDto workflowResultDto = new WorkflowResultDto();
                    workflowResultDto.setInstanceId(actTaskDTO.getProcessInstanceId());
                    workflowResultDto.setTaskName(actTaskDTO.getName());
                    workflowResultDto.setNextTaskId(actTaskDTO.getId());
                    workflowResultDto.setNextNodeKey(actTaskDTO.getKey()); // 工作流字段还未添加
                    workflowResultDto.setNextNodeName(actTaskDTO.getName());
                    List<String> nextGroups = item.getNextCandidateGroups().get(actTaskDTO.getId());
                    String join = String.join(",", nextGroups);
                    workflowResultDto.setNextExecutorIds(join);
                    List<String> nextUserIds = item.getNextTaskExecutor().get(actTaskDTO.getId()).stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
                    String nextUserIdsString = String.join(",", nextUserIds);
                    workflowResultDto.setNextExecuteUserIds(nextUserIdsString);
                    workflowResultDtoList.add(workflowResultDto);
                });

            }

        });
        return workflowResultDtoList;
    }

    public BasicGridAcceptance getBasicGridAcceptance(BasicGridAcceptance basicGridAcceptance, List<ProcessTaskDTO> processTaskDTOList, String userid) {
        ProcessTaskDTO listco = processTaskDTOList.isEmpty() ? null : processTaskDTOList.get(0);
        if (listco != null) {
            //	当前节点执行任务id
            basicGridAcceptance.setPromoter(userid);
            //流程实例
            basicGridAcceptance.setInstanceId(listco.getProcessInstance().getId());
            //	流程下一节点id
            if (listco.getNextTask() != null && !listco.getNextTask().isEmpty()) {
                basicGridAcceptance.setNextTaskId(listco.getNextTask().get(0).getId());
                //下个节点名称
                basicGridAcceptance.setNextNodeName(listco.getNextTask().get(0).getName());
                //下个节点key
                basicGridAcceptance.setNextNodeKey(listco.getNextTask().get(0).getKey());
            }
            ///	下一个节点角色权限
            if (listco.getNextCandidateGroups() != null) {
                List<String> ld = listco.getNextCandidateGroups().get(basicGridAcceptance.getNextTaskId());
                StringBuffer sbf = new StringBuffer();
                for (int i = 0; i <= ld.size() - 1; i++) {
                    if (i < ld.size() - 1) {
                        sbf.append(ld.get(i) + ",");
                    } else {
                        sbf.append(ld.get(i));
                    }
                }

                basicGridAcceptance.setNextExecutorIds(sbf.toString());
            }
            //下一节点可执行人逗号分割	0	0
            if (listco.getNextTaskExecutor() != null) {

                List<AgencyUserModel> li = listco.getNextTaskExecutor().get(basicGridAcceptance.getNextTaskId());
                if (li != null && !li.isEmpty()) {

                    StringBuffer sbf = new StringBuffer();
                    for (int i = 0; i <= li.size() - 1; i++) {
                        if (i < li.size() - 1) {
                            sbf.append(li.get(i).getUserId() + ",");
                        } else {
                            sbf.append(li.get(i).getUserId());
                        }
                    }
                    basicGridAcceptance.setNextExecuteUserIds(sbf.toString());
                }
            }
            //工作流发起人id
            basicGridAcceptance.setCreateUserId(listco.getStartUser().getUserId());

        } else {
            throw new RuntimeException("工作流异常");
        }
        return basicGridAcceptance;
    }

    public void getBasicGridAcceptanceone(BasicGridAcceptance basicGridAcceptance, ProcessTaskDTO processTaskDTO, String userid) {
        if (processTaskDTO != null) {
            //	当前节点执行任务id
            basicGridAcceptance.setPromoter(userid);
            //	流程下一节点id
            if (processTaskDTO.getNextTask() != null && !processTaskDTO.getNextTask().isEmpty()) {
                basicGridAcceptance.setNextTaskId(processTaskDTO.getNextTask().get(0).getId());
                //下个节点名称
                basicGridAcceptance.setNextNodeName(processTaskDTO.getNextTask().get(0).getName());
                //下个节点key
                basicGridAcceptance.setNextNodeKey(processTaskDTO.getNextTask().get(0).getKey());
            } else {
                return;
            }
            ///	下一个节点角色权限
            if (processTaskDTO.getNextCandidateGroups() != null) {
                List<String> ld = processTaskDTO.getNextCandidateGroups().get(basicGridAcceptance.getNextTaskId());
                StringBuffer sbf = new StringBuffer();
                for (int i = 0; i <= ld.size() - 1; i++) {
                    if (i < ld.size() - 1) {
                        sbf.append(ld.get(i) + ",");
                    } else {
                        sbf.append(ld.get(i));
                    }
                }

                basicGridAcceptance.setNextExecutorIds(sbf.toString());
            }

            //下一节点可执行人逗号分割	0	0
            if (processTaskDTO.getNextTaskExecutor() != null) {

                List<AgencyUserModel> li = processTaskDTO.getNextTaskExecutor().get(basicGridAcceptance.getNextTaskId());
                if (li != null && !li.isEmpty()) {

                    StringBuffer sbf = new StringBuffer();
                    for (int i = 0; i <= li.size() - 1; i++) {
                        if (i < li.size() - 1) {
                            sbf.append(li.get(i).getUserId() + ",");
                        } else {
                            sbf.append(li.get(i).getUserId());
                        }
                    }
                    basicGridAcceptance.setNextExecuteUserIds(sbf.toString());
                }
            }
        }
    }
}
