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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jyjc.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * ProjectName: amos-boot-biz
 * PackageName: com.yeejoin.amos.boot.module.jyjc.biz.service.impl
 *
 * @author yangyang
 * @version v1.0
 * @date 2023/12/15 15:46
 */
@Component
@Slf4j
public class WorkflowHelper {

    @Autowired
    private WorkflowFeignClient workflowFeignClient;

    /**
     * 获取工作流
     *
     *
     * @param instanceId instanceId
     * @return {@link  JSONObject}
     * @author yangyang
     * @throws
     * @date 2023/12/15 16:17
     */
    public JSONObject getTask(String instanceId) {
        AjaxResult ajaxResult = Workflow.taskClient.getTaskNoAuth(instanceId);
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");// 工作流ID
        FeignClientResult<JSONObject> nodeInfo = workflowFeignClient.getNodeInfotoken(RequestContext.getAppKey(), RequestContext.getProduct(), RequestContext.getToken(), taskId);
        dataObject.put("nodeInfo", nodeInfo.getResult());
        return dataObject;
    }

    public String getWorkflowStatus(JSONObject dataObject) {
        return !ValidationUtil.isEmpty(dataObject) && !ValidationUtil.isEmpty(dataObject.get("status")) ? String.valueOf(dataObject.get("status")) : "";
    }

    public String getWorkflowRoleGroups(JSONObject dataObject) {
        JSONArray executorArray = dataObject.getJSONObject("nodeInfo").getJSONArray("executor");
        if(!ValidationUtil.isEmpty(executorArray)) {
            return executorArray.stream().map(json -> Optional.ofNullable(((LinkedHashMap) json).get("groupId")).orElse("").toString()).collect(Collectors.joining(","));
        }
        return null;
    }

    public JSONObject rollBack(String workflowProstanceId) {
        return workflowFeignClient.rollBack(workflowProstanceId);
    }
}
