package com.engine.htsc.itlxlc.cmd;

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.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.io.IOException;
import java.util.*;


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

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

    @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=================ItlxlcProjectInfoCmd" );
        Map<String, Object> apimap = new HashMap<String, Object>();

        String projCode = Util.null2String(params.get("projectCode"));
        int nf = Util.getIntValue(Util.null2String(params.get("nf")));
        bb.writeLog("nf:"+nf);

        PropBean pb = new PropBean();
        String url  = pb.getPropName("ItlxlcProjectDetailUrl");
        bb.writeLog("url:"+url);

        HTUtil htutil = new HTUtil();
        String token = htutil.getAppToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("JTXT-AUTH-TOKEN", token);
        headers.put("JTXT-AUTH-TYPE", "APP");

        JSONObject jsonObject = new JSONObject();
        int userid = user.getUID();
        String workcode = "";
        String sql = " select workcode from hrmresource where id= "+userid;
        rs.execute(sql);
        if(rs.next()){
            workcode = Util.null2String(rs.getString("workcode"));
        }
        try{
            //011516
            jsonObject.put("badge",workcode);
            jsonObject.put("projectCode",projCode);
            String response = sendPost(url,jsonObject.toJSONString(),headers);
            bb.writeLog("response:"+response);
            if(!"".equals(response))
            {
                JSONObject retJson = JSONObject.parseObject(response);
                String retCode = retJson.getString("retCode");
                if("0000".equals(retCode)){
                    List<Map<String,Object>> budgetlist = new ArrayList<Map<String,Object>>();
//                List<Map<String,Object>> yearlist = new ArrayList<Map<String,Object>>();

                    List<Map<String,Object>> nlist = new ArrayList<Map<String,Object>>();
                    List<Map<String,Object>> n1list = new ArrayList<Map<String,Object>>();
                    List<Map<String,Object>> n2list = new ArrayList<Map<String,Object>>();

                    String operatorId = retJson.getString("operatorId");
                    apimap.put("operatorId",operatorId);

                    String pmId = retJson.getString("pmId");

                    String hrmid = "" ;
                    String lastname = "" ;
                    if(!"".equals(pmId))
                    {
                        sql = " select id,lastname from hrmresource where workcode='"+pmId+"' and belongto is null ";
                        rs.execute(sql);
                        if(rs.next()){
                            hrmid = Util.null2String(rs.getString("id"));
                            lastname = Util.null2String(rs.getString("lastname"));
                        }
                    }
                    apimap.put("lastname",lastname);
                    apimap.put("hrmid",hrmid);
                    apimap.put("pmId",pmId);

                    String projectCode = retJson.getString("projectCode");

                    String itemNum = retJson.getString("itemNum");
                    apimap.put("itemNum",itemNum);
                    bb.infoLog("itemNum:",itemNum);

                    if(!"".equals(projectCode) && projectCode.indexOf("&&")>0){

                        String projectCode_new = "";
                        String sjghxm = "" ;
                        String xmmczw = "" ;
                        String[] projectInfo = projectCode.split("&&");
                        if(projectInfo.length >= 1){
                            projectCode_new = projectInfo[0];
                        }
                        if(projectInfo.length >= 2){
                            xmmczw = projectInfo[1];
                        }
                        if(projectInfo.length >= 3){
                            sjghxm = projectInfo[2];
                        }
//                    String projectCode_new = projectCode.substring(0,projectCode.indexOf("&&"));
//                    String sjghxm = projectCode.substring(projectCode.indexOf("&&")+2);

                        apimap.put("projectCode",projectCode_new);
                        apimap.put("sjghxm",sjghxm);
                        apimap.put("xmmczw",xmmczw);
                    }


//                String jcxinxi = retJson.getString("jcxinxi");
//                apimap.put("jcxinxi",jcxinxi);

                    String totalMoney = retJson.getString("totalMoney");
                    apimap.put("totalMoney",totalMoney);
                    if(!"".equals(totalMoney)){
                        try{
                            double du_totalMoney = Double.parseDouble(totalMoney);
                            if(du_totalMoney >0){
                                apimap.put("sjfy","0");
                            }else{
                                apimap.put("sjfy","1");
                            }
                        }catch (Exception e){

                        }
                    }

//                String totalMoneyNoTax = retJson.getString("totalMoneyNoTax");
//                apimap.put("totalMoneyNoTax",totalMoneyNoTax);

                    String deptids = "" ;
                    Map<String,Object> deptMap =null;
                    List<Map<String,Object>> specialList = new ArrayList<Map<String,Object>>();
                    List<String> deptList = new ArrayList<String>();
                    if(retJson.containsKey("budgetData")){
                        String budgetData = retJson.getString("budgetData").replaceAll("\n","");
                        if(!"".equals(budgetData) && budgetData.startsWith("<?xml")){
                            Document doc = null;
                            try {
                                doc = DocumentHelper.parseText(budgetData);
                            } catch (DocumentException e) {
                                e.printStackTrace();
                            }
                            Element topEle = doc.getRootElement();
                            List<Element> nodes = topEle.elements("Item");
                            Map<String,Object> dataMap = null;

                            for (Iterator it = nodes.iterator(); it.hasNext();)
                            {
                                Element elm = (Element) it.next();

                                String BudgetYear = elm.elementTextTrim("BudgetYear");

                                String BudgetNoAmt = elm.elementTextTrim("BudgetNoAmt");

                                String BudgetId = elm.elementTextTrim("BudgetId");



                                String BudgetDep = elm.elementTextTrim("BudgetDep");
                                String deptid = "" ;
                                String deptname = "" ;


                                String BudgetAmt = elm.elementTextTrim("BudgetAmt");

                                String BudgetAcct = elm.elementTextTrim("BudgetAcct");

                                if(!"".equals(BudgetDep))
                                {

                                    sql = " select id,departmentname from hrmdepartment where departmentcode='"+BudgetDep+"' ";
                                    rs.execute(sql);
                                    if(rs.next()){
                                        deptid = Util.null2String(rs.getString("id"));
                                        deptname = Util.null2String(rs.getString("departmentname"));
                                    }
                                }

                                String yskmmc = "";
                                if(!"".equals(BudgetAcct)){
                                    sql = " select yskmmc from uf_kmpz where yskmbm='"+BudgetAcct+"' ";
                                    rs.execute(sql);
                                    if(rs.next()){
                                        yskmmc = Util.null2String(rs.getString("yskmmc"));
                                    }
                                }

                                dataMap = new HashMap<String,Object>();
                                dataMap.put("BudgetAcct",BudgetAcct);
                                dataMap.put("BudgetYear",BudgetYear);
                                dataMap.put("BudgetId",BudgetId);
                                dataMap.put("yskmmc",yskmmc);
                                dataMap.put("yskmbm",BudgetAcct);
                                dataMap.put("BudgetAmt",BudgetAmt);
                                dataMap.put("BudgetDep",BudgetDep);
                                dataMap.put("deptid",deptid);
                                dataMap.put("deptname",deptname);

                                if(BudgetYear.equals(Util.null2String(nf)))
                                {
                                    nlist.add(dataMap);

                                    if(!deptList.contains(deptid)){
                                        deptList.add(deptid);
                                        deptids += deptids =="" ? deptid : ","+deptid ;
                                        deptMap = new HashMap<String,Object>();
                                        deptMap.put("id",deptid);
                                        deptMap.put("name",deptname);
                                        specialList.add(deptMap);
                                    }
                                }

                                if(BudgetYear.equals(Util.null2String(nf+1)))
                                {
                                    n1list.add(dataMap);

                                    if(!deptList.contains(deptid)){
                                        deptList.add(deptid);
                                        deptids += deptids =="" ? deptid : ","+deptid ;
                                        deptMap = new HashMap<String,Object>();
                                        deptMap.put("id",deptid);
                                        deptMap.put("name",deptname);
                                        specialList.add(deptMap);
                                    }
                                }

                                if(BudgetYear.equals(Util.null2String(nf+2)))
                                {
                                    n2list.add(dataMap);

                                    if(!deptList.contains(deptid)){
                                        deptList.add(deptid);
                                        deptids += deptids =="" ? deptid : ","+deptid ;
                                        deptMap = new HashMap<String,Object>();
                                        deptMap.put("id",deptid);
                                        deptMap.put("name",deptname);
                                        specialList.add(deptMap);
                                    }

                                }


                            }
                        }
                    }

                    apimap.put("nlist",nlist);
                    apimap.put("n1list",n1list);
                    apimap.put("n2list",n2list);

                    apimap.put("ysbmvalue",deptids);
                    apimap.put("ysbmspecial",specialList);



                    if(retJson.containsKey("yearMoney")){
                        String yearMoney = retJson.getString("yearMoney").replaceAll("\n","");
                        if(!"".equals(yearMoney) && yearMoney.startsWith("<?xml")){
                            Document doc = null;
                            try {
                                doc = DocumentHelper.parseText(yearMoney);
                            } catch (DocumentException e) {
                                e.printStackTrace();
                            }

                            Element topEle = doc.getRootElement();
                            List<Element> nodes = topEle.elements("Item");
                            for (Iterator it = nodes.iterator(); it.hasNext();)
                            {
                                Element elm = (Element) it.next();
                                String Year = elm.elementTextTrim("Year");
                                if(Year.equals(Util.null2String(nf)))
                                {
                                    String BudgetMoney = elm.elementTextTrim("BudgetMoney");

                                    String BudgetMoneyNoTax = elm.elementTextTrim("BudgetMoneyNoTax");

                                    apimap.put("ntotalMoney",BudgetMoney);
                                }

                                if(Year.equals(Util.null2String(nf+1)))
                                {
                                    String BudgetMoney = elm.elementTextTrim("BudgetMoney");
                                    apimap.put("n1totalMoney",BudgetMoney);
                                }

                                if(Year.equals(Util.null2String(nf+2)))
                                {
                                    String BudgetMoney = elm.elementTextTrim("BudgetMoney");
                                    apimap.put("n2totalMoney",BudgetMoney);
                                }

                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            bb.writeLog("e---"+e);
        }

        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/getItProjectDetail" ;
        Map<String,String> headMap = new HashMap<String,String>();

        HTUtil htutil = new HTUtil();
        String token = htutil.getAppToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("JTXT-AUTH-TOKEN", token);
        headers.put("JTXT-AUTH-TYPE", "APP");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("badge","011516");
        jsonObject.put("projectCode","620072");

        ItlxlcProjectInfoCmd ItlxlcProjectCmd = new ItlxlcProjectInfoCmd(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 operatorId = retJson.getString("operatorId");
                System.out.println("operatorId:"+operatorId);

                String pmId = retJson.getString("pmId");
                System.out.println("pmId:"+pmId);

                String projectCode = retJson.getString("projectCode");
                System.out.println("projectCode:"+projectCode);

                String jcxinxi = retJson.getString("jcxinxi");
                System.out.println("jcxinxi:"+jcxinxi);

                String totalMoney = retJson.getString("totalMoney");
                System.out.println("totalMoney:"+totalMoney);

                String totalMoneyNoTax = retJson.getString("totalMoneyNoTax");
                System.out.println("totalMoneyNoTax:"+totalMoneyNoTax);

                String budgetData = retJson.getString("budgetData").replaceAll("\n","");
                System.out.println("budgetData:"+budgetData);
                if(!"".equals(budgetData) && budgetData.startsWith("<?xml")){
                    Document doc = null;
                    try {
                        doc = DocumentHelper.parseText(budgetData);
                    } 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 BudgetAcct = elm.elementTextTrim("BudgetAcct");
                        System.out.println("BudgetAcct:" + BudgetAcct);
                        String BudgetYear = elm.elementTextTrim("BudgetYear");
                        System.out.println("BudgetYear:" + BudgetYear);

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

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

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

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

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

//                        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);
                    }
                }



                String yearMoney = retJson.getString("yearMoney").replaceAll("\n","");
                System.out.println("yearMoney:"+yearMoney);
                if(!"".equals(yearMoney) && yearMoney.startsWith("<?xml")){
                    Document doc = null;
                    try {
                        doc = DocumentHelper.parseText(yearMoney);
                    } 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 Year = elm.elementTextTrim("Year");
                        System.out.println("Year:" + Year);
                        String BudgetMoney = elm.elementTextTrim("BudgetMoney");
                        System.out.println("BudgetMoney:" + BudgetMoney);

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

//                        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;
    }




}
