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.biz.feign.WorkFlowFeignService;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.workflow.Workflow;
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.List;
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 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 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);
            }
            workflowResultDtoList.add(workflowResultDto);
        });
        return workflowResultDtoList;
    }
}
