package weaver.interfaces.htsc.itlxlc.action;

import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.itlxlc.cmd.ItlxlcProjectInfoCmd;
import com.weaver.general.BaseBean;
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.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

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

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-09-24
 * @Description: 申请节点提交后删除明细表数据
 * @ModifyLog:
 *
 * 总部重要事项 拟稿节点提交执行
 **/

public class ItlxlcUpdateContractSysAction extends BaseBean implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {
        RecordSet rs = new RecordSet();
        String requestid = requestInfo.getRequestid();
        System.out.println( "----ItlxlcUpdateContractSysAction-------" + requestid );
        String tablename = requestInfo.getRequestManager().getBillTableName();//主表
        try {

            PropBean pb = new PropBean();
            String url = pb.getPropName("ItlxlcUrl");;

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

            String lcbh = "" ;
            String xmfzrname = "" ;
            String xmfzrcode = "" ;
            String lxjewyhs = "" ;
            String xmmczw = "" ;
            String ngrq = "" ;

            String sql =" select t.id,t.xmmc,t.xmmczw,t.xmfzr,t.lcbh,t.ngrq,t.lxjewyhs,\n" +
                        " h.lastname,h.workcode\n" +
                        " from "+tablename+" t \n" +
                        " left join hrmresource h on h.id = to_char(t.xmfzr)\n" +
                        " where t.requestid =" + requestid + "";

            writeLog( sql );
            rs.executeQuery( sql );
            if(rs.next())
            {
                lcbh = Util.null2String( rs.getString( "lcbh" ) );//
                xmmczw = Util.null2String( rs.getString( "xmmczw" ) );//
                lxjewyhs = Util.null2String( rs.getString( "lxjewyhs" ) );//
                xmfzrname = Util.null2String( rs.getString( "lastname" ) );//
                xmfzrcode = Util.null2String( rs.getString( "workcode" ) );//
                ngrq = Util.null2String( rs.getString( "ngrq" ));//
            }

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

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("workFlowNum",lcbh);
            jsonObject.put("projectName",xmmczw);
            jsonObject.put("totalSmallMoney",lxjewyhs);
            jsonObject.put("projectDirectorName",xmfzrname);
            jsonObject.put("projectDirector",xmfzrcode);
            jsonObject.put("requestId",requestid);
            jsonObject.put("draftDate",ngrq+":00");

            String response = sendPost(url,jsonObject.toJSONString(),headers);
            System.out.println(response);
            try{
                JSONObject retJson = JSONObject.parseObject(response);
                String resultState = retJson.getString("resultState");
                if("0".equals(resultState)){
                    return Action.SUCCESS;
                }else{
                    String msg = retJson.getString("msg");
                    requestInfo.getRequestManager().setMessageid( "1111" );
                    requestInfo.getRequestManager().setMessagecontent(msg);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }catch (Exception e){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "更新状态接口异常" );
                return Action.FAILURE_AND_CONTINUE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writeLog( "异常参考:" + e );
            requestInfo.getRequestManager().setMessageid( "111111" );
            requestInfo.getRequestManager().setMessagecontent( "流程提交失败" );
            return Action.FAILURE_AND_CONTINUE;
        }
    }


    /***
     *
     * @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");

        String url  ="http://168.61.69.225:8080/jtxt/ITProjects/createItProjectForCtrct" ;
        Map<String,String> headMap = new HashMap<String,String>();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("workFlowNum","IT立项申请202106605356");
        jsonObject.put("projectName","跨部门多科目测试项目一");

        jsonObject.put("totalSmallMoney","6554917");
        jsonObject.put("projectDirectorName","马振徽");
        jsonObject.put("projectDirector","011516");
        jsonObject.put("requestId","7325320");
        jsonObject.put("draftDate","2021-06-09 15:51:59");

//        "workFlowNum":"IT立项申请202106605356",
//                "projectName":"跨部门多科目测试项目一",
//                "totalSmallMoney":"6554917",
//                "projectDirectorName":"马振徽",
//                "projectDirector":"011516",
//                "requestId":"requestId",
//                "draftDate":"2021-06-09 15:51:59"


        ItlxlcProjectInfoCmd ItlxlcProjectCmd = new ItlxlcProjectInfoCmd(null,null);
        String response = ItlxlcProjectCmd.sendPost(url,jsonObject.toJSONString(),headMap);
        System.out.println(response);

    }


}
