package com.api.browser.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.ListHeadBean;
import com.api.browser.service.BrowserService;
import com.api.browser.util.*;
import com.engine.htsc.payment.util.HttpUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.htsc.util.TokenUtil;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.request.RequestBaseUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class OldOaBrowserService extends BrowserService {

    @Override
    public Map<String, Object> getBrowserData(Map<String, Object> paramMap) throws Exception {
        HashMap localHashMap1 = new HashMap();
        JSONArray jsonArray =new JSONArray();
        List dataList = new ArrayList();

        //获取起始值
        int min = Integer.valueOf(paramMap.get("min").toString());
        //获取末尾值
        int max = Integer.valueOf(paramMap.get("max").toString());
        //用户ID
        String userId = Util.null2String(paramMap.get("wfCreater"));
        String type = "2";
        //标题
        String requestName = Util.null2String(paramMap.get("title"));
        //流程编号
        String workFlowNum = Util.null2String(paramMap.get("workflownum"));
        //创建人
        String creater = Util.null2String(paramMap.get("creater"));

        int pageNumber = Integer.parseInt(Util.null2String(paramMap.get("current")));
        int pageSize = Integer.parseInt(Util.null2String(paramMap.get("pageSize")));


        JSONObject jsonObject=new JSONObject();
        jsonObject.put("title",requestName);
        jsonObject.put("workFlowNum",workFlowNum);
        jsonObject.put("drafterName",creater);
        jsonObject.put("pageNumber",pageNumber);
        jsonObject.put("pageSize",pageSize);
        jsonObject.put("type",type);

        try {
            RecordSet rs = new RecordSet();
            String workCodesql = " select workcode from hrmresource where id=?";
            rs.executeQuery(workCodesql,userId);
            if (rs.next()){
                jsonObject.put("userId",rs.getString("workcode"));
                log.debug("请求参数：jsonObject: [{}]",jsonObject);
                //查询接口
                String urlSql = "select xtmc,qqdz,appid from UF_LCJKDZ where sfqy=0";
                rs.executeQuery(urlSql);
                List<Map<String,String>> urlList = new ArrayList<>();
                while (rs.next()){
                    Map<String,String> map = Maps.newHashMap();
                    map.put("xtmc",rs.getString("xtmc"));
                    map.put("qqdz",rs.getString("qqdz"));
                    map.put("appid",rs.getString("appid"));
                    urlList.add(map);
                }

                for (Map<String,String> url:urlList){
                    String responsestr = "";
                    if (url.get("appid") != null && !"".equals(url.get("appid"))){
                        responsestr = TokenUtil.post(url.get("xtmc"),"/api/ohtersystem/workflow/todos",jsonObject.toJSONString(),url.get("appid"));
                    }else {
                        responsestr = HttpUtil.postApplicationJson(url.get("qqdz")+"todos", jsonObject.toJSONString());
                    }
                    log.debug("responsestr：[{}]",responsestr);
                    if (!"".equals(responsestr)){
                        JSONObject jsonObjectstr = JSONObject.parseObject(responsestr);
                        if(jsonObjectstr!=null&&jsonObjectstr.size()>0){
                            jsonArray.addAll(jsonObjectstr.getJSONArray("data"));
                        }
                    }
                }
                localHashMap1.put(BrowserConstant.BROWSER_RESULT_TOTAL,jsonArray.size());
                /**
                 * 分页
                 */
                if (max > jsonArray.size()){
                    max = jsonArray.size();
                }
                for (int i=(min-1);i<max;i++){
                    Map<String,Object> dataMap = new HashMap();
                    Map jsonMap = (Map) jsonArray.get(i);
                    dataMap.put(BrowserConstant.BROWSER_LIST_CHECKBOX_FIELDNAME,jsonMap.get("url")+"^"+jsonMap.get("requestid"));
//                    dataMap.put("id",jsonMap.get("url")+"^"+jsonMap.get("type"));
                    dataMap.put("id",jsonMap.get("url")+"^"+jsonMap.get("requestid"));
                    dataMap.put("title",jsonMap.get("title"));
                    dataMap.put("workflownum",jsonMap.get("referencenumber"));
                    dataMap.put("creater",jsonMap.get("createrName"));
                    dataMap.put("createdate",jsonMap.get("createDate")+" "+jsonMap.get("createTime"));
                    dataMap.put("url",jsonMap.get("url"));
                    dataList.add(dataMap);
                }
            }

        }catch (Exception e){
            log.error("sync fund status fail, catch error: [{}]", e);
        }



        List localObject = new ArrayList();
        localObject.add(new ListHeadBean(BrowserConstant.BROWSER_LIST_CHECKBOX_FIELDNAME, BoolAttr.TRUE));
        localObject.add(new ListHeadBean("id", BoolAttr.TRUE).setIsPrimarykey(BoolAttr.TRUE));
        ListHeadBean localListHeadBean = new ListHeadBean("title", SystemEnv.getHtmlLabelName(502369, this.user.getLanguage()), 1, BoolAttr.TRUE);
        localListHeadBean.setOldWidth("25%");
        localObject.add(localListHeadBean);
        localListHeadBean = new ListHeadBean("workflownum", SystemEnv.getHtmlLabelName(19502, this.user.getLanguage()));
        localListHeadBean.setOldWidth("25%");
        localObject.add(localListHeadBean);
        localListHeadBean = new ListHeadBean("creater", SystemEnv.getHtmlLabelName(882, this.user.getLanguage()));
        localListHeadBean.setOldWidth("25%");
        localObject.add(localListHeadBean);
        localListHeadBean = new ListHeadBean("createdate", SystemEnv.getHtmlLabelName(1339, this.user.getLanguage()));
        localListHeadBean.setOldWidth("25%");
        localObject.add(localListHeadBean);


        localHashMap1.put(BrowserConstant.BROWSER_RESULT_COLUMN, localObject);
        localHashMap1.put(BrowserConstant.BROWSER_RESULT_DATA, dataList);
        localHashMap1.put(BrowserConstant.BROWSER_RESULT_TYPE, Integer.valueOf(BrowserDataType.LIST_SPLIT_DATA_O.getTypeid()));
        return (Map<String, Object>)localHashMap1;
    }

    public Map<String, Object> getBrowserConditionInfo(Map<String, Object> paramMap)
            throws Exception
    {
        HashMap localHashMap = new HashMap();
        ArrayList localArrayList1 = new ArrayList();
        ConditionFactory localConditionFactory = new ConditionFactory(this.user);
        localArrayList1.add(localConditionFactory.createCondition(ConditionType.INPUT, 19502, "workflownum"));
        localArrayList1.add(localConditionFactory.createCondition(ConditionType.INPUT, 882, "creater"));
        localArrayList1.add(localConditionFactory.createCondition(ConditionType.INPUT, 502369, "title"));




        localHashMap.put(BrowserConstant.BROWSER_RESULT_CONDITIONS, localArrayList1);
        return (Map<String, Object>)(Map<String, Object>)localHashMap;
    }

    public Map<String, Object> getMultBrowserDestData(Map<String, Object> var1){
        HashMap var2 = new HashMap();
        String var3 = Util.null2String(var1.get(BrowserConstant.BROWSER_MULT_DEST_SELECTIDS));
        ArrayList dataList = new ArrayList();
        if ("".equals(var3)) {
            return var2;
        } else {
            String[] values = var3.split(",");
            Map<String,String> idMap = new HashMap<>();
            String id="";
            for (int i=0;i<values.length;i++){
                String value = values[i];
                String[] val = value.split("\\^");
                if (val.length>1){
                    String systemName = val[0].split("/")[3];//系统标识 xcoa、htoa
                    if (idMap.get(systemName) == null){
                        idMap.put(systemName,val[1]);
                    }else {
                        String ids = idMap.get(systemName) +","+val[1];
                        idMap.put(systemName,ids);
                    }
                }
            }

            log.debug("请求参数：ids: [{}]",idMap);
            try {
                RecordSet rs = new RecordSet();
                //查询接口
                String urlSql = "select xtmc,qqdz,appid from UF_LCJKDZ where sfqy=0";
                rs.executeQuery(urlSql);
                Map<String,String> urlMap = new HashMap<>();
                while (rs.next()){
                    if (idMap.get(rs.getString("xtmc")) !=null){
                        String ids = idMap.get(rs.getString("xtmc"));
                        String xtmc = rs.getString("xtmc");
                        String url = rs.getString("qqdz");
                        String appid = rs.getString("appid");
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("requestIds",ids);
                        jsonObject.put("xtmc",rs.getString("xtmc"));
                        String responsestr = "";
                        if (appid != null && !"".equals(appid)){
                            responsestr = TokenUtil.post(xtmc,"/api/ohtersystem/workflow/getRequestData",jsonObject.toJSONString(),appid);
                        }else {
                            responsestr = HttpUtil.postApplicationJson(url+"getRequestData", jsonObject.toJSONString());
                        }

                        log.debug("responsestr：[{}]",responsestr);
                        if (!"".equals(responsestr)){
                            JSONObject jsonObjectstr = JSONObject.parseObject(responsestr);
                            if(jsonObjectstr!=null&&jsonObjectstr.size()>0){
                                dataList.addAll(jsonObjectstr.getJSONArray("data"));
                            }
                        }
                    }
                }
            }catch (Exception e){
                log.error("sync fund status fail, catch error: [{}]", e);
            }
//            String var4 = "select requestid,creatertype,requestname,requestmark,requestnamenew,creater,createdate,createtime from workflow_requestbase where requestid in (" + ids + ")";
//            RecordSet rs = new RecordSet();
//            rs.executeSql(var4);
//            ResourceComInfo var6 = new ResourceComInfo();
//            CustomerInfoComInfo var7 = new CustomerInfoComInfo();
//            ArrayList var8 = new ArrayList();
//
//            while(rs.next()) {
//                String var9 = Util.null2String(rs.getString("requestid"));
//                String var10 = Util.null2String(rs.getString("creater"));
//                String var11 = Util.null2String(rs.getString("createdate"));
//                String var12 = Util.null2String(rs.getString("createtime"));
//                String var13 = Util.null2String(rs.getString("requestname"));
////                String var14 = this.getRequestname("", var9 + "+" + this.user.getLanguage() + "+" + var13);
//                String var15 = Util.null2String(rs.getString("createtype"));
//                if ("1".equals(var15)) {
//                    var10 = var7.getCustomerInfoname(var10);
//                } else {
//                    var10 = var6.getResourcename(var10);
//                }
//
//                HashMap var16 = new HashMap();
//                var16.put("id", var9);
//                var16.put("title", var13);
//                var16.put("workflownum", Util.null2String(rs.getString("requestmark")));
////                var16.put("titlespan", var13);
////                var16.put("titlenew", var14);
//                var16.put("creater", var10);
//                var16.put("createdate", var11 + " " + var12);
//                var8.add(var16);
//            }

            var2.put(BrowserConstant.BROWSER_RESULT_DATA, dataList);
            var2.put(BrowserConstant.BROWSER_RESULT_TYPE, BrowserDataType.LIST_ALL_DATA.getTypeid());
            return var2;
        }
    }


    public String getRequestname(String var1, String var2) {
        int var3 = Util.getIntValue(var2.substring(0, var2.indexOf("+")));
        var2 = var2.substring(var2.indexOf("+") + 1);
        int var4 = Util.getIntValue(var2.substring(0, var2.indexOf("+")));
        String var5 = var2.substring(var2.indexOf("+") + 1);
        RecordSet var6 = new RecordSet();
        var6.executeQuery("select id,formid,isbill from workflow_base t1 where exists (select 1 from workflow_requestbase t2 where t2.workflowid  = t1.id and t2.requestid = ? )", new Object[]{var3});
        int var7 = 0;
        int var8 = 0;
        int var9 = 0;
        if (var6.next()) {
            var7 = var6.getInt(1);
            var8 = var6.getInt(2);
            var9 = var6.getInt(3);
        }

        RequestBaseUtil var10 = new RequestBaseUtil();
        var5 = var10.formatRequestname(var5, var7 + "", var3 + "", var9, var8, var4);
        return var5;
    }
}
