package com.community.commom.fushi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.omg.CORBA.Request;

/**
 * 富士HTTP请求
 * @author weiximei
 */
@Data
public class FuShiHttpClient {
//	private static String url = "http://mops-test.fujica.com.cn:8021/Api/Park/GetParkInfoByCarNo";
	private String url;
	private String appid;
	private String appSecret;
	private String privateKey;
//	private String sign = "";
//	private String time;

    public FuShiHttpClient(String url, String appid, String appSecret, String privateKey) {
        this.url = url;
        this.appid = appid;
        this.appSecret = appSecret;
        this.privateKey = privateKey;
    }

    public static void main(String[] args) {
//		time = getTimestamp();
//		String jsonString = "{'ParkingCode':'19000100250504','CarNo':'苏A8M6B2'}";
//
//		TreeMap<String, String> map = new TreeMap();
//		map.put("param", jsonString);
//		map.put("secret", appSecret);
//		map.put("timestamp", time);
//		sign = signWithoutMD5(map);
//		sign = sign(sign, privateKey);
//
//		doJsonPost(url, jsonString);
	}

	/**
	 * POST 请求
	 * @param urlPath
	 * @param Json
	 * @return
	 */
	public String doJsonPost(String urlPath, String Json, String sign, String time) {
		urlPath = url + urlPath;
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("appid", appid);
			conn.setRequestProperty("appSecret", appSecret);
			conn.setRequestProperty("sign", sign);
			conn.setRequestProperty("timestamp", time);
			// 设置文件类型:
			conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			// 设置接收类型否则返回415错误
			conn.setRequestProperty("accept", "*/*");// 此处为暴力方法设置接受所有类型，以此来防范返回415;
			conn.setRequestProperty("accept", "application/json");
			// 往服务器里面发送数据
			if (Json != null && !("").equals(Json)) {
				byte[] writebytes = Json.getBytes();
				// 设置文件长度
				conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
				OutputStream outwritestream = (OutputStream) conn.getOutputStream();
				outwritestream.write(Json.getBytes());
				outwritestream.flush();
				outwritestream.close();

			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				// System.out.println(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

    /**
     * 时间戳, 取前十位
     * @return
     */
	public String getTimestamp() {
		String time = "";
		long timestamp = System.currentTimeMillis();
		time = String.valueOf(timestamp);
		time = time.substring(0, 10);
		return time;
	}

    /**
     * MD5
     * @param params
     * @return
     */
	public String signWithoutMD5(SortedMap<String, String> params) {
		String restul = "";
		if (params == null) {
			return restul;
		}

		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> me : params.entrySet()) {

			sb.append(me.getKey());
			sb.append('=');
			sb.append(me.getValue());
			sb.append('&');

		}
		int lastIndexOf = sb.lastIndexOf("&");
		if (lastIndexOf != -1) {
			sb.deleteCharAt(lastIndexOf);
		}
		restul = new String(sb);

		return restul;
	}

	private final String ALGORITHM = "RSA";
	private final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 开始签名
     * @param content
     * @param privateKey
     * @return
     */
	public String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);

			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}



}
