package com.engine.htsc.cgrwd.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 com.engine.htsc.itlxlc.util.RequestShareUtil;
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 CgrwdProjectInfoCmd extends AbstractCommonCommand<Map<String, Object>> {

    public CgrwdProjectInfoCmd(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();
        String formid = Util.null2String(params.get("formid"));
        String cglxfieldis = "";
        String cglxsql = " select id from workflow_billfield where billid="+formid+" and fieldname='cglx' " ;
        rs.execute(cglxsql);
        if(rs.next()){
            cglxfieldis = Util.null2String(rs.getString("id"));
        }

        bb.writeLog("cglxfieldis:"+cglxfieldis);
        String cgfsfieldis = "";
        String cgfssql = " select id from workflow_billfield where billid="+formid+" and fieldname='cgfs' " ;
        rs.execute(cgfssql);
        if(rs.next()){
            cgfsfieldis = Util.null2String(rs.getString("id"));
        }
        bb.writeLog("cgfsfieldis:"+cgfsfieldis);

        System.out.println( "in=================ItcglcProjectInfoCmd" );
        Map<String, Object> apimap = new HashMap<String, Object>();

        String projCode = Util.null2String(params.get("projectCode"));
        int nf = Util.getIntValue(Util.null2String(params.get("nf")));
        String userid = Util.null2String(user.getUID());
        System.out.println("userid:"+userid);

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

        Map<String, String> headers = new HashMap<String, String>();

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

        JSONObject jsonObject = new JSONObject();
        String workcode = "";
        String sql = " select workcode from hrmresource where id= "+userid;
        rs.execute(sql);
        if(rs.next()){
            workcode = Util.null2String(rs.getString("workcode"));
        }

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

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

        String hrmids = "" ;
        List<Map<String,Object>> hrmList = new ArrayList<Map<String,Object>>();
        String xcgwyhsy = "1";
        String projectNumber = "";
        String xmmczw = "" ;

        String requestids = "";
        try{
            //011516
            jsonObject.put("badge",workcode);
            jsonObject.put("projectCode",projCode);
            String response = sendPost(url,jsonObject.toJSONString(),headers);
            bb.writeLog("response:"+response);
            System.out.println("response:"+response);
            if(!"".equals(response))
            {
                JSONObject retJson = JSONObject.parseObject(response);
                String projectMasterPracticebadge = retJson.getString("projectMasterPracticebadge");
                Map<String,Object> hrmMap = null;
                if(!"".equals(projectMasterPracticebadge))
                {
                    sql = " select id,lastname from hrmresource where workcode='"+projectMasterPracticebadge+"' and belongto is null ";
                    rs.execute(sql);
                    while (rs.next()){
                        String hrmid = Util.null2String(rs.getString("id"));
                        String lastname = Util.null2String(rs.getString("lastname"));
                        hrmids += hrmids=="" ? hrmid : ","+hrmid ;
                        hrmMap = new HashMap<String,Object>();
                        hrmMap.put("id",hrmid);
                        hrmMap.put("name",lastname);
                        hrmList.add(hrmMap);
                    }
                }

                projectNumber = retJson.getString("projectNumber");
                System.out.println("projectNumber:"+projectNumber);
                xmmczw = retJson.getString("projectName");

                System.out.println("xmmczw:"+xmmczw);

                if(retJson.containsKey("otherWorkflowList1")){
                    JSONArray itlxsqArray = retJson.getJSONArray("otherWorkflowList1");
                    Map<String,Object> itlxsqMap = null;
                    for(int i=0;i<itlxsqArray.size();i++)
                    {
                        JSONObject itlxsqObj = itlxsqArray.getJSONObject(i);
                        String title = Util.null2String(itlxsqObj.get("title"));
                        String workFlowNum = Util.null2String(itlxsqObj.get("workFlowNum"));
                        String workFlowNumber = Util.null2String(itlxsqObj.get("workFlowNumber"));
                        String itlxsqurl = Util.null2String(itlxsqObj.get("url"));
                        if(!itlxsqurl.startsWith("http")){
                            String OAHOST = pb.getPropName("OAHOST");
                            itlxsqurl = OAHOST +itlxsqurl+"&ismonitor=1&_key=z5uz9j";

                            if(itlxsqurl.indexOf("requestid")>-1){
                                String requsturl = itlxsqurl.substring(itlxsqurl.indexOf("requestid"));
                                if(requsturl.indexOf("&") > -1){
                                    String itlx_requetsid = requsturl.substring(10,requsturl.indexOf("&"));
                                    if(!"".equals(itlx_requetsid) && !"1".equals(itlx_requetsid)){
                                        int num = getWorkflowStoped(itlx_requetsid);
                                        if(num == 0){
                                            requestids += requestids=="" ? itlx_requetsid : ","+itlx_requetsid ;

                                            itlxsqMap = new HashMap<String,Object>();
                                            itlxsqMap.put("title",title);
                                            itlxsqMap.put("workflownum",workFlowNum);
                                            itlxsqMap.put("workflownumber",workFlowNumber);
                                            itlxsqMap.put("url",itlxsqurl);
                                            itlxsqlist.add(itlxsqMap);

                                        }
                                    }
                                }else{
                                    String itlx_requetsid = requsturl.substring(10);
                                    if(!"".equals(itlx_requetsid) && !"1".equals(itlx_requetsid)){
                                        int num = getWorkflowStoped(itlx_requetsid);
                                        if(num == 0){
                                            requestids += requestids=="" ? itlx_requetsid : ","+itlx_requetsid ;

                                            itlxsqMap = new HashMap<String,Object>();
                                            itlxsqMap.put("title",title);
                                            itlxsqMap.put("workflownum",workFlowNum);
                                            itlxsqMap.put("workflownumber",workFlowNumber);
                                            itlxsqMap.put("url",itlxsqurl);
                                            itlxsqlist.add(itlxsqMap);

                                        }
                                    }
                                }
                            }
                        }

                    }
                }

                if(retJson.containsKey("purchaseList"))
                {
                    JSONArray xgcglcArray = retJson.getJSONArray("purchaseList");
                    Map<String,Object> xgcglcMap = null;
                    for(int i=0;i<xgcglcArray.size();i++)
                    {
                        JSONObject xgcglcObj = xgcglcArray.getJSONObject(i);
                        String title = Util.null2String(xgcglcObj.get("title"));
                        String workFlowNum = Util.null2String(xgcglcObj.get("workFlowNum"));
                        String cgxglcurl = Util.null2String(xgcglcObj.get("url"));
                        if(!cgxglcurl.startsWith("http")){
                            String OAHOST = pb.getPropName("OAHOST");
                            cgxglcurl = OAHOST + cgxglcurl+"&ismonitor=1&_key=z5uz9j";

                            if(cgxglcurl.indexOf("requestid")>-1){
                                String requsturl = cgxglcurl.substring(cgxglcurl.indexOf("requestid"));
                                if(requsturl.indexOf("&") > -1){
                                    String cgxglc_requetsid = requsturl.substring(10,requsturl.indexOf("&"));
                                    if(!"".equals(cgxglc_requetsid) && !"1".equals(cgxglc_requetsid)){
                                        int num = getWorkflowStoped(cgxglc_requetsid);
                                        if(num == 0){
                                            requestids += requestids=="" ? cgxglc_requetsid : ","+cgxglc_requetsid ;

                                            xgcglcMap = new HashMap<String,Object>();
                                            xgcglcMap.put("title",title);
                                            xgcglcMap.put("workflownum",workFlowNum);
                                            xgcglcMap.put("url",cgxglcurl);
                                            xgcglclist.add(xgcglcMap);

                                        }
                                    }
                                }else{
                                    String cgxglc_requetsid = requsturl.substring(10);
                                    if(!"".equals(cgxglc_requetsid) && !"1".equals(cgxglc_requetsid)){
                                        int num = getWorkflowStoped(cgxglc_requetsid);
                                        if(num == 0){
                                            requestids += requestids=="" ? cgxglc_requetsid : ","+cgxglc_requetsid ;

                                            xgcglcMap = new HashMap<String,Object>();
                                            xgcglcMap.put("title",title);
                                            xgcglcMap.put("workflownum",workFlowNum);
                                            xgcglcMap.put("url",cgxglcurl);
                                            xgcglclist.add(xgcglcMap);

                                        }
                                    }
                                }
                            }
                        }

                    }
                }

                if(retJson.containsKey("itsystemPurchaseData")){
                    JSONObject cgxxObject = retJson.getJSONObject("itsystemPurchaseData");
                    System.out.println("cgxxObject:"+cgxxObject);
                    if(cgxxObject !=null){
                        JSONArray cgxxArray = cgxxObject.getJSONArray("item");
                        System.out.println("cgxxArray:"+cgxxArray.size());
                        Map<String,Object> cgxxMap = null;

                        int d_xcgwyhsy = 0;
                        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 = "" ;
                            if (!"".equals(purchase_type)) {
                                sql = " select selectvalue from workflow_selectitem where fieldid="+cglxfieldis+" and selectname = '"+purchase_type+"'" ;
                                rs.execute(sql);
                                if (rs.next()){
                                    cglx = Util.null2String(rs.getString("selectvalue"));
                                }
                            }

                            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 = "" ;
                            if (!"".equals(buy_type)) {
                                sql = " select selectvalue from workflow_selectitem where fieldid="+cgfsfieldis+" and selectname = '"+buy_type+"'" ;
                                rs.execute(sql);
                                if (rs.next()){
                                    cgfs = Util.null2String(rs.getString("selectvalue"));
                                }
                            }


                            if(!"".equals(c_money))
                            {
                                if(Util.getDoubleValue(c_money)>=2000000)
                                {
                                    if("0".equals(cgfs) || "1".equals(cgfs) || "4".equals(cgfs) || "5".equals(cgfs)){

                                        d_xcgwyhsy++;
                                    }
                                }
                            }

                            //String y_department = Util.null2String(cgxxObj.get("y_department"));
                            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(",","','")+"'";
                                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 cgzd = "" ;
//                    if (!"".equals(purchase_system)) {
//                        sql = " select selectvalue from workflow_selectitem where fieldid="+cgzdfieldis+" and selectname = '"+purchase_system+"'" ;
//                        rs.execute(sql);
//                        if (rs.next()){
//                            cgzd = Util.null2String(rs.getString("selectvalue"));
//                        }
//                    }
                            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 purchaseNum = Util.null2String(cgxxObj.get("purchaseNum"));

                            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;
                                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 caigoufuzeren = Util.null2String(cgxxObj.get("caigoufuzeren"));
                            String project_name = Util.null2String(cgxxObj.get("project_name"));
//                String it_project_num = Util.null2String(cgxxObj.get("it_project_num"));
//                String beforehandPublicity = Util.null2String(cgxxObj.get("beforehandPublicity"));

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

                            System.out.println("4444444");
                        }

                        if(d_xcgwyhsy > 0)
                        {
                            xcgwyhsy = "0";
                        }
                    }
                }

                if(retJson.containsKey("projectDetail")){
                    JSONObject projDetailObj = retJson.getJSONObject("projectDetail");
                    if(projDetailObj !=null)
                    {
                        String budgetData = projDetailObj.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 BudgetYear = elm.elementTextTrim("BudgetYear");
                                System.out.println("BudgetYear:" + BudgetYear);

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

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



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


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

                                String BudgetAcct = elm.elementTextTrim("BudgetAcct");
                                System.out.println("BudgetAcct:" + 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(BudgetYear.equals(Util.null2String(nf+1)))
                                {
                                    n1list.add(dataMap);
                                }

                                if(BudgetYear.equals(Util.null2String(nf+2)))
                                {
                                    n2list.add(dataMap);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            System.out.println("e---"+e);
            bb.writeLog("e--:"+e);
        }


        if(!"".equals(requestids)){
            try{
                RequestShareUtil RequestShareUtil = new RequestShareUtil();
                bb.writeLog("ItcglcProjectInfoCmd--RequestShareUtil--"+requestids);
                RequestShareUtil.addShare(Util.null2String(userid),requestids);
            }catch (Exception e){
                bb.writeLog("e---"+e);
            }
        }

        System.out.println("cgxxlist:"+cgxxlist.size());
        apimap.put("value",hrmids);
        apimap.put("specialobj",hrmList);
        apimap.put("xmbh",projectNumber);
        apimap.put("xcgwyhsy",xcgwyhsy);
        apimap.put("xmmczw",xmmczw);

        apimap.put("xglcoa",requestids);

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

        apimap.put("itlxsqlist",itlxsqlist);
        apimap.put("xgcglclist",xgcglclist);
        apimap.put("cgxxlist",cgxxlist);
        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 int getWorkflowStoped(String requestid){
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        int i = 0;
        try{
            String sql = " select requestid from workflow_requestbase t\n" +
                         " where t.requestid="+requestid+" and (t.isstopped=1 or t.currentnodeid in(select id from workflow_nodebase k where k.unnumber in（'itcgsq_zz','itlxsq_zz'） )) " ;
            rs.execute(sql);
            if (rs.next()){
                i++;
            }
            bb.writeLog("requestid:"+requestid);
            bb.writeLog("sql:"+sql);
            bb.writeLog("i:"+i);

        }catch (Exception e){
        }
        return i;
    }

    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");
        Map<String, Object> params=new HashMap<>();
        params.put("usercode","011516");
        params.put("projectCode","621041");
        params.put("nf","2021");

        User user = new User(5620);
        CgrwdProjectInfoCmd ItcglcProjectInfoCmd = new CgrwdProjectInfoCmd(user,params);
        CommandContext ceshi = new CommandContext(null,null);
        ItcglcProjectInfoCmd.execute(ceshi);
    }




}
