package com.zfire.jiasm.syncdata.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.pojo.bo.DownRepairOrderGD;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

@Component
@Slf4j
public class SMSSelfManager {
	@Value("${SMSSelf_accountSID}")
	private String accountSID;
	@Value("${SMSSelf_authToken}")
	private String authToken;
	@Value("${SMSSelf_softVersion}")
	private String softVersion;
	@Value("${SMSSelf_baseURL}")
	private String baseURL;
	@Value("${SMSSelf_appId}")
	private String appId;
	@Value("${gdbaseurl}")
	private String baseurl = "";

	@Value("${SMSSelf_smsType}")
	private String smsType;

	@Value("${SMSSelf_startTime}")
	private String startTime;

	@Value("${SMSSelf_endTime}")
	private String endTime;

	public String getAccountSID() {
		return accountSID;
	}

	public void setAccountSID(String accountSID) {
		this.accountSID = accountSID;
	}

	public String getAuthToken() {
		return authToken;
	}

	public void setAuthToken(String authToken) {
		this.authToken = authToken;
	}

	public String getSoftVersion() {
		return softVersion;
	}

	public void setSoftVersion(String softVersion) {
		this.softVersion = softVersion;
	}

	public String getBaseURL() {
		return baseURL;
	}

	public void setBaseURL(String baseURL) {
		this.baseURL = baseURL;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	private String genAuthorization(String timestamp) throws UnsupportedEncodingException {
		return new String(Base64.getEncoder().encode((accountSID + ":" + timestamp).getBytes("utf8")), "utf8");
	}

	private String genSig(String timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest dessageDigest = MessageDigest.getInstance("MD5");
		byte[] result = dessageDigest.digest((accountSID + authToken + timestamp).getBytes("utf8"));
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < result.length; i++) {
			String s = Integer.toHexString(result[i] & 0xFF);
			if (s.length() == 1) {
				buf.append("0");
			}
			buf.append(s);
		}
		return buf.toString();
	}

	private String genURL(String func, String funcdes, String sig) {
		return baseURL + "/" + softVersion + "/Accounts/" + accountSID + "/" + func + "/" + funcdes + "?sig=" + sig;
	}

	private JSONObject httpRequest(String requestUrl, String authorization, String jsonString) throws Exception {
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {

			HttpUtil.trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", authorization);
			httpUrlConn.setRequestProperty("Accept", "application/json");
			httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			httpUrlConn.setRequestMethod("POST");

			log.debug("url[" + url + "],send[" + jsonString + "]");

			if (null != jsonString) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(jsonString.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
			log.debug("receive[" + result + "],url[" + url + "],send[" + jsonString + "]");

			jsonresult = JSONObject.parseObject(result);

		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	public String templateSMS(String phoneNo, String templateId, String reqId, String subAppend, String[] datas)
			throws Exception {
		String resultData = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timestamp = sdf.format(date);
		String authorization = genAuthorization(timestamp);
		String sig = genSig(timestamp);
		String url = genURL("SMS", "TemplateSMS", sig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("to", phoneNo);
		jsonObject.put("appId", this.appId);
		jsonObject.put("templateId", templateId);
		jsonObject.put("reqId", reqId);
		jsonObject.put("subAppend", subAppend);
		JSONArray array = new JSONArray();
		for (String data : datas) {
			array.add(data);
		}
		jsonObject.put("datas", array);
		JSONObject result = this.httpRequest(url, authorization, jsonObject.toJSONString());
		if (!"000000".equals(result.getString("statusCode"))) {
			String statusMsg = result.getOrDefault("statusMsg", "").toString();
			log.info("短信发送失败[" + result.getString("statusCode") + "," +
					result.getOrDefault("statusMsg", "") + "]");
			if (statusMsg.length()>128){
				resultData = statusMsg.substring(0,127);
			} else {
				resultData = statusMsg;
			}
		}

		return resultData;
	}

	public JSONObject getArrived() throws Exception {

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timestamp = sdf.format(date);

		String authorization = genAuthorization(timestamp);
		String sig = genSig(timestamp);
		String url = genURL("SMS", "GetArrived", sig);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("appId", this.appId);
		jsonObject.put("smsType", smsType);

		JSONObject result = this.httpRequest(url, authorization, jsonObject.toJSONString());

		if (!"000000".equals(result.getString("statusCode"))) {
			throw new Exception("查询上行短信失败[" + result.getString("statusCode") + "]");
		}

		return result;

	}

	public DownRepairOrderGD getArrivedGD(String api) throws Exception {
		DownRepairOrderGD datas = new DownRepairOrderGD();
		String url = baseurl + api;
		JSONObject jsonResult = HttpUtil.httpRequestGetPgidGD(url, "GET", null);
		String code = jsonResult.getString("code");
		if ("200".equals(code)) {
			String json = jsonResult.getString("data");
			JSONObject jsona = JSONObject.parseObject(json);
			String id = jsona.getString("id");
			datas.setId(id);
			datas.setData(jsona.getJSONArray("data"));
			return datas;
		} else {
			String errorMessage = jsonResult.getString("message");
			if (errorMessage == null || errorMessage.trim().length() == 0) {
				errorMessage = "失败";
			}
			throw new Exception(errorMessage);
		}

	}

	public boolean checkCanSend() {

		String currentTime = new SimpleDateFormat("HH:mm").format(new Date(System.currentTimeMillis()));

		if (currentTime.compareTo(startTime) >= 0 && currentTime.compareTo(endTime) <= 0) {
			return true;
		}

		return false;

	}

}
