package weaver.interfaces.htsc.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.engine.core.interceptor.CommandContext;
import com.engine.htsc.itxqlc.cmd.ItxqlcXgxtCmd;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpResponse;
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.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SendITSystemInfoAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        RecordSet rs = new RecordSet();
        String result = "";
        String requestId = Util.null2String(requestInfo.getRequestid());
        try {
            //获取主表名
            String mainTableName = JAVATools.getMaintable(requestId);
            String mainSql = "select a.lcbh,a.dywdyx,a.ngrgh,a.xtmc,a.devopsbbmc,a.lcbt,a.xmfzr,a.sxjhkssj1,a.sxjhjssj1,a.ngr,a.fj,b.requestname from "+mainTableName+" a left join workflow_requestbase b on a.requestid = b.requestid where a.requestid = '"+requestId+"' ";
            writeLog("requestId:"+requestId+" 【IT测试与上线申请】部分负责人同意后调用变更墙接口查询主表数据sql:"+mainSql);
            rs.execute(mainSql);
            if(rs.next()){
                HashMap<String, String> param = new HashMap<>();
                param.put("changeType", "01");
                param.put("releaseSource", "OA");
                param.put("sourceId", Util.null2String(rs.getString("lcbh")));//流程编号
                PropBean pb = new PropBean();

                param.put("appSysId", Util.null2String(rs.getString("xtmc"))); //系统编号 对接系统的指南针编号
                param.put("releaseVersion", "xxxYYY");
                param.put("impactSystem", Util.null2String(rs.getString("dywdyx")));//对业务的影响
                param.put("applyUserCode", JAVATools.gethrmidtoworkcode(Util.null2String(rs.getString("ngr"))));//拟稿人工号
                param.put("updateTitle", Util.null2String(rs.getString("requestname")));//流程标题

                //调用指南针接口获取责任人和责任人工号
                Map<String, Object> paramZnz=new HashMap<>();
                paramZnz.put("size","10");
                paramZnz.put("page","0");
                paramZnz.put("appSysId",Util.null2String(rs.getString("xtmc")));//通过系统名称来获取数据
                ItxqlcXgxtCmd ItxqlcXgxtCmd = new ItxqlcXgxtCmd(paramZnz);
                CommandContext commandContext = new CommandContext(null,null);
                Map<String, Object> map = ItxqlcXgxtCmd.execute(commandContext);
                List<Map<String,String>> list = ((List<Map<String,String>>) map.get("data"));
                if (null!=list&&list.size()>0){
                    Map<String,String> detail = list.get(0);
                    String[] array = Util.null2String(detail.get("rltResponsPr")).split(",");
                    String regEx="[^(0-9)]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(Util.null2String(array[0]));
                    param.put("opsUserCode", m.replaceAll("").trim());	//上线责任人工号
                }
                String startTime = Util.null2String(rs.getString("sxjhkssj1")) +":00";//上线开始时间
                String endTime = Util.null2String(rs.getString("sxjhjssj1"))+":00";//上线结束时间
                param.put("planReleaseStartTime",startTime);
                param.put("planReleaseEndTime", endTime);

                String token = pb.getPropName("rest.VaryWall.token"); //123
                String user = pb.getPropName("rest.VaryWall.user"); //cmdb-test
                String url = pb.getPropName("rest.VaryWall");
                String fileUrl = pb.getPropName("rest.VaryWall.FileUrl");

                String fj = Util.null2String(rs.getString("fj"));
                String files = "";
                writeLog("requestid:"+requestId+ " 开始访问nas fj:"+fj);
//                if (!"".equals(fj)){
//                    List<String> fileIds = uploadDocument(fj,fileUrl,user,token);
//                    for (String str : fileIds){
//                        files+=files==""?str:","+str;
//                    }
//                }
                param.put("testReportAddress",files);//制品库的路径
                JAVATools.SetCmdwritelog(param.toString());
                result = postForChangeProcess(url, param,token,user);
                JAVATools.SetCmdwritelog(result);
            }
        } catch (Exception e) {
            writeLog( "异常参考:" + e );
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;

    }

    /**
     * 用于变更墙平台返回系统信息过去
     * @param url
     * @param param
     * @param token
     * @param user
     * @return
     */
    public String postForChangeProcess(String url, HashMap<String, String> param, String token, String user) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 构造消息头
        httpPost.setHeader("user",user);
        httpPost.setHeader("token",token);
        httpPost.setHeader("contentType", "application/json;");
        try {
            //参数   json格式
            JSONObject json = JSONObject.fromObject(param);
            JAVATools.SetCmdwritelog("-----请求参数json------: " + json);
            StringEntity entity = new StringEntity(json.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            String result = "";
            JAVATools.SetCmdwritelog("-----返回参数code------: " + response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) {
                result = EntityUtils.toString(response.getEntity());
                JAVATools.SetCmdwritelog("-----返回结果result------: " + result);
                return result;
            } else {
                JAVATools.SetCmdwritelog("Error Response: " + response.getStatusLine().toString());
                return "Internal Server Error";
            }
        } catch (Exception e) {
            JAVATools.SetCmdwritelog("post failure :caused by-->" + e.getMessage().toString());
            return "Internal Server Error";
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    writeLog(e.getMessage());
                }
            }
        }
    }

    /**
     * 上传文件
     */
    public List<String> uploadDocument(String fj, String fileUrl, String user, String token) {
        //文件
        List<String> list = new ArrayList<>();
        GCONST.setRootPath("");
        GCONST.setServerName("ecology");
        ArrayList<File> files = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select a.fileRealPath,a.isZip from imageFile a,docimagefile b where b.imagefileid = a.imagefileid and b.docid in ( "+fj+" )";
        rs.execute(sql);
        String fileRealPath = "";
        while (rs.next())
        {
            fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            File file = new File(""+fileRealPath);
            files.add(file);
        }
        String result = null;
        PostMethod postMethod = null;
        try {
            postMethod = new PostMethod(fileUrl);
            postMethod.addRequestHeader("user",user);
            postMethod.addRequestHeader("token",token);
            // 构造消息头
            postMethod.getParams().setContentCharset("utf-8");
            postMethod.setContentChunked(true);
            Part[] parts = new Part[files.size()];
            for (int i = 0;i<files.size();i++){
                parts[i] = new FilePart("fileData", files.get(i), null, "utf-8");
            }
            MultipartRequestEntity mrp = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mrp);
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            httpClient.executeMethod(postMethod);
            result = postMethod.getResponseBodyAsString();
            JAVATools.SetCmdwritelog("-----上传文件返回结果result------: " + result);
            List<Map> listMap =  JSON.parseArray(result,Map.class);
            for (int i = 0;i<listMap.size();i++){
                list.add(Util.null2String(listMap.get(i).get("id")));
            }
        } catch (Exception e) {
            try {
                throw e;
            } catch (Exception e1) {
                writeLog(e.getMessage());
            }
        } finally {
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        return list;

    }


}
