package cn.com.ctop.crawler.modules.core.util;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

public class FateadmHttpUtil {
    public static class HttpResp {
        public int retCode;
        public double custVal;
        public String errMsg;
        public String reqId;
        public String rspData;
        public String predResl;
    }

    public static String toHex(byte[] arr) {
        StringBuffer md5str = new StringBuffer();
        int digital;
        for (int i = 0; i < arr.length; i++) {
            digital = arr[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toLowerCase();
    }

    public static String calcMd5(String src) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] input = src.getBytes();
            byte[] buff = md.digest(input);
            md5str = toHex(buff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }
    public static String CalcBase64(byte[] data){
        String s = "";
        if (data != null) {
            s   = Base64.getEncoder().encodeToString( data);
        }
        return s;
    }
    public static String CalcSign(String id, String key, String tm){
        String chk1 = calcMd5(tm + key);
        return calcMd5(id + tm + chk1);
    }

    public static HttpResp parseHttpResp(String resl) {
        HttpResp resp   = new HttpResp();
        resp.retCode = -1;
        JsonHelper json = new JsonHelper(resl);
        json.Parse(resp);
        if (!resp.rspData.isEmpty()) {
            JsonHelper rjson = new JsonHelper(resp.rspData);
            rjson.Parse(resp);
        }
        return resp;
    }

    public static byte[] readBinaryFile(String fileName) throws IOException {
        InputStream in = null;
        BufferedInputStream buffer = null;
        DataInputStream dataIn = null;
        ByteArrayOutputStream bos = null;
        DataOutputStream dos = null;
        byte[] bArray = null;
        try{
            in = new FileInputStream(fileName);
            buffer = new BufferedInputStream(in);
            dataIn = new DataInputStream(buffer);
            bos = new ByteArrayOutputStream();
            dos = new DataOutputStream(bos);
            byte[] buf = new byte[1024];
            while (true) {
                int len = dataIn.read(buf);
                if (len < 0) {
                    break;
                }
                dos.write(buf, 0, len);
            }
            bArray = bos.toByteArray();
        }catch( Exception e){
            return bArray;
        }finally {
            if (in != null) {
                in.close();
            }
            if (dataIn != null) {
                dataIn.close();
            }
            if (buffer != null) {
                buffer.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (dos != null) {
                dos.close();
            }
        }
        return bArray;
    }

    public static String mfPost(URL url, byte[] imgData, String stm, String pdId, String sign, String appId, String asign, String predType) throws Exception {
        String boundary = "--" + calcMd5(stm);
        String boundaryBytesString = "--" + boundary + "\r\n";
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setConnectTimeout(30000);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(true);
        con.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + boundary);
        OutputStream out    = con.getOutputStream();
        String itemString = boundaryBytesString + "Content-Disposition: form-data;name=\"";
        String paramString = itemString + "user_id\"\r\n\r\n" + pdId + "\r\n"
                + itemString + "timestamp\"\r\n\r\n" + stm + "\r\n"
                + itemString + "sign\"\r\n\r\n" + sign + "\r\n"
                + itemString + "predict_type\"\r\n\r\n" + predType + "\r\n"
                + itemString + "up_type\"\r\n\r\nmt\r\n";
        if (!appId.isEmpty()) {
            paramString += itemString + "appid\"\r\n\r\n" + appId + "\r\n"
                    + itemString + "asign\"\r\n\r\n" + asign + "\r\n";
        }
        String fileStrig = itemString + "img_data\";filename=\"image.jpg\"\r\nContent-Type: image/jpg\r\n\r\n";
        String endString = "\r\n--" + boundary + "--\r\n";
        out.write(paramString.getBytes(StandardCharsets.UTF_8));
        out.write(fileStrig.getBytes(StandardCharsets.UTF_8));
        out.write(imgData);
        out.write(endString.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();

        StringBuilder buffer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
        String temp;
        while((temp = br.readLine()) != null) {
        	buffer.append(temp);
        	buffer.append("\n");
        }
        return buffer.toString().trim();
	}

    public static byte[] getUrlImage(String strUrl) throws IOException {
        URL url = new URL(strUrl);
    	URLConnection con = url.openConnection();
		con.setConnectTimeout(30000);
		InputStream is = con.getInputStream();
		byte[] buff = new byte[128];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int rc = 0;
		while((rc = is.read(buff, 0, 128)) > 0 ) {
			baos.write(buff,0,rc);
		}
        return baos.toByteArray();
    }

    public static String httpPost(String url, String params) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
}
