package com.hzya.frame.ncc.v202005.service.impl;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.ncc.v202005.service.INccV202005Service;
import com.hzya.frame.util.oldNcc.Encryption;
import com.hzya.frame.util.oldNcc.SHA256Util;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


@Service(value="nccV202005Service")
public class  NccV202005ServiceImpl implements INccV202005Service {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());


	@Override
	public JsonResultEntity thirdInterfaceGetToken(JSONObject object) {
		JSONObject jsonObject = getstrObj("jsonStr", object);

		String client_id = jsonObject.getString("client_id");
		String pubKey = jsonObject.getString("pubKey");
		String client_secret = jsonObject.getString("client_secret");
		String username = jsonObject.getString("username");
		String pwd = jsonObject.getString("pwd");
		String busi_center = jsonObject.getString("busi_center");
		String dsname = jsonObject.getString("dsname");
		String baseUrl = jsonObject.getString("baseUrl");
		Map<String, String> paramMap = new HashMap<String, String>();
		// 密码模式认证
		paramMap.put("grant_type", "password");
		// 第三方应用id
		paramMap.put("client_id", client_id);
		// 第三方应用secret 公钥加密
		try {
			paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
		} catch (Exception e) {
			return BaseResult.getFailureMessageEntity("获取token失败");
		}
		// ncc用户名
		paramMap.put("username", username);
		// 密码 公钥加密
		try {
			paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8"));
		} catch (Exception e) {
			return BaseResult.getFailureMessageEntity("获取token失败");
		}
		// 账套编码
		paramMap.put("biz_center", busi_center);
		// 签名
		String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey);
		paramMap.put("signature", sign);
		paramMap.put("dsname", dsname);
		String url = baseUrl + "/nccloud/opm/accesstoken";
		String mediaType = "application/x-www-form-urlencoded";
		String token = doPost(url, paramMap, mediaType, null, "");
		//System.out.println("token:" + token);
		if(JSONUtil.isTypeJSON(token)){
			JSONObject jsonObject1 = JSONObject.parseObject(token);
			return BaseResult.getSuccessMessageEntity("获取token成功",jsonObject1);
		}else {
			return BaseResult.getSuccessMessageEntity("获取token成功",token);
		}
	}

	@Override
	public JsonResultEntity getNccData(JSONObject object) {
		String token = "{\"head\":{\"primal_money\":\"489.00\",\"bill_date\":\"2023-08-15 06:10:01\",\"pk_currtype\":\"1002Z0100000000001K1\",\"bill_type\":\"F4\",\"trade_type\":\"D4\",\"billmaker_date\":\"2023-08-15 06:10:01\",\"objecttype\":\"0\",\"source_flag\":\"2\",\"pk_org\":\"0001W310000000002WN9\"},\"body\":[{\"bill_date\":\"2023-08-15 06:10:01\",\"pk_customer\":\"1001W3100000000007PV\",\"pk_account\":\"1001W3100000000007RQ\",\"pk_recproject\":\"1001W3100000000007QR\",\"pk_currtype\":\"1002Z0100000000001K1\",\"bill_type\":\"F4\",\"trade_type\":\"D4\",\"creationtime\":\"2023-08-15 06:10:01\",\"objecttype\":\"0\",\"pk_org\":\"0001W310000000002WN9\",\"direction\":\"1\",\"rec_primal\":\"489.00\"}]}";
		JSONObject jsonObject1 = JSONObject.parseObject(token);
		return BaseResult.getSuccessMessageEntity("获取数据成功",jsonObject1);
	}
	@Override
	public JsonResultEntity getNccDataDetail(JSONObject object) {
		String token = "{\"primal_money\":\"489.00\",\"bill_date\":\"2023-08-15 06:10:01\",\"pk_currtype\":\"1002Z0100000000001K1\",\"bill_type\":\"F4\",\"trade_type\":\"D4\",\"billmaker_date\":\"2023-08-15 06:10:01\",\"objecttype\":\"0\",\"source_flag\":\"2\",\"pk_org\":\"0001W310000000002WN9\",\"bill_date1\":\"2023-08-15 06:10:01\",\"pk_customer\":\"1001W3100000000007PV\",\"pk_account\":\"1001W3100000000007RQ\",\"pk_recproject\":\"1001W3100000000007QR\",\"pk_currtype1\":\"1002Z0100000000001K1\",\"bill_type1\":\"F4\",\"trade_type1\":\"D4\",\"creationtime\":\"2023-08-15 06:10:01\",\"objecttype1\":\"0\",\"pk_org1\":\"0001W310000000002WN9\",\"direction\":\"1\",\"rec_primal\":\"489.00\"}";
		JSONObject jsonObject1 = JSONObject.parseObject(token);
		return BaseResult.getSuccessMessageEntity("获取数据成功",jsonObject1);
	}

	/**
	 * 发送post请求
	 *
	 * @param baseUrl
	 * @param paramMap
	 * @param mediaType
	 * @param headers
	 * @param json
	 * @return
	 */
	private String doPost(String baseUrl, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {

		HttpURLConnection urlConnection = null;
		InputStream in = null;
		OutputStream out = null;
		BufferedReader bufferedReader = null;
		String result = null;
		try {
			StringBuffer sb = new StringBuffer();
			sb.append(baseUrl);
			if (paramMap != null) {
				sb.append("?");
				for (Map.Entry<String, String> entry : paramMap.entrySet()) {
					String key = entry.getKey();
					String value = entry.getValue();
					sb.append(key + "=" + value).append("&");
				}
				baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
			}

			URL urlObj = new URL(baseUrl);
			urlConnection = (HttpURLConnection) urlObj.openConnection();
			urlConnection.setConnectTimeout(50000);
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.addRequestProperty("content-type", mediaType);
			if (headers != null) {
				for (String key : headers.keySet()) {
					urlConnection.addRequestProperty(key, headers.get(key));
				}
			}
			out = urlConnection.getOutputStream();
			out.write(json.getBytes("utf-8"));
			out.flush();
			int resCode = urlConnection.getResponseCode();
			if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
				in = urlConnection.getInputStream();
			} else {
				in = urlConnection.getErrorStream();
			}
			bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			StringBuffer temp = new StringBuffer();
			String line = bufferedReader.readLine();
			while (line != null) {
				temp.append(line).append("\r\n");
				line = bufferedReader.readLine();
			}
			String ecod = urlConnection.getContentEncoding();
			if (ecod == null) {
				ecod = Charset.forName("utf-8").name();
			}
			result = new String(temp.toString().getBytes("utf-8"), ecod);
		} catch (Exception e) {
			//System.out.println(e);
		} finally {
			if (null != bufferedReader) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			urlConnection.disconnect();
		}
		return result;
	}
	/**
	 * @Author lvleigang
	 * @Description  获取对象转换成jsonobj
	 * @Date 11:51 下午 2023/7/10
	 * @param key
	 * @param object
	 * @return com.alibaba.fastjson.JSONObject
	 **/
	protected JSONObject getstrObj(String key, JSONObject object) {
		if (checkStr(object.getString(key)) ) {
			return object.getJSONObject(key);
		}
		return new JSONObject();
	}

	/**
	 * @param str
	 * @return void
	 * @Author lvleigang
	 * @Description 校验字符串
	 * @Date 11:41 上午 2022/12/7
	 **/
	protected Boolean checkStr(String str) {
		Boolean flag = true;
		if (str == null || "".equals(str)) {
			flag = false;
		}
		return flag;
	}
}
