package com.engine.htsc.itcglc.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 weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;

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

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

    public ItcglcProjectListCmd(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();

        Map<String, Object> apimap = new HashMap<String, Object>();
        String pcode = Util.null2String(params.get("projectCode"));
        String pstate = Util.null2String(params.get("projectState"));
        String pname = Util.null2String(params.get("projectName"));
        String processno = Util.null2String(params.get("processNo"));
        String pmanager = Util.null2String(params.get("projectManager"));
        String usercode = Util.null2String(params.get("usercode"));

        bb.writeLog("usercode:"+usercode);

        PropBean pb = new PropBean();
        String url  = pb.getPropName("ItcglcProjectQueryUrl") ;
        //String url = "http://168.61.69.225:8080/jtxt/ITProjects/getProjectInfoBySearch";
        bb.writeLog(url);
        Map<String, String> headers = new HashMap<>();
        String workcode = "" ;
        if(!"".equals(usercode)){
            String sql = " select workcode from hrmresource where id="+usercode+" ";
            bb.writeLog(sql);
            rs.execute(sql);
            if(rs.next()){
                workcode = Util.null2String(rs.getString("workcode"));
            }
        }
        bb.writeLog("workcode:"+workcode);

        JSONObject jsonObject = new JSONObject();
        //011516
        jsonObject.put("badge",workcode);

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try{
            bb.writeLog("jsonObject:"+jsonObject);

            String response = sendPost(url,jsonObject.toJSONString(),headers);
            bb.writeLog("response:"+response);
            if(!"".equals(response))
            {
                Map<String,Object> dataMap = null;
                JSONArray jsonArray = JSONArray.parseArray(response);
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject dataJson = jsonArray.getJSONObject(i);

                    dataMap = new HashMap<String,Object>();
                    dataMap.put("projectState",dataJson.getString("projectState"));
                    dataMap.put("projectName",dataJson.getString("projectName"));
                    dataMap.put("processNo",dataJson.getString("processNo"));
                    dataMap.put("projectManager",dataJson.getString("projectManager"));
                    dataMap.put("projectCode",dataJson.getString("projectCode"));
                    dataMap.put("completeTime",dataJson.getString("completeTime"));
                    //判断是否关联本地oa流程

                    String sql = "select abs(formid)  formid from workflow_base where unnumber = 'itlxsq' and isvalid = 1";
                    rs.executeQuery(sql);
                    String formtable = "";
                    if(rs.next()){
                        formtable = "formtable_main_" + rs.getString("formid");
                    }
                    if(!"".equals(formtable)){
                        sql = "select * from  " + formtable + " where xmbh  = ?";
                        rs.executeQuery(sql, dataJson.getString("projectCode"));
                        if(rs.next()){
                            dataMap.put("gllcFlag","1");//加入一个标记，标识是否关联本地oa   1：关联 0:无
                            dataMap.put("lcbt",rs.getString("lcbt")); //添加一条记录流程标题
                        }else{
                            dataMap.put("gllcFlag","0");
                            dataMap.put("lcbt","");
                        }
                    }else{
                        dataMap.put("gllcFlag","0");
                        dataMap.put("lcbt","");
                    }

                    list.add(dataMap);
                }

                if(list !=null && list.size() >0)
                {
                    Pattern name = Pattern.compile(pname);
                    Pattern code = Pattern.compile(pcode);
                    Pattern state = Pattern.compile(pstate);
                    Pattern rocessno = Pattern.compile(processno);
                    Pattern manager = Pattern.compile(pmanager);

                    if(!"".equals(state)){
                        list = list.stream().filter(map -> state.matcher(Util.null2String(map.get("projectState"))).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());
                    }
                    if(!"".equals(manager)){
                        list = list.stream().filter(map -> manager.matcher(Util.null2String(map.get("projectManager"))).find()).collect(Collectors.toList());
                    }
                    if(!"".equals(rocessno)){
                        list = list.stream().filter(map -> rocessno.matcher(Util.null2String(map.get("projectManager"))).find()).collect(Collectors.toList());
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
        }
        bb.writeLog("list:"+list.size());
//        System.out.println("list:"+list.size());
        apimap.put("data",list);
        apimap.put("count",list.size());
        return apimap;
    }

    /***
     *
     * @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","1");
        params.put("usercode","5620");

        params.put("ProjectCode","");
        params.put("projectState","");
        params.put("projectName","");
        params.put("processNo","");
        params.put("projectManager","");

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


}
