package com.engine.htsc.itcglc.cmd;

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.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.itcglc.action.ItcglcCreateCgrwdAction;
import weaver.interfaces.htsc.util.HT_WorkflowInfo;

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

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

    public CreateRequestCmd(Map<String, Object> params, User user) {
        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();
        int isok = 0;
        HT_WorkflowInfo HT_WorkflowInfo = new HT_WorkflowInfo();
        Map<String, Object> apimap = new HashMap<String, Object>();
        String requestid = Util.null2String(params.get("requestid"));
        bb.writeLog("requestid:"+requestid);
        ItcglcCreateCgrwdAction ItcglcCreateCgrwdAction = new ItcglcCreateCgrwdAction();
        try{
            String formtable = HT_WorkflowInfo.getFormTableByRequestid(requestid);
            String requestname = HT_WorkflowInfo.getRequestnameByRequestid(requestid);
            int dt5count = 0;
            String dtsql = " select * from "+formtable+" t inner join "+formtable+"_dt5 l on l.mainid = t.id where requestid="+requestid;
            rs.execute(dtsql);
            while(rs.next()){
                dt5count++;
            }
            if(dt5count >0){
                isok = ItcglcCreateCgrwdAction.createRequest(requestid,formtable,requestname);
                if(isok > 0){

                    int loginid = user.getUID();
                    PropBean pb = new PropBean();
                    String yjngr = pb.getPropName("cgd_yj_ngr");
                    String fyjngr = pb.getPropName("cgd_fyj_ngr");

                    int yj_bool = 0 ;
                    int fyj_bool = 0;
                    String yjngrid = "" ;
                    String fyjngrid = "" ;
                    if(!"".equals(yjngr)) {
                        String hrmSql = " select id from hrmresource where workcode='"+yjngr+"' and belongto is null" ;
                        rs.execute(hrmSql);
                        if(rs.next()){
                            yjngrid = Util.null2String(rs.getString("id")) ;
                        }
                        ;
                        String selSql = " select requestid from workflow_currentoperator where requestid="+requestid+" and userid="+yjngrid ;
                        rs.execute(selSql);
                        if(rs.next()){
                            yj_bool++;
                        }
                    }
                    if(!"".equals(fyjngr)) {

                        String hrmSql = " select id from hrmresource where workcode='"+fyjngr+"' and belongto is null" ;
                        rs.execute(hrmSql);
                        if(rs.next()){
                            fyjngrid = Util.null2String(rs.getString("id")) ;
                        }

                        String selSql = " select requestid from workflow_currentoperator where requestid="+requestid+" and userid="+fyjngrid ;
                        rs.execute(selSql);
                        if(rs.next()){
                            fyj_bool++;
                        }
                    }

                    if(yj_bool ==0 || fyj_bool==0)
                    {
                        String currentnodeid = "" ;
                        String sql = " select currentnodeid from workflow_requestbase h where requestid= "+requestid;
                        rs.execute(sql);
                        if (rs.next()){
                            currentnodeid  = Util.null2String(rs.getString("currentnodeid"));
                        }
                        if(!"".equals(currentnodeid)){

                            String curr_requestid = "" ;
                            String groupid = "" ;
                            String workflowid = "" ;
                            String workflowtype = "" ;
                            String nodeid = "" ;
                            String groupdetailid = "" ;

                            String selSql = " select requestid,groupid,workflowid,workflowtype,nodeid,groupdetailid from workflow_currentoperator where requestid="+curr_requestid+" and nodeid="+currentnodeid+" order by showorder desc" ;
                            rs.execute(selSql);
                            if(rs.next()){
                                curr_requestid = Util.null2String(rs.getString("requestid"));
                                groupid = Util.null2String(rs.getString("groupid"));
                                workflowid = Util.null2String(rs.getString("workflowid"));
                                workflowtype = Util.null2String(rs.getString("workflowtype"));
                                nodeid = Util.null2String(rs.getString("nodeid"));
                                groupdetailid = Util.null2String(rs.getString("groupdetailid"));
                            }

                            String agentorbyagentid = "-1";
                            String agenttype = "0";
                            String showorder = "1";
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                            SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");//设置日期格式

                            String receivedate = sdf1.format(new Date()) ;
                            String receivetime = sdf2.format(new Date()) ;
                            if(yj_bool ==0){
                                sql = " select max(showorder)+1 as showorder from workflow_currentoperator where requestid= "+curr_requestid+" and nodeid="+currentnodeid;
                                bb.writeLog("sql:"+sql);
                                rs.execute(sql);
                                if(rs.next()){
                                    showorder = Util.null2String(rs.getString("showorder"));
                                }

                                sql =   " insert into workflow_currentoperator(requestid,userid,groupid,workflowid,workflowtype,usertype,nodeid,agentorbyagentid,\n" +
                                        " agenttype,showorder,receivedate,receivetime,viewtype,iscomplete,islasttimes,groupdetailid,needwfback,isremark,preisremark)\n" +
                                        " values("+curr_requestid+","+yjngrid+","+groupid+","+workflowid+","+workflowtype+",0,"+nodeid+","+agentorbyagentid+","+agenttype+","+showorder+",'"+receivedate+"','"+receivetime+"',0,0,1,"+groupdetailid+",1,8,8)" ;
                                bb.writeLog("sql:"+sql);
                                rs.executeUpdate(sql);
                            }

                            if(fyj_bool ==0){

                                sql = " select max(showorder)+1 as showorder from workflow_currentoperator where requestid= "+curr_requestid+" and nodeid="+currentnodeid;
                                bb.writeLog("sql:"+sql);
                                rs.execute(sql);
                                if(rs.next()){
                                    showorder = Util.null2String(rs.getString("showorder"));
                                }

                                sql =   " insert into workflow_currentoperator(requestid,userid,groupid,workflowid,workflowtype,usertype,nodeid,agentorbyagentid,\n" +
                                        " agenttype,showorder,receivedate,receivetime,viewtype,iscomplete,islasttimes,groupdetailid,needwfback,isremark,preisremark)\n" +
                                        " values("+curr_requestid+","+fyjngrid+","+groupid+","+workflowid+","+workflowtype+",0,"+nodeid+","+agentorbyagentid+","+agenttype+","+showorder+",'"+receivedate+"','"+receivetime+"',0,0,1,"+groupdetailid+",1,8,8)" ;
                                bb.writeLog("sql:"+sql);
                                rs.executeUpdate(sql);
                            }
                        }
                    }
                }
            }else{
                isok = -1000;
            }

        }catch (Exception e){
            System.out.println(e);
        }
        apimap.put("msg",isok+"");
        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;
    }

}
