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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.entity.policy_core.InsPreservationRecord;
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.service.preservation.InsPreservationRecordAPIService;
import com.bcxin.ins.third.gzx.huatai.util.RsaUtil;
import com.bcxin.ins.third.tyx.huatai.TYX_HTRequestService;
import com.bcxin.ins.third.tyx.huatai.TYX_PackageMessageHuaTai;
import com.bcxin.ins.third.zzx.huatai.ZZX_HTRequestService;
import com.bcxin.ins.third.zzx.huatai.ZZX_PackageMessageHuaTai;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.PolicyTransactionVo;
import com.bcxin.ins.vo.ResultDto;
import com.bcxin.mybatisplus.toolkit.StringUtils;
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.UnsupportedEncodingException;
import java.net.URLDecoder;

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


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

	@Autowired
	private InsPreservationRecordAPIService insPreservationRecordAPIService;
	@Autowired
	private TYX_HTRequestService tYX_HTRequestService;

	/**
	 * 保单接口回调
	 * @param json 请求报文
	 */
	@RequestMapping(value = "/HT-API/TYX/callback-policy")
	public void callbackPolicy(@RequestBody String json) throws UnsupportedEncodingException {
		if(json.contains("%3C%")){
			json = URLDecoder.decode(json, ConstProp.ENCODE_UTF8);
		}
		logger.info("保单生效接口回调-callback-policy-HT-TYX：请求报文（密文）-"+json);
		JSONObject obj = (JSONObject)JSONObject.parse(json);
		try {
			json = RsaUtil.dSign(obj.get("signature")+"", GlobalResources.HT_TYX_RSA_PRIVATEKEY);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		logger.info("保单生效接口回调-callback-policy-HT-TYX：请求报文（明文）-"+json);
		TYX_PackageMessageHuaTai gpm = new TYX_PackageMessageHuaTai();
		String result = gpm.returnAnalysisXML(json, TransTypeEnum.HDCB.getValue());
		logger.info("保单生效接口回调-callback-policy-HT-TYX：接口返回数据-"+result);
		if(StringUtils.isEmpty(result)){
			renderString(response, returnRet("1","报文解析失败"), ConstProp.CT_JSON);
			logger.info("保单生效接口回调-callback-policy-HT-TYX：业务结束：end");
			return;
		}
		if(!ConstProp.CODE_SUCCESS.equals(result.split(ConstProp.POUND_SIGN)[0])){
			renderString(response, returnRet("1",result.split(ConstProp.POUND_SIGN)[1]), ConstProp.CT_JSON);
			logger.info("保单生效接口回调-callback-policy-HT-TYX：业务结束：end");
			return;
		}
		//200#订单号#保单号#保单地址#保涵地址#支付订单号#支付时间（时间戳）#支付方式
		OrderFormVo orderVo = policyService.getPolicyDtoByRcptNo(result.split(ConstProp.POUND_SIGN)[1]);
		if(orderVo == null){
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			orderVo = policyService.getPolicyDtoByRcptNo(result.split(ConstProp.POUND_SIGN)[1]);
			if(orderVo == null){
				renderString(response, returnRet("1","订单不存在"), ConstProp.CT_JSON);
				logger.info("保单生效接口回调-callback-policy-HT-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);
			}
			//200#PA1182343131539055552#PB27I425052302098253#https://test.pc.ehuatai.com:9003/inco-gateway/printPdf?key=2CBEED6826B9F97DB500CF047798EC8E#DB202312080941590010340700001#1702051200000#54
			if(result.split(ConstProp.POUND_SIGN).length == 7){
				//保存保单地址
				vo.setInsure_path(result.split(ConstProp.POUND_SIGN)[3]);//保单地址
//				vo.setLg_path(result.split(ConstProp.POUND_SIGN)[4]);//保涵地址
				insTransactionAPIService.savePolicyOther(vo);
			}
			OrderFormVo orderVo1 = orderVo;
			new Thread(()->{ //异步
				try {
					//返回订单给指定平台
					policyService.returnsAnOrderToTheSpecifiedPlatform(orderVo1.getOid());
				} catch(Exception e) {
					logger.error("------------团意险推送百保盾，异常："+e.getMessage());
				}
			}).start();
		}
		renderString(response, returnRet("0","成功"), ConstProp.CT_JSON);
		logger.info("保单生效接口回调-callback-policy-HT-TYX：业务结束：end");
	}

	/**
	 * <b> 申请电子发票 </b>
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/HT-API/TYX/PRINT_INVOICE/{oid}")
	@ResponseBody
	public ResultDto printInvoice(@PathVariable long oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto == null || !ConstProp.DIGIT_SIX.equals(dto.getPolicy_status())){
			return new ResultDto("无法获取发票！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		String result = "";
		for(int i=0;i<3;i++){
			result = tYX_HTRequestService.request_ht_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.isNotEmpty(strs[1])){
				if(StringUtils.isNotEmpty(dto.getExternal_reference())){
					policyService.updateUrlByExternalreference(strs[1],dto.getExternal_reference());
				}
				return new ResultDto(strs[1], ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			Thread.sleep(2000);
		}
		return new ResultDto("发票生成中！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	/**
	 * 保单批改生效接口回调
	 * @param json 请求报文
	 */
	@RequestMapping(value = "/HT-API/TYX/callback-record")
	public void callbackRecord(@RequestBody String json) throws UnsupportedEncodingException {
		if(json.contains("%3C%")){
			json = URLDecoder.decode(json, ConstProp.ENCODE_UTF8);
		}
		logger.info("保单批改生效接口回调-callback-record-HT-TYX：请求报文（密文）-"+json);
		JSONObject obj = (JSONObject)JSONObject.parse(json);
		try {
			json = RsaUtil.dSign(obj.get("signature")+"", GlobalResources.HT_TYX_RSA_PRIVATEKEY);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
//		json = "{\"edrEffectDate\":\"2025-04-18\",\"edrNo\":\"PA1362434842800853777\",\"edrResult\":\"01\",\"orderNo\":\"PA1362439149969379840\",\"plyNo\":\"PB251649722503943872\",\"plyUrl\":\"http://localhost:8080/HT-API/TYX/callback-record\"}";
		logger.info("保单批改生效接口回调-callback-record-HT-TYX：请求报文（明文）-"+json);
		JSONObject data = (JSONObject)JSONObject.parse(json);

		String plyNo = data.get("plyNo")+"";
		String edrResult = data.get("edrResult")+"";
		String orderNo = data.get("orderNo")+"";
		String edrNo = data.get("edrNo")+"";
		String plyUrl = data.get("plyUrl")+"";
		String edrInfo = data.get("edrInfo")+"";
		if(StringUtils.isEmpty(plyNo)){
			renderString(response, returnRet("1","保单号不能为空"), ConstProp.CT_JSON);
			return;
		}
		if(StringUtils.isEmpty(edrResult)){
			renderString(response, returnRet("1","批改结果不能为空"), ConstProp.CT_JSON);
			return;
		}

		InsPreservationRecord record = insPreservationRecordAPIService.findInsPreservationRecordBySerialNumber(orderNo);
		if(record == null){
			renderString(response, returnRet("1","订单不存在"), ConstProp.CT_JSON);
			return;
		}
		insPreservationRecordAPIService.updateHTRecordStatus(orderNo,edrNo,plyUrl,edrResult,edrInfo);
		renderString(response, returnRet("0","成功"), ConstProp.CT_JSON);
		logger.info("保单批改生效接口回调-callback-record-HT-TYX：业务结束：end");
	}

	public static void main(String[] args) {
//		String url = "http://localhost:8080/HT-API/TYX/callback-policy";
		String url = "http://localhost:8080/HT-API/TYX/callback-record";
		String param = "{\"signature\":\"PDjfqaMsquJ/Mvne3vkPjuu8eGxEKcXdGOt6AoI2vkPlClktRvfhviHnwo2VDU1fwWDbYBHa2Gx03PA8/Li4VhZw7d7diIpcX6reWaTUcEiGE8s7uomkRuaETF0ZO8RGIx9tI8L4PnVqKUEsRNrKYo/eqOZQpEjTFRsc9x8rnC8P403M8KwGjBuDdbDfEBhGNB7j/5Uw1fVHOCIiLj63auvtXX1SSRbZN9v7BxvFKOohv3tuhS/+7K0UQb1jFiZCbZ8PePYfOarNxGks4iOnrQP9RJI+xwaCOXahpfgU37A4OJAE39+tUuHhzovpG/sbdsP0IrwPg8x7ZHhs/A9wXA==\",\"chlCode\":\"HT102195\",\"chlorderNo\":\"1731494068917235712\"}";
		String result = "";
		try {
			result = RequestUtil.initHttp().doPost(url, param, "text/json", "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(result);
	}

	private String returnRet(String code,String msg){
		return "{\"responseDate\": \""+ DateUtil.getCurrentDateTime() +"\",\"status\": "+code+",\"statusText\": \""+msg+"\"}";
	}
}

