package com.bcxin.ins.coninsweb.order.controller.api.gzzrx.pingancai;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.third.gzzrx.pingancai.GZZRX_PACRequestService;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <b> 平安财-雇主责任险接口Controller控制器，用于回调 </b>
 * @author ZXF
 * @create 2019/11/14 0014 17:32
 * @version
 * @注意事项 </b>
 */
@Controller
public class GZZRX_PAC_API_Controller extends BaseController {


	@Autowired
	private PolicyService policyService;

	@Autowired
	private GZZRX_PACRequestService pACRequestService;

	public static final String SUCCESS = "0";

	public static final String FAIL = "-1";

	/**
	 * 支付接口回调
	 * {
	 * dataSource:"数据来源",
	 * businessNo:"通知单号",
	 * bankOrderNo:"订单号/银行流水",
	 * paymentSum:"支付金额",
	 * remark:"备注",【非必传】
	 * paymentDate:"支付时间
	 * paymentState:"支付结果1-成功，2-失败",
	 * errorMsg:"交易结果信息/失败描述
	 * signMsg:"加签串
	 * policyNo:"如果支付成功，则自动承保，并返回保单号
	 * resultCode:承保结果 1支付成功且承保成功，2支付成功承保失败，3支付失败；
	 * resultMsg:承保信息；
	 * }
	 * @param response
	 */
	@RequestMapping(value = "/PAC-API/GZZRX/callbackPay")
	@ResponseBody
	public String callbackPay(HttpServletResponse response, @RequestBody PingAnCaiTYXPayVo pacVo){

		logger.info("支付接口回调-callbackPay-PAC-GZZRX：");
		JSONObject json = new JSONObject();
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		try {
			if(pacVo == null){
				json.put("responseCode","2");
				json.put("responseMsg","未接收到交易信息！");
				logger.info("支付接口回调-callbackPay-PAC-GZZRX：【未接收到交易信息"+pacVo.getPolicyNo()+"】业务结束：end");
				return json.toString();
			}
			if(!getRequestTime(ConstProp.REDIS_HEAD_POLICY_NO+"GZZRXCALLBACKPAY"+pacVo.getPolicyNo(),60)){
				json.put("responseCode","2");
				json.put("responseMsg","禁止短时重复访问！");
				logger.info("支付接口回调-callbackPay-PAC-GZZRX：【禁止短时重复访问"+pacVo.getPolicyNo()+"】业务结束：end");
				return json.toString();
			}
			setRequestTime(ConstProp.REDIS_HEAD_POLICY_NO+"GZZRXCALLBACKPAY"+pacVo.getPolicyNo());
			Map<String, String> requestMap = pacVo.toMap();
			logger.info("支付接口回调-callbackPay-PAC-GZZRX：【"+pacVo.getPolicyNo()+"】接收到数据-"+requestMap.toString());
			if(("999999".equals(pacVo.getResultCode())||"SUCCESS".equals(pacVo.getResultCode()))&&StringUtils.isNotEmpty(pacVo.getPolicyNo())){
				if(policyService.PAC_GZZRX_SAVE_PAY_MSG(requestMap)){
					logger.info("支付接口回调-callbackPay-PAC-GZZRX：数据更新成功-承保完成");
					json.put("responseCode","1");
					json.put("responseMsg","接收成功！");
				} else {
					logger.info("支付接口回调-callbackPay-PAC-GZZRX：承保失败");
					json.put("responseCode","2");
					json.put("responseMsg","信息处理出现异常！");
				}
			}else{
				logger.info("支付接口回调-callbackPay-PAC-GZZRX：支付失败或缺少保单号信息");
				json.put("responseCode","2");
				json.put("responseMsg","信息处理出现异常！");
			}
		}catch (Exception ex){
			logger.info("支付接口回调-callbackPay-PAC-GZZRX：接收失败--");
			logger.error("支付接口回调-ERRO:",ex);
			json.put("responseCode","2");
			json.put("responseMsg","信息处理出现异常！");
		}
		logger.info("支付接口回调-callbackPay-PAC-GZZRX：接口返回数据-"+json.toString());
		logger.info("支付接口回调-callbackPay-PAC-GZZRX：业务结束：end");
		return json.toString();
	}

	/**
	 * <b> 申请电子发票 </b>
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/PAC-API/GZZRX/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 = pACRequestService.requestPAC(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-GZZRX-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);
		}
	}

	/**
	 * <b> 订单补承保 </b>
	 * 当用户支付后，未成功接收到保险接口回传的保单信息，可以调该接口去查询承保信息，并保存承保信息，将订单变更为承保状态
	 * @param oid 订单id
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/PAC-API/GZZRX/REPAIR_CB/{oid}")
	@ResponseBody
	public ResultDto repairCB(@PathVariable long oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto == null || !DictConst.ORDER_STATUS_DZF.equals(dto.getPolicy_status())){
			return new ResultDto("订单不符合承保条件！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		String result = pACRequestService.requestPAC(oid, TransTypeEnum.CBXX.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])||StringUtils.isEmpty(strs[2])){
			return new ResultDto("（APP-GZZRX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		PingAnCaiTYXPayVo pacVo = new PingAnCaiTYXPayVo();
		pacVo.setNoticeNo(dto.getNotice_no());
		pacVo.setApplyPolicyNo(strs[2]);
		pacVo.setPolicyNo(strs[1]);
		pacVo.setTradeNo(String.valueOf(idWorker.nextId()));
		pacVo.setPaymentSum(strs[3]);
		Map<String, String> requestMap = pacVo.toMap();
		logger.info("补承保接口-REPAIR_CB-PAC-GZZRX：承保信息-"+requestMap.toString());
		if(policyService.PAC_TYX_SAVE_PAY_MSG(requestMap)){
			logger.info("支付接口回调-REPAIR_CB-PAC-GZZRX：数据更新成功-承保完成");
			return new ResultDto("承保信息已补充！", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		} else {
			logger.info("支付接口回调-REPAIR_CB-PAC-GZZRX：承保失败");
			return new ResultDto("承保信息补充失败！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	/**
	 * <b> 如果申请批单成功，但是确认批单步骤失败，就调该方法 </b>
	 * 参数拿申请批单返回的报文信息：200#保单号#批单号#保费#批单申请号
	 * @author ZXF
	 * @create 2019/11/04 0004 10:11
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/PAC-API/GZZRX/BU_PD")
	@ResponseBody
	public String buPD(String result) throws Exception {
		//200#保单号#批单号#保费#批单申请号
//		String result = "200#10162003900158369209#1#155#70162001900699850312#1190168033767845888";
		return pACRequestService.pdqr(TransTypeEnum.PDQR.getValue(),result);
	}

	public static void main(String[] args) {
		PingAnCaiTYXPayVo pacVo = new PingAnCaiTYXPayVo();
//		pacVo.setPolicyNo("10126003901346881210");pacVo.setApplyPolicyNo("50126003901779772103");pacVo.setPaymentSum("1950.00");pacVo.setNoticeNo("01120006000659137350");pacVo.setTradeNo("1422381836033716224");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346871280");pacVo.setApplyPolicyNo("50126003901779761575");pacVo.setPaymentSum("8450.00");pacVo.setNoticeNo("01120006000659134957");pacVo.setTradeNo("1422380622961307648");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346861389");pacVo.setApplyPolicyNo("50126003901779752278");pacVo.setPaymentSum("2925.00");pacVo.setNoticeNo("01120006000659132871");pacVo.setTradeNo("1422379561244553216");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346849741");pacVo.setApplyPolicyNo("50126003901779737450");pacVo.setPaymentSum("2925.00");pacVo.setNoticeNo("01120006000659129590");pacVo.setTradeNo("1422377854028607488");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346839539");pacVo.setApplyPolicyNo("50126003901779724462");pacVo.setPaymentSum("9750.00");pacVo.setNoticeNo("01120006000659126854");pacVo.setTradeNo("1422376321962602496");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346826800");pacVo.setApplyPolicyNo("50126003901779706974");pacVo.setPaymentSum("2925.00");pacVo.setNoticeNo("01120006000659122948");pacVo.setTradeNo("1422374271929413632");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346824783");pacVo.setApplyPolicyNo("50126003901779694863");pacVo.setPaymentSum("9750.00");pacVo.setNoticeNo("01120006000659120620");pacVo.setTradeNo("1422372860202184704");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346789283");pacVo.setApplyPolicyNo("50126003901779659822");pacVo.setPaymentSum("4550.00");pacVo.setNoticeNo("01120006000659113971");pacVo.setTradeNo("1422368603323363328");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346783635");pacVo.setApplyPolicyNo("50126003901779649144");pacVo.setPaymentSum("2600.00");pacVo.setNoticeNo("01120006000659111951");pacVo.setTradeNo("1422367236793954304");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346775080");pacVo.setApplyPolicyNo("50126003901779641024");pacVo.setPaymentSum("3900.00");pacVo.setNoticeNo("01120006000659110402");pacVo.setTradeNo("1422366171696590848");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346618776");pacVo.setApplyPolicyNo("50126003901779442043");pacVo.setPaymentSum("2925.00");pacVo.setNoticeNo("01120006000659070286");pacVo.setTradeNo("1422162762699763712");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346604391");pacVo.setApplyPolicyNo("50126003901779437497");pacVo.setPaymentSum("4225.00");pacVo.setNoticeNo("01120006000659069100");pacVo.setTradeNo("1422161224669458432");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346601866");pacVo.setApplyPolicyNo("50126003901779431768");pacVo.setPaymentSum("6500.00");pacVo.setNoticeNo("01120006000659067563");pacVo.setTradeNo("1422159532053884928");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346582506");pacVo.setApplyPolicyNo("50126003901779409235");pacVo.setPaymentSum("2275.00");pacVo.setNoticeNo("01120006000659061313");pacVo.setTradeNo("1422152873030053888");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346575749");pacVo.setApplyPolicyNo("50126003901779403126");pacVo.setPaymentSum("5200.00");pacVo.setNoticeNo("01120006000659059395");pacVo.setTradeNo("1422151127247482880");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346563434");pacVo.setApplyPolicyNo("50126003901779387416");pacVo.setPaymentSum("1300.00");pacVo.setNoticeNo("01120006000659054687");pacVo.setTradeNo("1422146924152221696");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346561602");pacVo.setApplyPolicyNo("50126003901779304506");pacVo.setPaymentSum("1300.00");pacVo.setNoticeNo("01120006000659030282");pacVo.setTradeNo("1422130075784048640");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346276614");pacVo.setApplyPolicyNo("50126003901779020576");pacVo.setPaymentSum("6175.00");pacVo.setNoticeNo("01120006000658948865");pacVo.setTradeNo("1422091356582572032");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346242771");pacVo.setApplyPolicyNo("50126003901778980030");pacVo.setPaymentSum("3575.00");pacVo.setNoticeNo("01120006000658938426");pacVo.setTradeNo("1422086100981248000");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346224397");pacVo.setApplyPolicyNo("50126003901778957046");pacVo.setPaymentSum("3250.00");pacVo.setNoticeNo("01120006000658932522");pacVo.setTradeNo("1422082875234316288");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346199844");pacVo.setApplyPolicyNo("50126003901778913600");pacVo.setPaymentSum("2925.00");pacVo.setNoticeNo("01120006000658921980");pacVo.setTradeNo("1422076574244663296");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
//		pacVo.setPolicyNo("10126003901346168293");pacVo.setApplyPolicyNo("50126003901778884236");pacVo.setPaymentSum("1625.00");pacVo.setNoticeNo("01120006000658914856");pacVo.setTradeNo("1422071153475842048");pacVo.setPaymentState("20");pacVo.setPartnerCode("P_BCXZR_GP");pacVo.setDataSource("2");pacVo.setResultCode("SUCCESS");
		String jsonObject = postJsonString("http://www.bailianbao.cn/PAC-API/GZZRX/callbackPay", JSONObject.toJSONString(pacVo));
		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 "";
	}
}

