package org.security.desk.esb;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.security.common.constant.CommonConstant;
import org.security.desk.esb.request.EsbRequest;
import org.security.desk.esb.response.EsbResponse;
import org.security.desk.esb.response.RetMsg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author zj 2022/9/2
 */
@Slf4j
@Component
public class EsbHttp {
	@Value("${blade.esbUrl}")
	private String esbUrl;
	@Value("${blade.esbPort}")
	private String esbPort;

	public HttpEsbResponse creatEsbHttpPost(EsbRequest esbRequest) {
		String msg = JSONUtil.toJsonStr(esbRequest);
		HttpRequest post = HttpUtil.createPost(esbUrl + ":" + esbPort + "/" + CommonConstant.SYS_ID);
		post.body(msg);
		log.info("===============请求esb服务开始：{}===============", StringUtils.join(esbRequest.getSYS_HEAD().getSvcCd(), esbRequest.getSYS_HEAD().getSvcScn()));
		log.info("请求报文：\n{}", msg);
		post.contentType("application/json;charset=UTF-8");
		post.setReadTimeout(6000);
		HttpResponse response;
		HttpEsbResponse httpEsbResponse = new HttpEsbResponse();
		try {
			response = post.execute();
		} catch (Exception e) {
			log.error("=============请求esb失败=============");
			log.error(e.getMessage());
			log.error("=============");
			e.printStackTrace();
			httpEsbResponse.setSuccess(Boolean.FALSE);
			EsbResponse<String> esbResponse = new EsbResponse<>();
			esbResponse.setBODY("请求esb失败，" + e.getMessage());
			httpEsbResponse.setEsbResponse(esbResponse);
			return httpEsbResponse;
		}
		String res = response.body();
		log.info("=============esb返回报文=============");
		log.info("{}", res);
		EsbResponse esbResponse = JSONUtil.toBean(res, EsbResponse.class);
		httpEsbResponse.setEsbResponse(esbResponse);
		httpEsbResponse.setSuccess(Boolean.TRUE);
		List<RetMsg> retMsgArry = esbResponse.getSYS_HEAD().getRetMsgArry();
		if (Objects.isNull(retMsgArry)) {
			log.error("=============esb返回为空=============");
			httpEsbResponse.setSuccess(Boolean.FALSE);
			return httpEsbResponse;
		}
		String retCd = retMsgArry.get(0).getRetCd();
		// 人脸注册与识别成功返回000000而不是0
		String svcCd = esbRequest.getSYS_HEAD().getSvcCd().trim();
		if ("60120120".equals(svcCd) || "60120114".equals(svcCd)) {
			if (!retCd.equals("000000")) {
				log.info("===============请求esb服务失败===============");
				httpEsbResponse.setCode(retCd);
				httpEsbResponse.setSuccess(Boolean.FALSE);
			}
		} else if (!retCd.equals("0")) {
			log.info("===============请求esb服务失败===============");
			httpEsbResponse.setCode(retCd);
			httpEsbResponse.setSuccess(Boolean.FALSE);
		}
		log.error("=============请求esb服务结束=============");
		return httpEsbResponse;
	}
}
