package com.bcxin.ins.coninsweb.order.controller.api.tyx.qianhai;

import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.preservation.InsPreservationPayAPIService;
import com.bcxin.ins.third.tyx.qianhai.TYX_PackageMessageQianHai;
import com.bcxin.ins.third.tyx.qianhai.TYX_QHRequestService;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * <b> 前海团意险接口Controller控制器，用于回调 </b>
 * @author ZXF
 * @create 2023/02/08 0008 11:27
 * @version
 * @注意事项 </b>
 */
@Controller
public class TYX_QH_API_Controller extends BaseController {


	@Autowired
	private InsTransactionAPIService insTransactionAPIService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private InsPreservationPayAPIService insPreservationPayAPIService;
	@Autowired
	private TYX_QHRequestService tYX_QHRequestService;

	/**
	 * 保单接口回调
	 * @param xml 请求报文
	 */
	@RequestMapping(value = "/QH-API/TYX/callback-policy")
	public void callbackPolicy(@RequestBody String xml) throws UnsupportedEncodingException {
		if(xml.contains("%3C%")){
			xml = URLDecoder.decode(xml, ConstProp.ENCODE_UTF8);
		}
		logger.info("保单生效接口回调-callback-policy-QH-TYX：请求报文-"+xml);
		TYX_PackageMessageQianHai gpm = new TYX_PackageMessageQianHai();
		String result = gpm.returnAnalysisXML(xml, TransTypeEnum.HDCB.getValue());
		logger.info("保单生效接口回调-callback-policy-QH-TYX：接口返回数据-"+result);
		if(StringUtils.isEmpty(result)){
			renderString(response, returnRet("0001","报文解析失败"), ConstProp.CT_JSON);
			logger.info("保单生效接口回调-callback-policy-QH-TYX：业务结束：end");
			return;
		}
		if(!ConstProp.CODE_SUCCESS.equals(result.split(ConstProp.POUND_SIGN)[0])){
			//TODO 回调结果如果是支付失败，需要在这里进行处理，未开发
			renderString(response, returnRet("0002",result.split(ConstProp.POUND_SIGN)[1]), ConstProp.CT_JSON);
			logger.info("保单生效接口回调-callback-policy-QH-TYX：业务结束：end");
			return;
		}
		OrderFormVo orderVo = policyService.getPolicyDtoByRcptNo(result.split(ConstProp.POUND_SIGN)[1]);
		if(orderVo == null){
			renderString(response, returnRet("0100","订单不存在"), ConstProp.CT_JSON);
			logger.info("保单生效接口回调-callback-policy-QH-TYX：业务结束：end");
			return;
		}
		if(StringUtils.isEmpty(orderVo.getExternal_reference())){
			PolicyTransactionVo vo= new PolicyTransactionVo();
			//保存保单号
			vo.setPolicy_number(result.split(ConstProp.POUND_SIGN)[2]);//policy.setExternalReference();
			vo.setPolicy_id(orderVo.getOid());
			insTransactionAPIService.savePolicyExternalReference(vo);
			if(result.split(ConstProp.POUND_SIGN).length == 4){
				//保存保单地址
				vo.setInsure_path(result.split(ConstProp.POUND_SIGN)[3]);//保单地址
				insTransactionAPIService.savePolicyOther(vo);
			}
			new Thread(()->{ //异步
				try {
					//返回订单给指定平台
					policyService.returnsAnOrderToTheSpecifiedPlatform(orderVo.getOid());
				} catch(Exception e) {
					logger.error("------------雇主责任险推送百保盾，异常："+e.getMessage());
				}
			}).start();
		}
		renderString(response, returnRet("0000","成功"), ConstProp.CT_JSON);
		logger.info("保单生效接口回调-callback-policy-QH-TYX：业务结束：end");
	}

	public static void main(String[] args) {
		String xml="<Packet><Head><UUID>4b07e8b0-0c49-4cf0-a9eb-db3376b2442b</UUID><CRequestType>220005</CRequestType><CBusiChnl>BLB</CBusiChnl><TAcctTm>2023-12-04 13:42:13.0</TAcctTm><CheckCode>440410781dc91e884ab6e136a4c09432</CheckCode></Head><Body><Base><AppNo>0BLB2023120437056318</AppNo><TradeAmount>5292</TradeAmount><TradeDate>2023-12-04 13:42:13.0</TradeDate><TradeState>1</TradeState><TradeMsg>成功</TradeMsg><ResultCode>1</ResultCode><ResultMsg>成功</ResultMsg><PlyNo>1BLB2023120437056318</PlyNo><PlyDocUrl>https://www.qhins.com/webins/epoliy?pNo=1BLB2023120437056318&sign=c726b1b1f6050fcecaf6afcbad1a0b1a</PlyDocUrl></Base></Body></Packet>";
//		String jsonObject = postJsonString("https://www.bailianbao.cn/QH-API/GZZRX/callback-policy", xml);
//		String jsonObject = postJsonString("http://www.bailianbao.cn/QH-API/GZZRX/callback-policy", xml);
//		System.out.println(jsonObject);
	}

	public static String postJsonString(String url, String json) {
		try (CloseableHttpClient httpclient = HttpClients.createDefault()){
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader(HTTP.CONTENT_TYPE, "application/json");
			if(StringUtils.isNotEmpty(json)){
				StringEntity se = new StringEntity(json, StandardCharsets.UTF_8);
				se.setContentType("text/json");
				se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
				httppost.setEntity(se);
			}
			try (CloseableHttpResponse response = httpclient.execute(httppost) ){
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, StandardCharsets.UTF_8);
				}
			}
		} catch (IOException e) {
		}
		return "";
	}

	/**
	 * <b> 申请电子发票 </b>
	 * @author ZXF
	 * @create 2023/04/03 0003 17:48
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/QH-API/TYX/PRINT_INVOICE/{oid}")
	@ResponseBody
	public ResultDto printInvoice(@PathVariable long oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto == null || !DictConst.ORDER_STATUS_YCB.equals(dto.getPolicy_status())){
			return new ResultDto("无法获取发票！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		String result = tYX_QHRequestService.request_qh_tyx(oid, TransTypeEnum.DZFP.getValue(),null);
		if(StringUtils.isEmpty(result)){
			return new ResultDto("获取电子发票接口异常！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		String[] strs = result.split(ConstProp.POUND_SIGN);
		if(!ConstProp.CODE_SUCCESS.equals(strs[0])){
			return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(StringUtils.isEmpty(strs[1])){
			return new ResultDto("（APP-TYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(StringUtils.isNotEmpty(dto.getExternal_reference())){
			policyService.updateUrlByExternalreference(strs[2],dto.getExternal_reference());
			return new ResultDto(strs[1], ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}else{
			return new ResultDto("未获取到保单号！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	private String returnRet(String code,String msg){
		return "<Packet type=\"RESPONSE\" version=\"1.0\">\n" +
				"\t<Head>\n" +
				"\t\t<CRequestType>220005</CRequestType>\n" +
				"\t\t<CBusiChnl>blb</CBusiChnl>\n" +
				"\t\t<ResultCode>"+code+"</ResultCode>\n" +
				"\t\t<ResultMessage>"+msg+"</ResultMessage>\n" +
				"\t</Head>\n" +
				"</Packet>";
	}
}

