package com.engine.htsc.itxqlc.cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ItxqlcXgxtCmd extends AbstractCommonCommand<Map<String, Object>> {

    public ItxqlcXgxtCmd(Map<String, Object> params) {
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {

        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        bb.writeLog( "in=================ItlxlcFreeNodeCmd" );
        Map<String, Object> apimap = new HashMap<String, Object>();

        int pageNo = Util.getIntValue(Util.null2String(params.get("pageNo")),1);
        int pagesize = Util.getIntValue(Util.null2String(params.get("pagesize")),10);
        bb.writeLog( "pageNo:"+pageNo );
        bb.writeLog( "pagesize:"+pagesize );

        String pappSysId = Util.null2String(params.get("appSysId"));
        String pappCode = Util.null2String(params.get("appCode"));
        String pappNameCnStr = Util.null2String(params.get("appNameCnStr"));
        String presponsibleBuNameCn = Util.null2String(params.get("responsibleBuNameCn"));
        String prltResponsPr = Util.null2String(params.get("rltResponsPr"));
        String prltTeams = Util.null2String(params.get("rltTeams"));

        PropBean pb = new PropBean();
        //String url  = "http://168.61.10.179:8888/jtxt/ItDemandand/getITsystemAll";
        String url = pb.getPropName("itxqsq_xgxtxz");
        Map<String, String> headers = new HashMap<>();
        try{
            HTUtil htutil = new HTUtil();
            String token = htutil.getAppToken();
            headers.put("JTXT-AUTH-TOKEN", token);
            headers.put("JTXT-AUTH-TYPE", "APP");
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }

        JSONObject jsonObject = new JSONObject();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try{
            String response = sendPost(url,jsonObject.toJSONString(),headers);
            System.out.println(response);
            if(!"".equals(response))
            {
                JSONArray jsonArray = JSONArray.parseArray(response);
                Map<String,Object> map = null ;
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject dataObject = jsonArray.getJSONObject(i);
                    String appSysId = dataObject.getString("appSysId");
                    String appCode = dataObject.getString("appCode");
                    String appNameCnStr = dataObject.getString("appNameCnStr");
                    String responsibleBuNameCn = dataObject.getString("responsibleBuNameCn");
                    String rltResponsPr = dataObject.getString("rltResponsPr");
                    String rltTeams = dataObject.getString("rltTeams");

                    map = new HashMap<String,Object>();
                    map.put("appSysId",appSysId);
                    map.put("appCode",appCode);
                    map.put("appNameCnStr",appNameCnStr);
                    map.put("responsibleBuNameCn",responsibleBuNameCn);
                    map.put("rltResponsPr",rltResponsPr);
                    map.put("rltTeams",rltTeams);
                    list.add(map);
                }
            }
            if(list !=null && list.size() > 0){
                Pattern k_pappSysId = Pattern.compile(pappSysId);
                Pattern k_pappCode = Pattern.compile(pappCode);
                Pattern k_pappNameCnStr = Pattern.compile(pappNameCnStr);
                Pattern k_presponsibleBuNameCn = Pattern.compile(presponsibleBuNameCn);
                Pattern k_prltResponsPr = Pattern.compile(prltResponsPr);
                Pattern k_prltTeams = Pattern.compile(prltTeams);

                if(!"".equals(k_pappSysId)){
                    list = list.stream().filter(map -> k_pappSysId.matcher(Util.null2String(map.get("appSysId"))).find()).collect(Collectors.toList());
                }
                if(!"".equals(k_pappCode)){
                    list = list.stream().filter(map -> k_pappCode.matcher(Util.null2String(map.get("appCode"))).find()).collect(Collectors.toList());
                }
                if(!"".equals(k_pappNameCnStr)){
                    list = list.stream().filter(map -> k_pappNameCnStr.matcher(Util.null2String(map.get("appNameCnStr"))).find()).collect(Collectors.toList());
                }
                if(!"".equals(k_presponsibleBuNameCn)){
                    list = list.stream().filter(map -> k_presponsibleBuNameCn.matcher(Util.null2String(map.get("responsibleBuNameCn"))).find()).collect(Collectors.toList());
                }
                if(!"".equals(k_prltResponsPr)){
                    list = list.stream().filter(map -> k_prltResponsPr.matcher(Util.null2String(map.get("rltResponsPr"))).find()).collect(Collectors.toList());
                }
                if(!"".equals(k_prltTeams)){
                    list = list.stream().filter(map -> k_prltTeams.matcher(Util.null2String(map.get("rltTeams"))).find()).collect(Collectors.toList());
                }
            }

        }catch (Exception e){
            bb.writeLog(e);
        }
        System.out.println("size:"+list.size());
        apimap.put("data",list);
        apimap.put("count",list.size());
        return apimap;
    }

    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");

        Map<String, Object> params=new HashMap<>();
        params.put("size","10");
        params.put("page","0");

        CommandContext ceshi = new CommandContext(null,null);
        String url  ="http://168.61.10.179:8888/jtxt/ItDemandand/getITsystemAll" ;
        Map<String,String> headMap = new HashMap<String,String>();
        JSONObject jsonObject = new JSONObject();
        ItxqlcXgxtCmd ItxqlcXgxtCmd = new ItxqlcXgxtCmd(params);
        ItxqlcXgxtCmd.execute(ceshi);


    }

    /***
     *
     * @param url
     * @param params
     * @param headsMap
     * @return
     */
    public String sendPost(String url, String params, Map<String,String> headsMap)
    {
        //BaseBean bb = new BaseBean();
        String body = "";
        String encoding = "UTF-8";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);


        //设置参数到请求对象中
        StringEntity strEntity = new StringEntity(params,encoding);//解决中文乱码问题
        strEntity.setContentEncoding(encoding);
        strEntity.setContentType("application/json");
        httpPost.setEntity(strEntity);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                //bb.writeLog("key:"+key+" value:"+value);
                httpPost.addHeader(key, value);
            });
        }
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            System.out.println("OrganizationSyn-e:"+e);
            e.printStackTrace();
        }
        return body;
    }


//    public static void main(String[] args) {
//        GCONST.setRootPath("WEB-INF/");
//        GCONST.setServerName("ecology");
//        Map<String, Object> params=new HashMap<>();
//        params.put("size","10");
//        params.put("page","0");
//
//        ItxqlcXgxtCmd ItlxlcProjectCmd = new ItxqlcXgxtCmd(params);
//        CommandContext ceshi = new CommandContext(null,null);
//        ItlxlcProjectCmd.execute(ceshi);
//    }


}
