package weaver.interfaces.htsc.itlxlc.action;

import com.alibaba.fastjson.JSONObject;
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 weaver.conn.RecordSet;
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.HashMap;
import java.util.Map;

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

public class ItlxlcUpdateStatusAction extends BaseBean implements Action {

    private String proStatus;

    public String getProStatus() {
        return proStatus;
    }

    public void setProStatus(String proStatus) {
        this.proStatus = proStatus;
    }

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

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

            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");
            String ngrcode = "";//
            String fzrcode = "";//
            String xmmc = "";//
            String xmfzr ="";//
            String lcbh = "" ;
            String lcbt = "";
            String sql =" select t.id,t.ngr,t.xmmc,h.workcode as ngrcode,t.lcbh,t.lcbt,k.workcode as fzrcode\n" +
                        " from "+tablename+" t \n" +
                        " inner join hrmresource h on h.id = t.ngr \n" +
                        " left join hrmresource k on k.id = to_char(t.xmfzr)\n" +
                        " where t.requestid = " + requestid + "";
            writeLog( sql );
            rs.executeQuery( sql );
            if(rs.next())
            {
                ngrcode = Util.null2String(rs.getString( "ngrcode" ));//
                fzrcode = Util.null2String(rs.getString( "fzrcode" ));//
                xmmc = Util.null2String( rs.getString( "xmmc" ) );//
                lcbh = Util.null2String( rs.getString( "lcbh" ) );//
                lcbt = Util.null2String( rs.getString( "lcbt" ) );
            }

            System.out.println("ngrcode:"+ngrcode);
            System.out.println("fzrcode:"+fzrcode);
            System.out.println("xmmc:"+xmmc);
            System.out.println("lcbh:"+lcbh);
            System.out.println("proStatus:"+this.proStatus);

            if("".equals(fzrcode)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "项目负责人不能为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            if("".equals(ngrcode)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "拟稿人不能为空" );
                return Action.FAILURE_AND_CONTINUE;
            }
            if("".equals(lcbh)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "流程编号为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            if("".equals(xmmc)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "项目为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            if("".equals(this.proStatus)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "接口配置参数为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            if("".equals(lcbt)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "流程标题为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            if("".equals(requestid)){
                requestInfo.getRequestManager().setMessageid( "1111" );
                requestInfo.getRequestManager().setMessagecontent( "流程requestId为空" );
                return Action.FAILURE_AND_CONTINUE;
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("badge",ngrcode);
            jsonObject.put("projectCode",xmmc);
            jsonObject.put("projectDirector",fzrcode);

            jsonObject.put("proStatus",this.proStatus);
            jsonObject.put("workFlowNum",lcbh);
            jsonObject.put("requestId",requestid);
            jsonObject.put("title",lcbt);

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

            try{
                JSONObject retJson = JSONObject.parseObject(response);
                String retCode = retJson.getString("retCode");
                if("0000".equals(retCode)){
                    return Action.SUCCESS;
                }else{
                    requestInfo.getRequestManager().setMessageid( "1111" );
                    requestInfo.getRequestManager().setMessagecontent( "更新状态失败" );
                    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;
    }

}
