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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.spring.listener.SessionContext;
import com.bcxin.ins.spring.util.JedisUtils;
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.tyx.pingancai.PACRequestService;
import com.bcxin.ins.util.IdWorker;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <b>平安财-公责险接口Controller控制器，用于回调</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Controller
public class TYX_PAC_API_Controller extends BaseController {


	@Autowired
	private PolicyService policyService;

	@Autowired
	private 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/TYX/callbackPay")
	@ResponseBody
	public String callbackPay(HttpServletResponse response, @RequestBody PingAnCaiTYXPayVo pacVo){

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

	/**
	 * <b> 申请电子发票 </b>
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/PAC-API/TYX/PRINT_INVOICE/{oid}")
	@ResponseBody
	public ResultDto printInvoice(@PathVariable long oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto == null || !"6".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-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);
		}
	}

	/**
	 * <b> 订单补承保 </b>
	 * 当用户支付后，未成功接收到保险接口回传的保单信息，可以调该接口去查询承保信息，并保存承保信息，将订单变更为承保状态
	 * @param oid 订单id
	 * @author ZXF
	 * @create 2019/11/01 0001 10:38
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/PAC-API/TYX/REPAIR_CB/{oid}")
	@ResponseBody
	public ResultDto repairCB(@PathVariable long oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto == null || !"4".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-TYX-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-TYX：承保信息-"+requestMap.toString());
		if(policyService.PAC_TYX_SAVE_PAY_MSG(requestMap)){
			logger.info("支付接口回调-REPAIR_CB-PAC-TYX：数据更新成功-承保完成");
			return new ResultDto("承保信息已补充！", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		} else {
			logger.info("支付接口回调-REPAIR_CB-PAC-TYX：承保失败");
			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/TYX/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.setNoticeNo("01090036000873096035");//已执行
		pacVo.setTradeNo("1691683446893703168");
		pacVo.setPaymentSum("3900.00");
		pacVo.setApplyPolicyNo("50143003902717013948");
		pacVo.setPartnerCode("P_BCX_GA");
		pacVo.setPolicyNo("10143003902147721524");
		pacVo.setResultCode("SUCCESS");
//		String jsonObject = postJsonString("http://www.bailianbao.cn/PAC-API/TYX/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 "";
	}
}

