package org.springblade.common.utils;

import cn.hutool.json.JSONUtil;
import org.springblade.common.entity.CustInfoVerifyConfig;
import org.springblade.common.entity.CustInfoResponse;
import org.springblade.common.entity.CustInfoVerify;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created By lidexi in 2021/4/26
 **/
public class CustInfoVerifyUtil {


	public static Boolean custInfoVerify(CustInfoVerify custInfoVerify){
		String certNumber = custInfoVerify.getCertNumber();
		String custName = custInfoVerify.getCustName();
		if(!StringUtils.hasText(certNumber) || !StringUtils.hasText(custName)){
			Assert.isTrue(false, "身份证和姓名不能为空");
		}
		//姓名、身份证号去首尾空格
		custInfoVerify.setCertNumber(certNumber.trim());
		custInfoVerify.setCustName(custName.trim());
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		String uuid = UUID.randomUUID().toString();
		CustInfoVerifyConfig config = new CustInfoVerifyConfig();
		headers.add("X-APP-ID", config.getAppId());
		headers.add("X-APP-KEY", config.getAppKey());
		headers.add("X-CTG-Request-ID",uuid);
		headers.add("Content-Type", "text/xml;charset=utf-8");
		Map<String, Object> logMap = new HashMap<>();
		logMap.put("header", headers);
		logMap.put("body", custInfoVerify);
		HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(custInfoVerify), headers);
		ParameterizedTypeReference<CustInfoResponse> reference = new ParameterizedTypeReference<CustInfoResponse>() {};
		String url = config.getHost();
		URI uri = URI.create(url);
		logMap.put("url", uri);
		ResponseEntity<CustInfoResponse> result = null;
		try {
			result = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
			logMap.put("result", result.getBody());
		}catch (Exception e){
			logMap.put("result", e.getMessage());
		}
		CustInfoResponse response = result.getBody();

		if(!"0".equals(response.getCode())){
			return false;
		}else{
			return true;
		}
	}
}
