package com.yeejoin.amos.patrol.common.remote;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.util.HttpUtil;
import com.yeejoin.amos.patrol.common.enums.WorkFlowUriEnum;
import com.yeejoin.amos.patrol.common.enums.YesOrNoEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import java.util.Map;

@Service("remoteWorkFlowService")
public class RemoteWorkFlowService {

    private final Logger logger = LoggerFactory.getLogger(RemoteWorkFlowService.class);

    @Value("${params.work.flow.address}")
    private String address;

    private static final String success = "SUCCESS";

    private static final String appKey = "8b193f7cb22c842b5a56e866c2e20dbf";

    @Value("${params.work.flow.processDefinitionKey}")
    private String processDefinitionKey;

    private String buildUrl(String address, WorkFlowUriEnum workFlowUriEnum, Map<String, String> map) {
        String uri = workFlowUriEnum.getUri();
        String params = workFlowUriEnum.getParams();
        if (!StringUtils.isEmpty(params) && map != null) {
            String[] paramsArr = params.split(",");
            for (String param : paramsArr) {
                uri = uri.replace("{" + param + "}", map.get(param));
            }
        }
        return address + uri;
    }

    private JSONObject handleResult(String resultStr) {
        if (resultStr == null) {
            return null;
        }
        JSONObject json = JSON.parseObject(resultStr);
        if ("200".equals(json.getString("code"))) {
            return json;
        }
        return null;
    }

    public JSONObject start(String businessKey, String processDefinitionKey) {
        String url = buildUrl(address, WorkFlowUriEnum.启动流程, null);
        JSONObject body = new JSONObject();
        body.put("businessKey", businessKey);
        body.put("processDefinitionKey", processDefinitionKey);
        String resultStr = HttpUtil.sendHttpPostJson(url, body.toJSONString());
        return handleResult(resultStr);
    }

    public JSONObject getChildNodeDetail(String instanceId) {
        Map<String, String> map = Maps.newHashMap();
        map.put("instanceId", instanceId);
        String url = buildUrl(address, WorkFlowUriEnum.子节点信息, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + instanceId + "\r\n返回参数=======================>" + resultStr);
        return  handleResult(resultStr);
    }


    public JSONObject start(Long dangerId, String businessKey, String processDefinitionKey) {
        String url = buildUrl(address, WorkFlowUriEnum.启动流程, null);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        JSONObject body = new JSONObject();
        body.put("businessKey", businessKey);
        body.put("processDefinitionKey", processDefinitionKey);
        JSONArray variables = new JSONArray();
//        JSONObject companyJson = new JSONObject();
//        companyJson.put("name", "companyId");
//        companyJson.put("value", companyId);
//        JSONObject departmentJson = new JSONObject();
//        departmentJson.put("name", "departmentId");
//        departmentJson.put("value", departmentId);
        JSONObject dangerIdJson = new JSONObject();
//        dangerIdJson.put("name", "dangerId");
        dangerIdJson.put("dangerId", dangerId);
//        variables.add(companyJson);
//        variables.add(departmentJson);
//        variables.add(dangerIdJson);
//        body.put("variables", variables);
//        String requestBody = body.toJSONString();
        body.put("variables", dangerIdJson);
        String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, body.toJSONString(), headerMap);
        logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + body + "\r\n返回参数=======================>" + resultStr);
        return JSON.parseObject(resultStr);
    }

    public JSONObject startWithAppKey(JSONObject body) {
        Map<String, String> map = Maps.newHashMap();
        map.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        map.put(XJConstant.PRODUCT, RequestContext.getProduct());
        map.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String url = buildUrl(address, WorkFlowUriEnum.启动免登录流程, map);
        String requestBody = body.toJSONString();
        String resultStr = HttpUtil.sendHttpPostJson(url, requestBody);
        logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + requestBody + "\r\n返回参数=======================>" + resultStr);
        return handleResult(resultStr);
    }

    public JSONObject startNew(Long dangerId, String businessKey, String processDefinitionKey) {
        String url = buildUrl(address, WorkFlowUriEnum.合并启动流程, null);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        JSONObject body = new JSONObject();
        body.put("businessKey", businessKey);
        body.put("processDefinitionKey", processDefinitionKey);
        JSONObject dangerIdJson = new JSONObject();
        dangerIdJson.put("dangerId", dangerId);
        body.put("variables", dangerIdJson);
        String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, body.toJSONString(), headerMap);
        logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + body + "\r\n返回参数=======================>" + resultStr);
        return JSON.parseObject(resultStr);
    }
//    public JSONObject stop(String processInstanceId, String deleteReason) {
//        Map<String, String> map = Maps.newHashMap();
//        map.put("deleteReason", deleteReason);
//        map.put("processInstanceId", processInstanceId);
//        String url = buildUrl(address, WorkFlowUriEnum.终止流程, map);
//        String resultStr = HttpUtil.sendHttpDelete(url);
//        JSONObject json = handleResult(resultStr);
//        logger.info("\r\n终止流程请求路径=======================>" + url + "\r\n终止流程返回参数=======================>" + resultStr);
//        return json;
//    }

    public JSONObject stop(String processInstanceId) {
        Map<String, String> map = Maps.newHashMap();
//        map.put("deleteReason", deleteReason);
        map.put("processInstanceId", processInstanceId);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String url = buildUrl(address, WorkFlowUriEnum.终止流程, map);
        String resultStr = HttpUtil.sendHttpDeleteWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }

//    public JSONObject excute(String taskId, String requestBody) {
//        Map<String, String> map = Maps.newHashMap();
//        map.put("taskId", taskId);
//        String url = buildUrl(address, WorkFlowUriEnum.执行流程, map);
//        String resultStr = HttpUtil.sendHttpPostJson(url, requestBody);
//        JSONObject json = handleResult(resultStr);
//        logger.info("\r\n执行任务请求路径=======================>" + url + "\r\n执行任务请求参数=======================>" + requestBody + "\r\n执行任务返回参数=======================>" + resultStr);
//        return json;
//    }

    public JSONObject execute(String taskId, String requestBody) {
        Map<String, String> map = Maps.newHashMap();
        map.put("taskId", taskId);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String url = buildUrl(address, WorkFlowUriEnum.执行流程, map);
        String resultStr = HttpUtil.sendHttpPostJsonWithHeader(url, requestBody, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n请求参数=======================>" + requestBody + "\r\n返回参数=======================>" + resultStr);
        return json;
    }

    public JSONObject currentTask(String instanceId) {
        Map<String, String> map = Maps.newHashMap();
        map.put("processInstanceId", instanceId);
        String url = buildUrl(address, WorkFlowUriEnum.当前节点, map);
        String resultStr = HttpUtil.sendHttpGet(url);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n当前任务请求路径=======================>" + url + "\r\n当前任务返回参数=======================>" + resultStr);
        if (json == null) {
            return null;
        }
        JSONArray reviewContent = json.getJSONObject("dataList").getJSONArray("content");
        if (reviewContent != null && reviewContent.size() > 0) {
            return reviewContent.getJSONObject(0);
        }
        return null;
    }

    public JSONObject allTasksInProcessInstanceId(String instanceId) {
        Map<String, String> map = Maps.newHashMap();
        map.put("processInstanceId", instanceId);
        String url = buildUrl(address, WorkFlowUriEnum.工作流流水, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        if (json == null) {
            return null;
        }
        JSONArray allContent = json.getJSONArray("dataList");
        if (allContent != null && allContent.size() > 0) {
            return allContent.getJSONObject(allContent.size() - 1);
        }
        return null;
    }

    public JSONObject pageTask(String userId,Integer BelongType) {
        Map<String, String> map = Maps.newHashMap();
        String url = "";
        map.put("processDefinitionKey", processDefinitionKey);
        if(Integer.parseInt(YesOrNoEnum.YES.getCode())==BelongType){
            map.put("userId", userId);
            url = buildUrl(address, WorkFlowUriEnum.我的代办有ID, map);
        }else{
            url = buildUrl(address, WorkFlowUriEnum.我的代办, map);
        }
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }

    public JSONObject completedPageTask(String userId,Integer BelongType) {
        Map<String, String> map = Maps.newHashMap();
        String url = "";
        map.put("processDefinitionKey", processDefinitionKey);
        if(Integer.parseInt(YesOrNoEnum.YES.getCode())==BelongType){
            map.put("userId", userId);
            url = buildUrl(address, WorkFlowUriEnum.已执行任务有ID, map);
        }else{
             url = buildUrl(address, WorkFlowUriEnum.已执行任务, map);
        }

        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }

    public JSONObject queryTask(String id) {
        Map<String, String> map = Maps.newHashMap();
        map.put("processInstanceId", id);
        String url = buildUrl(address, WorkFlowUriEnum.流程任务, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }
    public JSONObject queryTaskNoAuth(String id) {
        Map<String, String> map = Maps.newHashMap();
        map.put("processInstanceId", id);
        String url = buildUrl(address, WorkFlowUriEnum.无权限流程任务, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }
    public JSONObject queryTaskDetail(String taskId) {
        Map<String, String> map = Maps.newHashMap();
        map.put("taskId", taskId);
        String url = buildUrl(address, WorkFlowUriEnum.流程详情, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }
    public JSONObject queryFinishTaskDetail(String taskId) {
        Map<String, String> map = Maps.newHashMap();
        map.put("taskId", taskId);
        String url = buildUrl(address, WorkFlowUriEnum.所有已执行任务详情, map);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put(XJConstant.TOKEN_KEY, RequestContext.getToken());
        headerMap.put(XJConstant.PRODUCT, RequestContext.getProduct());
        headerMap.put(XJConstant.APPKEY, RequestContext.getAppKey());
        String resultStr = HttpUtil.sendHttpGetWithHeader(url, headerMap);
        JSONObject json = handleResult(resultStr);
        logger.info("\r\n请求路径=======================>" + url + "\r\n返回参数=======================>" + resultStr);
        return json;
    }
}
