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.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 {


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


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


    /***
     * 执行
     *
     * */
    public ProcessTaskDTO complete(String taskId, TaskResultDTO data) {
        ProcessTaskDTO processTaskDTO;
        try {
            log.info("开始前请求工作流完成任务接口:/complete/standard/{taskId},请求参数：{},{}", taskId, JSONObject.toJSONString(data));
            processTaskDTO = FeignUtil.remoteCall(() -> Workflow.taskV2Client.completeByTaskFroStandard(taskId, data));
        } 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;
    }
}
