package com.engine.htxc.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 weaver.interfaces.htsc.util.HT_SelectField;

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

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

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

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

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

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        HT_SelectField HT_SelectField = new HT_SelectField();
        Map<String, Object> apimap = new HashMap<String, Object>();
        String usercode = Util.null2String(params.get("usercode"));
        System.out.println("usercode:"+usercode);
        PropBean pb = new PropBean();
        String url  = pb.getPropName("Itcglc_cgjhurl") ;
        //String url = "http://168.61.69.225:8080/jtxt/ITProjects/getNonstandardizedItProcurement" ;

        String workflowid = pb.getActiveWorkflowIdByUnNumber("itcgsq");
        System.out.println("workflowid:"+workflowid);
        String cglxfieldis = HT_SelectField.getbillFieldByWorkflowid(workflowid,"cglx","dt5");
        String cgfsfieldis = HT_SelectField.getbillFieldByWorkflowid(workflowid,"cgfs","dt5");
        System.out.println("cglxfieldis:"+cglxfieldis);
        System.out.println("cgfsfieldis:"+cgfsfieldis);

        Map<String, String> headers = new HashMap<String, String>();
        String workcode = "" ;
        if(!"".equals(usercode)){
            String sql = " select workcode from hrmresource where id="+usercode+" and belongto is null ";
            rs.execute(sql);
            if(rs.next()){
                workcode = Util.null2String(rs.getString("workcode"));
            }
        }
        System.out.println("workcode:"+workcode);

        JSONObject jsonObject = new JSONObject();
        //011516
        jsonObject.put("badge",workcode);
        List<Map<String,Object>> cgxxlist = new ArrayList<Map<String,Object>>();
        Map<String,Object> cgxxMap = null;
        try{
            String response = sendPost(url,jsonObject.toJSONString(),headers);
            System.out.println("response:"+response);
            if(!"".equals(response))
            {
                JSONObject responseJson = JSONObject.parseObject(response);
                if(!"".equals(responseJson)){
                    if(responseJson.containsKey("itsystemPurchaseData")){

                        JSONObject cgxxObject = responseJson.getJSONObject("itsystemPurchaseData");
                        if(cgxxObject !=null){
                            JSONArray cgxxArray = cgxxObject.getJSONArray("item");


                            for(int i=0;i<cgxxArray.size();i++)
                            {
                                JSONObject cgxxObj = cgxxArray.getJSONObject(i);
                                String app_id = Util.null2String(cgxxObj.get("app_id"));
                                System.out.println("app_id:"+app_id);
                                String purchase_type = Util.null2String(cgxxObj.get("purchase_type"));
                                String cglx = HT_SelectField.getSelectItemValue(cglxfieldis,purchase_type) ;
                                bb.writeLog("cglx:"+cglx);
                                String c_money = Util.null2String(cgxxObj.get("c_money"));

                                String number_units = Util.null2String(cgxxObj.get("number_units"));
                                String buy_type = Util.null2String(cgxxObj.get("buy_type"));
                                String cgfs = HT_SelectField.getSelectItemValue(cgfsfieldis,buy_type) ;
                                bb.writeLog("cgfs:"+cgfs);
                                String y_department_id = Util.null2String(cgxxObj.get("y_department_id"));
                                List<Map<String,Object>> ysbmList = new ArrayList<Map<String,Object>>();
                                String ysbm = "" ;
                                if(!"".equals(y_department_id))
                                {
                                    Map<String,Object> ysbmMap = null;
                                    y_department_id = "'"+y_department_id.replaceAll(",","','")+"'";
                                    String sql = " select id,departmentname from hrmdepartment l where l.departmentcode in("+y_department_id+")";
                                    rs.execute(sql);
                                    while (rs.next()){
                                        String deptid = Util.null2String(rs.getString("id"));
                                        String departmentname = Util.null2String(rs.getString("departmentname"));
                                        ysbm += ysbm=="" ? deptid : ","+deptid ;

                                        ysbmMap = new HashMap<String,Object>();
                                        ysbmMap.put("id",deptid);
                                        ysbmMap.put("name",departmentname);
                                        ysbmList.add(ysbmMap);
                                    }
                                }
                                String c_content = Util.null2String(cgxxObj.get("c_content"));
                                String cgzd = Util.null2String(cgxxObj.get("purchase_system"));

                                String purchase_terms = Util.null2String(cgxxObj.get("purchase_terms"));
                                String team_id = Util.null2String(cgxxObj.get("team_id"));
                                String c_remark = Util.null2String(cgxxObj.get("c_remark"));

                                String cgfzr = "" ;
                                List<Map<String,Object>> cgfzrList = new ArrayList<Map<String,Object>>();
                                String caigoufuzerenid = Util.null2String(cgxxObj.get("caigoufuzerenid"));
                                if(!"".equals(caigoufuzerenid))
                                {
                                    Map<String,Object> cgfzrMap = null;
                                    String sql = " select id,lastname from hrmresource where workcode='"+caigoufuzerenid+"' and belongto is null ";
                                    rs.execute(sql);
                                    while (rs.next()){
                                        String hrmid = Util.null2String(rs.getString("id"));
                                        String lastname = Util.null2String(rs.getString("lastname"));
                                        cgfzr += cgfzr=="" ? hrmid : ","+hrmid ;
                                        cgfzrMap = new HashMap<String,Object>();
                                        cgfzrMap.put("id",hrmid);
                                        cgfzrMap.put("name",lastname);
                                        cgfzrList.add(cgfzrMap);
                                    }
                                }
                                String project_name = Util.null2String(cgxxObj.get("project_name"));

                                cgxxMap = new HashMap<String,Object>();
                                cgxxMap.put("appid",app_id);
                                cgxxMap.put("cglx",cglx);
                                cgxxMap.put("cgfs",cgfs);
                                cgxxMap.put("ysbm",ysbm);
                                cgxxMap.put("ysbmObj",ysbmList);
                                cgxxMap.put("ysje",c_money);
                                cgxxMap.put("sl",number_units);
                                cgxxMap.put("cgfzr",cgfzr);
                                cgxxMap.put("cgfzrObj",cgfzrList);
                                cgxxMap.put("cgnr",c_content);
                                cgxxMap.put("cgzd",cgzd);
                                cgxxMap.put("ejcgzd",purchase_terms);
                                cgxxMap.put("gys",team_id);
                                cgxxMap.put("bz",c_remark);
                                cgxxMap.put("xmmczw",project_name);
                                cgxxlist.add(cgxxMap);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
        }
        System.out.println("cgxxlist:"+cgxxlist.size());
        apimap.put("cgxxlist",cgxxlist);
        apimap.put("count",cgxxlist.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");
        HT_SelectField HT_SelectField = new HT_SelectField();
        PropBean pb = new PropBean();

        String workflowid = pb.getActiveWorkflowIdByUnNumber("itcgsq");
        System.out.println("workflowid:"+workflowid);
        String cglxfieldis = HT_SelectField.getbillFieldByWorkflowid(workflowid,"cglx","dt5");
        String cgfsfieldis = HT_SelectField.getbillFieldByWorkflowid(workflowid,"cgfs","dt5");

        System.out.println("cglxfieldis:"+cglxfieldis);
        System.out.println("cgfsfieldis:"+cgfsfieldis);

        List<Map<String,Object>> cgxxlist = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        RecordSet rs = new RecordSet();
        String usercode = "12977" ;
        String workcode = "" ;
        if(!"".equals(usercode)){
            String sql = " select workcode from hrmresource where id="+usercode+" and belongto is null ";
            rs.execute(sql);
            if(rs.next()){
                workcode = Util.null2String(rs.getString("workcode"));
            }
        }

        com.engine.htsc.itcglc.cmd.cgplanListCmd cgplanListCmd = new com.engine.htsc.itcglc.cmd.cgplanListCmd(params);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("badge",workcode);
        Map<String, String> headers = new HashMap<String, String>();
        String url = "http://168.61.69.225:8080/jtxt/ITProjects/getNonstandardizedItProcurement" ;

        String response = cgplanListCmd.sendPost(url,jsonObject.toJSONString(),headers);
        System.out.println("response:"+response);

        System.out.println("response:"+response);
        if(!"".equals(response))
        {
            JSONObject responseJson = JSONObject.parseObject(response);
            if(!"".equals(responseJson)){
                if(responseJson.containsKey("itsystemPurchaseData")){

                    JSONObject cgxxObject = responseJson.getJSONObject("itsystemPurchaseData");
                    if(cgxxObject !=null){
                        JSONArray cgxxArray = cgxxObject.getJSONArray("item");
                        Map<String,Object> cgxxMap = null;

                        for(int i=0;i<cgxxArray.size();i++)
                        {
                            JSONObject cgxxObj = cgxxArray.getJSONObject(i);
                            String app_id = Util.null2String(cgxxObj.get("app_id"));
                            System.out.println("app_id:"+app_id);
                            String purchase_type = Util.null2String(cgxxObj.get("purchase_type")).trim();
                            String cglx = HT_SelectField.getSelectItemValue(cglxfieldis,purchase_type) ;

                            String c_money = Util.null2String(cgxxObj.get("c_money"));

                            String number_units = Util.null2String(cgxxObj.get("number_units"));
                            String buy_type = Util.null2String(cgxxObj.get("buy_type")).trim();
                            String cgfs = HT_SelectField.getSelectItemValue(cgfsfieldis,buy_type) ;

                            System.out.println("cglx:"+cglx);
                            System.out.println("cgfs:"+cgfs);
                            String y_department_id = Util.null2String(cgxxObj.get("y_department_id"));
                            String departmentname = "" ;
                            if(!"".equals(y_department_id))
                            {
                                y_department_id = "'"+y_department_id.replaceAll(",","','")+"'";
                                String sql = " select id,departmentname from hrmdepartment l where l.departmentcode in("+y_department_id+")";
                                rs.execute(sql);
                                if (rs.next()){
                                    departmentname = Util.null2String(rs.getString("departmentname"));
                                }
                            }
                            String c_content = Util.null2String(cgxxObj.get("c_content"));
                            String cgzd = Util.null2String(cgxxObj.get("purchase_system"));

                            String purchase_terms = Util.null2String(cgxxObj.get("purchase_terms"));
                            String team_id = Util.null2String(cgxxObj.get("team_id"));
                            String c_remark = Util.null2String(cgxxObj.get("c_remark"));
                            String caigoufuzeren = Util.null2String(cgxxObj.get("caigoufuzeren"));
                            String project_name = Util.null2String(cgxxObj.get("project_name"));

                            cgxxMap = new HashMap<String,Object>();
                            cgxxMap.put("appid",app_id);
                            cgxxMap.put("cglx",cglx);
                            cgxxMap.put("cgfs",cgfs);
                            cgxxMap.put("ysbm",departmentname);
                            cgxxMap.put("ysje",c_money);
                            cgxxMap.put("sl",number_units);
                            cgxxMap.put("cgfzr",caigoufuzeren);
                            cgxxMap.put("cgnr",c_content);
                            cgxxMap.put("cgzd",cgzd);
                            cgxxMap.put("ejcgzd",purchase_terms);
                            cgxxMap.put("gys",team_id);
                            cgxxMap.put("bz",c_remark);
                            cgxxMap.put("xmmczw",project_name);
                            cgxxlist.add(cgxxMap);
                        }
                    }
                }
            }
        }
    }
}
