package com.engine.htsc.itlxlc.cmd;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import weaver.general.Util;
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.*;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.hrm.User;
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 ItlxlcProjectCmd extends AbstractCommonCommand<Map<String, Object>> {

    public ItlxlcProjectCmd(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 pcode = Util.null2String(params.get("ProjectCode"));
        String pkey = Util.null2String(params.get("PmID"));
        String pname = Util.null2String(params.get("ProjectName"));
        String usercode = Util.null2String(params.get("usercode"));
        bb.writeLog("usercode:"+usercode);

        PropBean pb = new PropBean();
        String url  = pb.getPropName("ItlxlcProjectQueryUrl");
        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);
        }
        //System.out.println("");
        String workcode = "" ;
        if(!"".equals(usercode)){
            String sql = " select workcode from hrmresource where id="+usercode+" ";
            rs.execute(sql);
            if(rs.next()){
                workcode = Util.null2String(rs.getString("workcode"));
            }
        }


        JSONObject jsonObject = new JSONObject();
        bb.writeLog("workcode:"+workcode);
        //011516
        jsonObject.put("badge",workcode);

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> datalist = new ArrayList<Map<String,Object>>();
        try{
            String response = sendPost(url,jsonObject.toJSONString(),headers);
            System.out.println(response);
            if(!"".equals(response))
            {
                JSONObject retJson = JSONObject.parseObject(response);
                String retCode = retJson.getString("retCode");
                if("0000".equals(retCode)){
                    String projectData = retJson.getString("projectData").replaceAll("\n","");
                    //System.out.println("projectData:"+projectData);
                    if(!"".equals(projectData) && projectData.startsWith("<?xml")){
                        Document doc = null;
                        try {
                            doc = DocumentHelper.parseText(projectData);
                        } catch (DocumentException e) {
                            e.printStackTrace();
                        }
                        Element topEle = doc.getRootElement();
                        //System.out.println("topEle:"+topEle.toString());
                        List<Element> nodes = topEle.elements("Item");
                        Map<String,Object> dataMap = null;
                        for (Iterator it = nodes.iterator(); it.hasNext();)
                        {
                            Element elm = (Element) it.next();
                            String PmName = elm.elementTextTrim("PmName");
                            //System.out.println("PmName:" + PmName);
                            String ProjectName = elm.elementTextTrim("ProjectName");
                            //System.out.println("ProjectName:" + ProjectName);

                            String ProjectCode = elm.elementTextTrim("ProjectCode");
                           // System.out.println("ProjectCode:" + ProjectCode);

                            String planningProject = elm.elementTextTrim("planningProject");
                            //System.out.println("planningProject:" + planningProject);

                            String PmID = elm.elementTextTrim("PmID");
                            //System.out.println("PmID:" + PmID);

                            dataMap = new HashMap<String,Object>();
                            dataMap.put("PmName",PmName);
                            dataMap.put("ProjectName",ProjectName);
                            dataMap.put("ProjectCode",ProjectCode);
                            dataMap.put("planningProject",planningProject);
                            dataMap.put("PmID",PmID);
                            list.add(dataMap);
                        }
                    }

                    Pattern name = Pattern.compile(pname);
                    Pattern code = Pattern.compile(pcode);
                    Pattern key = Pattern.compile(pkey);

                    if(!"".equals(pkey)){
                        list = list.stream().filter(map -> key.matcher(Util.null2String(map.get("PmID"))).find()).collect(Collectors.toList());
                    }
                    if(!"".equals(pcode)){
                        list = list.stream().filter(map -> code.matcher(Util.null2String(map.get("ProjectCode"))).find()).collect(Collectors.toList());
                    }
                    if(!"".equals(pname)){
                        list = list.stream().filter(map -> name.matcher(Util.null2String(map.get("ProjectName"))).find()).collect(Collectors.toList());
                    }

//                    bb.writeLog("list:"+list.size());
//                    if(list !=null && list.size() > 0 )
//                    {
//                        int listsize = list.size();
//                        int page1 = (pageNo-1)*pagesize;
//                        int page2 = pageNo*pagesize;
//                        if(listsize >= page2)
//                        {
//                            datalist = list.subList(page1,page2);  //获取子列表
//                        }else if(listsize < page2 && listsize >= page1){
//                            datalist = list.subList(page1,listsize);
//                        }else{
//                            datalist = new ArrayList<Map<String,Object>>();
//                        }
//                    }
                    bb.writeLog("datalist:"+datalist.size());
                }
            }
        }catch (Exception e){
            bb.writeLog(e);
        }
        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","300");
////        params.put("page","0");
////        params.put("workcode","002180");
////        params.put("month","2021-01");
////        params.put("type","1");
//
//        String url  ="http://168.61.69.225:8080/jtxt/ITProjects/getItProjects" ;
//        Map<String,String> headMap = new HashMap<String,String>();
//
//        HTUtil htutil = new HTUtil();
//        String token = htutil.getAppToken();
//        Map<String, String> headers = new HashMap<>();
//        System.out.println("");
//        headers.put("JTXT-AUTH-TOKEN", token);
//        headers.put("JTXT-AUTH-TYPE", "APP");
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("badge","011516");
//        ItlxlcProjectCmd ItlxlcProjectCmd = new ItlxlcProjectCmd(null,null);
//        String response = ItlxlcProjectCmd.sendPost(url,jsonObject.toJSONString(),headMap);
//        System.out.println(response);
//        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//        if(!"".equals(response))
//        {
//            JSONObject retJson = JSONObject.parseObject(response);
//            String retCode = retJson.getString("retCode");
//            if("0000".equals(retCode)){
//                String projectData = retJson.getString("projectData").replaceAll("\n","");
//                System.out.println("projectData:"+projectData);
//                if(!"".equals(projectData) && projectData.startsWith("<?xml")){
//                    Document doc = null;
//                    try {
//                        doc = DocumentHelper.parseText(projectData);
//                    } catch (DocumentException e) {
//                        e.printStackTrace();
//                    }
//                    Element topEle = doc.getRootElement();
//                    System.out.println("topEle:"+topEle.toString());
//                    //Element bodyEle = topEle.element("Body");
//                    //System.out.println("bodyEle:"+bodyEle.toString());
//                    //Element rootEle = topEle.element("ProjectData");
//                    //System.out.println("rootEle:"+rootEle.toString());
//                    List<Element> nodes = topEle.elements("Item");
//                    Map<String,Object> dataMap = null;
//                    for (Iterator it = nodes.iterator(); it.hasNext();)
//                    {
//                        Element elm = (Element) it.next();
//                        String PmName = elm.elementTextTrim("PmName");
//                        System.out.println("PmName:" + PmName);
//                        String ProjectName = elm.elementTextTrim("ProjectName");
//                        System.out.println("ProjectName:" + ProjectName);
//
//                        String ProjectCode = elm.elementTextTrim("ProjectCode");
//                        System.out.println("ProjectCode:" + ProjectCode);
//
//                        String planningProject = elm.elementTextTrim("planningProject");
//                        System.out.println("planningProject:" + planningProject);
//
//                        String PmID = elm.elementTextTrim("PmID");
//                        System.out.println("PmID:" + PmID);
//
//                        dataMap = new HashMap<String,Object>();
//                        dataMap.put("PmName",PmName);
//                        dataMap.put("ProjectName",ProjectName);
//                        dataMap.put("ProjectCode",ProjectCode);
//                        dataMap.put("planningProject",planningProject);
//                        dataMap.put("PmID",PmID);
//                        list.add(dataMap);
//                    }
//                }
//            }
//        }
//    }

    /***
     *
     * @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");

        ItlxlcProjectCmd ItlxlcProjectCmd = new ItlxlcProjectCmd(params);
        CommandContext ceshi = new CommandContext(null,null);
        ItlxlcProjectCmd.execute(ceshi);
    }


}
