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

import com.alibaba.fastjson.JSON;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.util.JwtUtil;
import com.bcxin.ins.dto.Result;
import com.bcxin.ins.entity.policy_core.InsPreservationRecord;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.preservation.InsPreservationRecordAPIService;
import com.bcxin.ins.third.gzzrx.changan.GZZRX_PackageMessageChangAn;
import com.bcxin.ins.third.tyx.changan.TYX_CARequestService;
import com.bcxin.ins.third.tyx.changan.TYX_PackageMessageChangAn;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.DictConst;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.ResultDto;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.http.HttpUtil;
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;
import java.util.Map;

/**
 * <b> 长安-团意险接口Controller控制器，用于回调 </b>
 * @author ZXF
 * @create 2021/03/01 0001 10:03
 * @version
 * @注意事项 </b>
 */
@Controller
public class TYX_CA_API_Controller extends BaseController {


	@Autowired
	private PolicyService policyService;
	@Autowired
	private InsPreservationRecordAPIService insPreservationRecordAPIService;
	@Autowired
	private TYX_CARequestService tYX_CARequestService;

	/**
	 * 长安团意险回调地址（在用）
	 * //		支付成功后渠道平台会使用http + post方式调用该链接，并且支付相关信息通过URL参数形式返回
	 * //		订单号：orderNo
	 * //		支付方式：payType
	 * //		刷卡流水号：cardSerialNo
	 * //		支付时间：payTime
	 * //		请求方：parterId
	 * //		订单类型：orderType
	 * //		校验码：passWord
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/CA-API/TYX/Policy-Opinion")
	@ResponseBody
	public Result PolicyOpinion() {
		logger.info("团意险承保完成后页面展示-star");
		String orderNo = getRequest().getParameter("orderNo");
		String payType = getRequest().getParameter("payType");
		String tradeNo = getRequest().getParameter("tradeNo");
		String payTime = getRequest().getParameter("payTime");
		String parterId = getRequest().getParameter("parterId");
		String orderType = getRequest().getParameter("orderType");
		String passWord = getRequest().getParameter("passWord");
		Map<String,String> map = Maps.newHashMap();
		map.put("payType",payType);
		map.put("tradeNo",tradeNo);
		map.put("payTime",payTime);
		map.put("orderNo",orderNo);
		map.put("parterId",parterId);
		map.put("orderType",orderType);
		map.put("passWord",passWord);
		logger.info("====团意险,param:"+map.toString());
		policyService.CA_TYX_SAVE_PAY_MSG(map);
		logger.info("团意险承保完成后页面展示-ca-pay-service：orderNo:"+orderNo);
		OrderFormVo dto = policyService.getPolicyDtoByRcptNo(orderNo);
		if(DictConst.ORDER_STATUS_YCB.equals(dto.getPolicy_status())){
			return Result.success("数据接收成功");
		}
		return Result.fail("数据处理失败");
	}

	@RequestMapping(value = "/CA-API/TYX/BU-Policy-Opinion")
	@ResponseBody
	public Result BUPolicyOpinion() {
		logger.info("团意险承保完成后页面展示-star");
		String orderNo = getRequest().getParameter("orderNo");
		String payType = getRequest().getParameter("payType");
		String tradeNo = getRequest().getParameter("tradeNo");
		String payTime = getRequest().getParameter("payTime");
		String parterId = getRequest().getParameter("parterId");
		String orderType = getRequest().getParameter("orderType");
		String passWord = getRequest().getParameter("passWord");
		String policyNo = getRequest().getParameter("policyNo");
		String eUrl = getRequest().getParameter("eUrl");
		Map<String,String> map = Maps.newHashMap();
		map.put("payType",payType);
		map.put("tradeNo",tradeNo);
		map.put("payTime",payTime);
		map.put("orderNo",orderNo);
		map.put("parterId",parterId);
		map.put("orderType",orderType);
		map.put("passWord",passWord);
		map.put("policyNo",policyNo);
		map.put("eUrl",eUrl);
		logger.info("====团意险,param:"+map.toString());
		policyService.BU_CA_TYX_SAVE_PAY_MSG(map);
		logger.info("团意险承保完成后页面展示-ca-pay-service：orderNo:"+orderNo);
		OrderFormVo dto = policyService.getPolicyDtoByRcptNo(orderNo);
		if(DictConst.ORDER_STATUS_YCB.equals(dto.getPolicy_status())){
			return Result.success("数据接收成功");
		}
		return Result.fail("数据处理失败");
	}

	/**
	 * <b> 申请电子发票 </b>
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/CA-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_CARequestService.request_ca_dzfp(oid, TransTypeEnum.DZFP.getValue(),"","","");
		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[1],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);
		}
	}

	/**
	 * 长安团意险线下支付结果回调地址（在用）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/CA-API/TYX/Policy-Opinion-Offline")
	@ResponseBody
	public String PolicyOpinionOffline(@RequestBody String xml) throws UnsupportedEncodingException {
		logger.info("长安团意险线下支付结果回调-star");
		if(xml.contains("%3C%")){
			xml = URLDecoder.decode(xml, ConstProp.ENCODE_UTF8);
		}
		TYX_PackageMessageChangAn gpm = new TYX_PackageMessageChangAn();
		String result = gpm.returnAnalysisXML(xml,"21","");//200#投保单号#保单号#电子保单链接
		String[] arr = result.split("#");
		if(ConstProp.CODE_FAILURE.equals(arr[0])){
			return xmlXXZFResult("false",arr[1],"");
		}
		Map<String,String> map = Maps.newHashMap();
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		map.put("payType","offlinepay");
		map.put("tradeNo",String.valueOf(idWorker.nextId()));
		map.put("payTime", DateUtil.getCurrentDateTime());
		map.put("orderNo",arr[1]);
		map.put("policyNo",arr[2]);
		map.put("eUrl",arr[3]);
		logger.info("长安团意险线下支付结果回调-PolicyOpinionOffline：param:"+map.toString());
		policyService.BU_CA_TYX_SAVE_PAY_MSG(map);
		OrderFormVo dto = policyService.getPolicyDtoByRcptNo(map.get("orderNo"));
		if(dto==null){
			return xmlXXZFResult("false","订单不存在","");
		}
		if(DictConst.ORDER_STATUS_YCB.equals(dto.getPolicy_status())){
			return xmlXXZFResult("true","数据接收成功","");
		}
		return xmlXXZFResult("false","数据处理失败","");
	}

	/**
	 * <b> 批单结果回调 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:58
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping(value = "/CA-API/TYX/Endorsement-Opinion")
	public void EndorsementOpinion(@RequestBody String json) throws UnsupportedEncodingException {
		json = URLDecoder.decode(json, ConstProp.ENCODE_UTF8);
		logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：请求报文-"+json);
		String[] arr = json.split("&");
		String[] mArr;
		Map<String,String> reqMap = Maps.newHashMap();
		for(int i=0;i<arr.length;i++){
			mArr=arr[i].split("=");
			if(mArr.length==1){
				reqMap.put(mArr[0],"");
			}else{
				reqMap.put(mArr[0],mArr[1]);
			}
		}
		if(StringUtils.isEmpty(reqMap.get("UnderwriteFlag"))||ConstProp.DIGIT_ZERO.equals(reqMap.get("UnderwriteFlag"))){
			renderString(response, "{\"ResponseCode\": \"1\",\"ErrorMessage\": \"成功\"}", ConstProp.CT_JSON);
			logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：业务结束：end");
			return;
		}
		InsPreservationRecord record = insPreservationRecordAPIService.findInsPreservationRecordBySerialNumber(reqMap.get("CertiNo"));
		if(record == null){
			renderString(response, "{\"ResponseCode\": \"0\",\"ErrorMessage\": \"未找到批单记录\"}", ConstProp.CT_JSON);
			logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：业务结束：end");
			return;
		}
		if(DictConst.REVISE_STATUS_BTG.equals(record.getRevise_status())||DictConst.REVISE_STATUS_TG.equals(record.getRevise_status())||DictConst.REVISE_STATUS_SX.equals(record.getRevise_status())){
			renderString(response, "{\"ResponseCode\": \"1\",\"ErrorMessage\": \"接收成功，当前为重复访问\"}", ConstProp.CT_JSON);
			logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：业务结束：end");
			return;
		}
		Map map = Maps.newHashMap();
		map.put("recordId",String.valueOf(record.getIns_preservation_record_id()));
		if(ConstProp.DIGIT_ZERO.equals(reqMap.get("UnderwriteFlag"))||ConstProp.DIGIT_TWO.equals(reqMap.get("UnderwriteFlag"))){
			map.put("remark",reqMap.get("UnderwriteOpinion"));
			map.put("recordStatus","3");
		}else{
			map.put("recordStatus","4");
			map.put("reviseSerialNumIns",reqMap.get("EndorNo"));
		}
		String token = "";
		try{
			token = JwtUtil.createJWT(map,JwtUtil.JWT_SECRET,JwtUtil.JWT_REFRESH_TTL);
		}catch (Exception e){
			e.printStackTrace();
		}
		String url = GlobalResources.WEB_URL+"/api/myApply/updataCAReviseStatus?token="+token;
		map = Maps.newHashMap();
		map.put("token",token);
		String ret = HttpUtil.get(url);
		Result r = JSON.parseObject(ret, Result.class);
		if(Result.ERROR.equals(r.getRetType())){
			renderString(response, "{\"ResponseCode\": \"0\",\"ErrorMessage\": \""+r.getMsg()+"\"}", ConstProp.CT_JSON);
			logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：业务结束：end");
			return;
		}
		renderString(response, "{\"ResponseCode\": \"1\",\"ErrorMessage\": \"成功\"}", ConstProp.CT_JSON);
		logger.info("批单结果回调-Endorsement-Opinion-CA-TYX：业务结束：end");
	}

	public static void main(String[] args) {
		String xml = "passWord=&parterId=baichuanxin&orderType=02&payType=Alipay&orderNo=227112021Y43000000006&tradeNo=null&payTime=2021-11-11 16:20:07}";
		String[] arr = xml.split("&");
		String[] mArr;
		Map<String,String> reqMap = Maps.newHashMap();
		for(int i=0;i<arr.length;i++){
			mArr=arr[i].split("=");
			if(mArr.length==1){
				reqMap.put(mArr[0],"");
			}else{
				reqMap.put(mArr[0],mArr[1]);
			}

		}
		System.out.println(reqMap);
		String url = "http://localhost:8080/CA-API/TYX/Policy-Opinion";
		Map map = Maps.newHashMap();
		map.put("xml",xml);
		String ret = HttpUtil.post(url,xml);
		System.out.println(ret);
	}

	/**
	 * <b> 返回结果处理 </b>
	 * @ChannelTradeSerialNo 渠道交易流水号（一次交易标识）
	 * @ResponseCode 错误编码：0失败，1成功
	 * @ErrorMessage 错误信息
	 * @proposalNo 渠道交易流水号（一次交易标识）
	 * @type 回调类型：0核保结果回调，1保单结果回调，2批单结果回调
	 *
	 * @author ZXF
	 * @create 2021/03/01 0001 17:25
	 * @version
	 * @注意事项 </b>
	 */
	private static String xmlResult(String ChannelTradeSerialNo, String ResponseCode, String ErrorMessage, int type) {
		String xmlResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				xmlResult += "<HEAD>";
				if(type == 0) {
					xmlResult += "<ChannelTradeSerialNo>" + ChannelTradeSerialNo + "</ChannelTradeSerialNo>";
				}
				if(type == 1) {
					xmlResult += "<proposalNo>" + ChannelTradeSerialNo + "</proposalNo>";
				}
				xmlResult += "<ResponseCode>"+ResponseCode+"</ResponseCode>";
				xmlResult += "<ErrorMessage>"+ErrorMessage+"</ErrorMessage>";
				xmlResult += "</HEAD>";
		return xmlResult;
	}

	/**
	 * <b> 批单确认返回结果处理 </b>
	 * @ChannelTradeSerialNo 渠道交易流水号（一次交易标识）
	 * @ResponseCode 错误编码：0失败，1成功
	 * @ErrorMessage 错误信息
	 *
	 * @author ZXF
	 * @create 2021/03/01 0001 17:25
	 * @version
	 * @注意事项 </b>
	 */
	private static String xmlPDQRResult(String ResponseCode, String ErrorMessage) {
		String xmlResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				xmlResult += "<response>";
				xmlResult += "<responseHead>";
				xmlResult += "<appCode>"+ResponseCode+"</ResponseCode>";
				xmlResult += "<appMessage>"+ErrorMessage+"</ErrorMessage>";
				xmlResult += "</responseHead>";
				xmlResult += "</response>";
		return xmlResult;
	}

	/**
	 * <b> 线下支付回调接收结果 </b>
	 * @ResponseCode 错误编码：0失败，1成功
	 * @ErrorMessage 错误信息
	 *
	 * @author ZXF
	 * @create 2021/03/01 0001 17:25
	 * @version
	 * @注意事项 </b>
	 */
	private static String xmlXXZFResult(String ResponseCode, String ErrorMessage, String sign) {
		String xmlResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		xmlResult += "<Root>";
		xmlResult += "<ResponseHead>";
		xmlResult += "<Sign>"+sign+"</Sign>";
		xmlResult += "</ResponseHead>";
		xmlResult += "<ResponseBody>";
		xmlResult += "<ResultFlag>"+ResponseCode+"</ResultFlag>";
		xmlResult += "<Message>"+ErrorMessage+"</Message>";
		xmlResult += "<TimeStamp>"+System.currentTimeMillis()+"</TimeStamp>";
		xmlResult += "</ResponseBody>";
		xmlResult += "</Root>";
		return xmlResult;
	}

}

