package com.horizon.wf.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.horizon.cache.api.HCacheClient;
import com.horizon.common.collect.Lists;
import com.horizon.common.collect.Maps;
import com.horizon.common.constant.Constants;
import com.horizon.core.HorizonCore;
import com.horizon.db.Access;
import com.horizon.third.adapter.OrganizationAdapter;
import com.horizon.wf.bean.WorkParaBean;
import com.horizon.wf.util.dto.WbCompleteTodoDto;
import com.horizon.wf.util.dto.WbPushTodoDto;

import java.util.*;


public class PushWorkflowToPortal {

    private static String cacheGroup = "SendMsgToHall";
    /**
     * 如果需要往第三方数据写入待办相关数据
     * tmpJson JSON格式的数组
     *
     * SqlType=INSERT时
     * InsertFields = 已经拼好的要插入的字段,字符串
     * InsertPara = 插入时对应的值,数组
     *
     * SqlType=UPDATE或者DELETE时
     * WhereCondition = 已经拼好的查询条件字段,字符串
     * WhereFields = 查询条件字段列表,数组
     * WherePara = 查询条件对应的参数值,数组
     *
     * SqlType=UPDATE时
     * SetStr = 已经拼好的需要更新的字段,字符串
     * SetFields = 更新字段列表,数组
     * SetPara = 更新字段对应的参数值,数组
     */
    public static void sendTodoData(String type, JSONArray tmpJson, WorkParaBean paraBean, String workid) {
        if(type.equals("dataToSend")){
            //待办、待阅数据
            Map<String, Map<String, String>> insertSaveMap = Maps.newHashMap();
            //待办变已办、待阅变已阅、待办变可阅数据
            Map<String, Map<String, String>> updateSaveMap = Maps.newHashMap();
            sendTodoData(tmpJson, paraBean, insertSaveMap, updateSaveMap, workid);
            // System.out.println("+=============================");
            boolean newQAPush = true;
            List<String> todoIds = Lists.newArrayList();
            //在这里调用门户的接口
            if(!insertSaveMap.isEmpty()){
                // select creator from tw_hz_instance where id = 'workid'
                // HorizonCore.USER_ID.value()
                String creator = "";
                if(workid != null && !workid.isEmpty()){
                    String sql = "select creator from tw_hz_instance where id = ?";
                    List<String> list = Lists.newArrayList();
                    list.add(workid);
                    //单条数据查询
                    //返回第一条数据，list
                    //返回第一条数据，map，key=小写字段名，value=值
                    Map resmap = Access.getSingleMap(sql, list);
                    // System.err.println(resmap);
                    creator = (String) resmap.get("creator");
                }else{
                    creator = HorizonCore.USER_ID.value();
                }

                for(Map.Entry<String, Map<String, String>> entry : insertSaveMap.entrySet()){
                    String scheduleId = entry.getKey();
                    Map<String, String> value = entry.getValue();

                    String subjectionId = value.get("subjectionId");
                    String workId = value.get("workId");
                    String trackId = value.get("trackId");
                    String flowId = value.get("flowId");
                    String nodeId = value.get("nodeId");
                    String flowName = value.get("flowName");

                    String title = value.get("title");

                    String startTime = value.get("sendTime");
                    String nextUserId = value.get("authId");

                    // String businessParam = value.get("title");

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("scheduleId", scheduleId);
                    jsonObject.put("title", title);
                    jsonObject.put("startUserId", creator);
                    jsonObject.put("startTime", startTime);
                    jsonObject.put("nextUserId", nextUserId);
                    jsonObject.put("toWebPath", "/workflow/detail");

                    JSONObject businessParam = new JSONObject();
                    businessParam.put("flowId", flowId);
                    businessParam.put("flowName", flowName);
                    businessParam.put("workId", workId);
                    businessParam.put("trackId", trackId);
                    businessParam.put("subjectionId", subjectionId);
                    businessParam.put("nodeId", nodeId);
                    businessParam.put("type", "3");
                    jsonObject.put("businessParam", businessParam.toJSONString());

                    String url = Constants.WF_PRE_URL + "/framework/Schedule/horizonAdd";
                    Map<String, Object> params = new HashMap<>();
                    params.put("json", jsonObject.toJSONString());

                    String result = HttpUtil.post(url, params);
                    // System.out.println("INSERT: "+result);
                    if(newQAPush){
                        String pushTodoUrl = "/task-service/task/pushTodo";
                        List<String> ass = new ArrayList<>();
                        String jsonBody = "";

                        String userName = "";
                        String queryUserNameSql = "SELECT user_name FROM JLOPAPUSER.sys_user where id = ?";
                        List<String> list = Lists.newArrayList();
                        list.add(nextUserId);
                        Map resmap = Access.getSingleMap(queryUserNameSql, list);
                        userName = (String) resmap.get("user_name");
                        System.err.println(userName);
                        if(userName != null && !userName.isEmpty() && userName.toLowerCase().startsWith("s")){
                            System.err.println(userName);
                            todoIds.add(scheduleId);
                            WbPushTodoDto wbPushTodoDto = new WbPushTodoDto();
                            // 任务实例id
                            wbPushTodoDto.setTaskInstId(scheduleId);
                            // 来源系统代码
                            wbPushTodoDto.setSrcSystemCode("JLYYPT");
                            // 任务所属业务类型代码
                            wbPushTodoDto.setBizTypeCode("SIGN_REQUEST");
                            // 任务指派处理⼈（⽤户名）列表
                            ass = new ArrayList<>();
                            ass.add(userName);
                            wbPushTodoDto.setAssignees(ass);
                            // 任务标题
                            wbPushTodoDto.setTitle(title);
                            // 任务关联业务编码id
                            // wbPushTodoDto.setBizId();
                            // 任务时间（如来源系统⽆则由统⼀待办⽣成）
                            wbPushTodoDto.setTaskTime(startTime);
                            // 任务推送⼈
                            wbPushTodoDto.setCreateUser(creator);
                            // 流程当前节点Id
                            wbPushTodoDto.setNodeDefId(nodeId);
                            // 流程当前节点名称
                            wbPushTodoDto.setNodeDefName(nodeId);
                            // 流程定义id
                            wbPushTodoDto.setProcDefId(flowId);
                            // 流程实例名称
                            wbPushTodoDto.setProcDefName(flowName);
                            // 流程实例id
                            wbPushTodoDto.setProcInstId(workId);
                            // 任务描述
                            wbPushTodoDto.setTaskDescription(title);
                            // PC端待办详情访问链接
                            String todoDetailUrl;
                            String todoDetailUrlMobile;
                            if(subjectionId != null && !subjectionId.isEmpty()){
                                 todoDetailUrl = "http://10.198.1.15/#/workflow/detail?userId="
                                        + nextUserId + "&from=oa&workId=" + workId + "&trackId="
                                        + trackId + "&flowId=" + flowId + "&subjectionId=" + subjectionId;

                                 todoDetailUrlMobile = "https://jlwuliu.shansteelgroup.com/h5/workflow?userId="
                                        + nextUserId + "&workId=" + workId + "&trackId="
                                        + trackId + "&flowId=" + flowId + "&subjectionId=" + subjectionId;
                            }else {
                                 todoDetailUrl = "http://10.198.1.15/#/workflow/detail?userId="
                                        + nextUserId + "&from=oa&workId=" + workId + "&trackId="
                                        + trackId + "&flowId=" + flowId;

                                 todoDetailUrlMobile = "https://jlwuliu.shansteelgroup.com/h5/workflow?userId="
                                        + nextUserId + "&workId=" + workId + "&trackId="
                                        + trackId + "&flowId=" + flowId ;
                            }


                            System.err.println(todoDetailUrl);
                            wbPushTodoDto.setTodoDetailUrl(todoDetailUrl);

                            System.err.println(todoDetailUrlMobile);
                            // 移动端待办详情访问链接
                            wbPushTodoDto.setTodoDetailUrlMobile(todoDetailUrlMobile);

                            jsonBody = JSON.toJSONString(wbPushTodoDto);
                            BaoSightMessengerUtils.sendWithLog("", pushTodoUrl, jsonBody, "");
                        }else {
                            System.err.println("oaUserCode为空,暂不支持推送");
                        }
                    }
                }
            }
            if(!updateSaveMap.isEmpty()){
                // System.err.println(updateSaveMap);
                for(Map.Entry<String, Map<String, String>> entry : updateSaveMap.entrySet()){
                    String scheduleId = entry.getKey();
                    Map<String, String> value = entry.getValue();

                    String url = Constants.WF_PRE_URL + "/framework/Schedule/horizonUpdateDealFlag";
                    Map<String, Object> params = new HashMap<>();
                    params.put("scheduleId", scheduleId);

                    String result = HttpUtil.post(url, params);
                    // System.out.println("UPDATE: "+result);
//                    if(newQAPush && todoIds.contains(scheduleId)){
                    if(newQAPush){
                        // String completeTodoUrl = "/task-service/task/completeTodo";
                        // 501 CReader
                        // 101 Author
                        // 201 Done
                        String statusNo = value.get("statusNo");
                        String status = value.get("status");
                        System.err.println(statusNo + "--" + status);
                        String completeTodoUrl = "/task-service/task/completeTodoByTaskInst";

                        if(statusNo.equals("501") || status.equals("CReader")){
                            completeTodoUrl = "/task-service/task/discardTodoByTaskInst";
                        }

                        WbCompleteTodoDto wbCompleteTodoDto = new WbCompleteTodoDto();

                        // 任务实例id
                        wbCompleteTodoDto.setTaskInstId(scheduleId);
                        // 来源系统代码
                        wbCompleteTodoDto.setSrcSystemCode("JLYYPT");
                        // 任务所属业务类型代码
                        wbCompleteTodoDto.setBizTypeCode("SIGN_REQUEST");
                        // 任务指派处理⼈
                        // wbCompleteTodoDto.setAssignee(creator);

                        String jsonBody = "";
                        jsonBody = JSON.toJSONString(wbCompleteTodoDto);
                        BaoSightMessengerUtils.sendWithLog("", completeTodoUrl, jsonBody, "");
                    }
                }
            }
        }
    }

    private static void sendTodoData(JSONArray dataToSend, WorkParaBean paraBean,
                                     Map<String, Map<String, String>> insertSaveMap, Map<String, Map<String, String>> updateSaveMap, String workid){
        OrganizationAdapter organizationAdapter = new OrganizationAdapter();
        if(dataToSend == null || dataToSend.size() <= 0){
            return;
        }

        //2022-06-29 新增
        //判断是不是创建流程,如果只有一条，并且是insert，则表示是创建流程
        if(dataToSend.size()==1 && "INSERT".equals(dataToSend.getJSONObject(0).getString("SqlType"))) {
            //将流程的实例信息放到session中
            HCacheClient.put(cacheGroup,"TODO"+workid,dataToSend.getJSONObject(0), 0L);
            return;
        }

        //2022-06-29 end
        for(int i = 0; i < dataToSend.size(); i++){
            JSONObject currentItem = dataToSend.getJSONObject(i);

            //2022-06-29 新增 如果是更新，在缓存中查找是否有workid，有的就是新流程暂存，加入insert
            if(currentItem.getString("SqlType").equals("UPDATE")){
                JSONObject cacheTodo = HCacheClient.get(cacheGroup,"TODO"+paraBean.getWorkId());
                if(cacheTodo!=null && cacheTodo.size()>0){
                    currentItem = cacheTodo;
                    HCacheClient.remove(cacheGroup,"TODO"+paraBean.getWorkId());
                }
            }
            //2022-06-29 end
            String sqlType = currentItem.getString("SqlType");
            String flag = currentItem.getString("FLAG");
            if(sqlType.equals("INSERT")){ //待办
                String[] insertFields = currentItem.getString("InsertFields").split(",");
                if(insertFields.length == 0){
                    continue;
                }
                JSONArray insertParas = currentItem.getJSONArray("InsertPara");
                Map<String,String> insertTodo = Maps.newHashMap();
                for(int index = 0; index < insertFields.length; index++){
                    insertTodo.put(insertFields[index], insertParas.getString(index));
                }
                String status = insertTodo.get("STATUS"); //Author主办
                String statusNo = insertTodo.get("STATUS_NO"); //Author主办
                String authId = insertTodo.get("AUTH_ID"); //办理人id
                // String agentId = insertTodo.get("AGENT_ID"); //代办人id
                Map<String, String> author = organizationAdapter.getUserById(authId, paraBean.getFlowIdentifier());
                String authName = author.get("name"); //办理人姓名
                String authLoginName = author.get("login_name"); //办理人账号
                // Map<String, String> agentor = organizationAdapter.getUserById(agentId, paraBean.getFlowIdentifier());
                // String agentName = agentor.get("name"); //代办人姓名
                // String agentLoginName = agentor.get("login_name"); //代办人账号
                String workId = insertTodo.get("WORKID");
                String trackId = insertTodo.get("TRACKID");
                String flowId = insertTodo.get("FLOWID");
                String flowName = insertTodo.get("FLOWNAME");
                String nodeId = insertTodo.get("NODEID");
                String title = insertTodo.get("TITLE");
                String sendTime = insertTodo.get("SENDTIME"); //sendtime
                String subjectionType = insertTodo.get("SUBJECTION_TYPE"); //办理人所属组织type D部门 G群组 P岗位
                String subjectionId = insertTodo.get("SUBJECTION_ID"); //办理人所属组织id
                String id = insertTodo.get("ID"); //待办数据的唯一标识
                Map<String, String> map = insertSaveMap.get(id);
                if(null==map || map.isEmpty()){
                    map = Maps.newHashMap();
                    map.put("flowId", flowId);
                    map.put("workId", workId);
                    map.put("trackId", trackId);
                    map.put("title", title);
                    map.put("flowName", flowName);
                    map.put("nodeId", nodeId);
                }
                map.put("authId", authId);
                map.put("authName", authName);
                map.put("authLoginName", authLoginName);
                // map.put("agentId", agentId);
                // map.put("agentName", agentName);
                // map.put("agentLoginName", agentLoginName);
                map.put("sendTime", sendTime);
                map.put("subjectionType", subjectionType);
                map.put("subjectionId", subjectionId);
                map.put("status", status);
                map.put("statusNo", statusNo);
                map.put("id", id);
                insertSaveMap.put(id, map);

            } else if(sqlType.equals("UPDATE")&&flag.equals("DONE")){ //待办变已办
                JSONArray todoIds = currentItem.getJSONArray("WherePara");
                String workId = paraBean.getWorkId(); //workid
                String[] setFields = currentItem.getString("SetFields").substring(1, currentItem.getString("SetFields").length()-1).split(",");
                if(setFields.length == 0){
                    continue;
                }
                JSONArray setParas = currentItem.getJSONArray("SetPara");
                Map<String,String> updateTodo = Maps.newHashMap();
                for(int index = 0; index < setFields.length; index++){
                    updateTodo.put(setFields[index].trim(), setParas.getString(index));
                }
                String dotime = updateTodo.get("dotime"); //办理时间
                String status = updateTodo.get("status"); //状态
                String statusNo = updateTodo.get("statusNo"); //状态编号
                String title = updateTodo.get("title"); //title
                String id = todoIds.getString(0);
                Map<String, String> map = updateSaveMap.get(id);
                if(null==map || map.isEmpty()){
                    map = Maps.newHashMap();
                    map.put("dotime", dotime);
                    map.put("statusNo", statusNo);
                    map.put("status", status);
                    map.put("workId", workId);
                    map.put("title", title);
                } else {
                    map.put("dotime", dotime);
                    map.put("statusNo", statusNo);
                    map.put("status", status);
                }
                map.put("id", id);
                updateSaveMap.put(id, map);
            }
        }
    }
}

