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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.third.build.yangguang.util.SendUtils;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.third.zzx.pingancai.ZZX_PACRequestService;
import com.bcxin.ins.third.zzx.pingancai.ZZX_PackageMessagePingAnCai;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.MD5Util;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

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


	@Autowired
	private PolicyService policyService;
	@Autowired
	private ZZX_PACRequestService zZX_PACRequestService;

	public static final String SUCCESS = "0";

	public static final String FAIL = "-1";

	/**
	 * 撤单
	 */
	@RequestMapping(value = "/PAC-API/ZZX/testPingAnCheDan")
	public void  testPingAnCheDan(){

		try {
			String json = ZZX_PackageMessagePingAnCai.marshal(null, null, ConstProp.DIGIT_FOUR,null);

			logger.info(json);
			String url ="https://test-api.pingan.com.cn:20443/open/appsvr/annuity/openapi/receive/service?access_token="+policyService.pnc_access_token();
//			String  url ="http://test-api.pingan.com.cn:20080/oauth/oauth2/access_token?client_id=P_EGIS_DAP_TEST&grant_type=client_credentials&client_secret=2TgXtn72";
			logger.info("开始时间"+System.currentTimeMillis());
//			String returnJson=HttpClientUtil.doRequest(url, json);
			String ret = RequestUtil.initHttp().doPost(url, json, "application/json", "UTF-8");
			logger.info("返回字段"+ret);
			String result= ZZX_PackageMessagePingAnCai.returnAnalysisJson(ret,ConstProp.DIGIT_FOUR);
			logger.info(result);
			logger.info("结束时间"+System.currentTimeMillis());


		}catch (Exception ex){
			logger.error("testPingAnCheDan",ex);
//			ex.printStackTrace();
		}

	}

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

		logger.info("支付接口回调-callbackPay-PAC-ZZX：");
		JSONObject json = new JSONObject();
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		try {
			if(pacVo == null){
				json.put("errno",ConstProp.DIGIT_TWO);
				json.put("errmsg","未接收到交易信息！");
				logger.info("支付接口回调-callbackPay-PAC-ZZX：接口返回数据-"+json.toString());
				logger.info("支付接口回调-callbackPay-PAC-ZZX：业务结束：end");
				return json.toString();
			}
			Map<String, String> requestMap = pacVo.toMap();
			logger.info("支付接口回调-callbackPay-PAC-ZZX：接收到数据-"+requestMap.toString());
			if(ConstProp.DIGIT_ONE.equals(requestMap.get("paymentState"))){
				if(policyService.PAC_ZZX_SAVE_PAY_MSG(requestMap)){
					logger.info("支付接口回调-callbackPay-PAC-ZZX：数据更新成功-承保完成");
					json.put("errno",ConstProp.DIGIT_ONE);
					json.put("errmsg","已承保！");
				} else {
					logger.info("支付接口回调-callbackPay-PAC-ZZX：承保失败");
					json.put("errno",ConstProp.DIGIT_TWO);
					json.put("errmsg","承保过程出现异常！");
				}
			}else{
				logger.info("支付接口回调-callbackPay-PAC-ZZX：Fail,"+requestMap.get("errorMsg"));
				json.put("errno",ConstProp.DIGIT_TWO);
				json.put("errmsg","支付回调接收到失败信息，中断业务！");
			}
		}catch (Exception ex){
			logger.info("支付接口回调-callbackPay-PAC-ZZX：接收失败--");
			logger.error("支付接口回调-ERRO:",ex);
			json.put("errno",ConstProp.DIGIT_TWO);
			json.put("errmsg","信息处理出现异常！");
		}
		logger.info("支付接口回调-callbackPay-PAC-ZZX：接口返回数据-"+json.toString());
		logger.info("支付接口回调-callbackPay-PAC-ZZX：业务结束：end");
		return json.toString();
	}

	public static void main(String[] args) {
		PingAnCaiPayVo pacVo = new PingAnCaiPayVo();
		pacVo.setPaymentState("1");
		pacVo.setPaymentDate("2018-10-29 10:35:05");
		pacVo.setPaymentSum("2350");
		pacVo.setPolicyNo("13076013900542460538");
		pacVo.setBusinessNo("30080006000367598288");

		String url = "http://www.bailianbao.cn/PAC-API/ZZX/callbackPay";
		try {
			String a = SendUtils.httpSendReceiverForUTF8(url,JSONObject.toJSONString(pacVo));
			System.out.println(a);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 组装支付数据(平安收银台)pc端
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/PAC-API/ZZX/paCheckstand")
	@ResponseBody
	public String paCheckstand(HttpServletResponse response, HttpServletRequest request ){
		String oid = request.getParameter("oid");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(StringUtils.isNotEmpty(oid)&& userdetail != null){
			OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
			try{
				String url= GlobalResources.PN_INS_URL + "/open/appsvr/property/financialPayments?access_token="+policyService.pnc_access_token();
				return ZZX_PackageMessagePingAnCai.pay_pc(dto,url);//收据号，多少钱， 地址
			}catch (Exception ex){
				logger.error("pc端组装支付数据(平安收银台)",ex);
			}
		}
		return ConstProp.BLANK_CHAR;
	}

	/**
	 * 组装支付数据(平安收银台)移动端调用支付请求数据
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/PAC-API/ZZX/paCheckstandAPP")
	@ResponseBody
	public String paCheckstandAPP(HttpServletResponse response, HttpServletRequest request ){
		String oid = request.getParameter("oid");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(StringUtils.isNotEmpty(oid)/*&& userdetail != null*/){
			OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
			try{
				String url= GlobalResources.PN_INS_URL + "/open/appsvr/property/applyCustToFinance?access_token="+policyService.pnc_access_token();
				return ZZX_PackageMessagePingAnCai.pay_app(dto,url);//收据号，多少钱， 地址
			}catch (Exception ex){
				logger.error("移动端组装支付数据(平安收银台)",ex);
			}
		}
		return ConstProp.BLANK_CHAR;
	}


	/**
	 * 平安分账(对账)
	 * @param response
	 */
	@RequestMapping(value = "/PAC-API/ZZX/pa_reconciliation")
	public @ResponseBody String pa_reconciliation(PingAnReconciliationVo vo, HttpServletResponse response){
		JSONObject json = new JSONObject();
		try {
			if(StringUtils.isEmpty(vo.getRequestId())||StringUtils.isEmpty(vo.getClientType())||StringUtils.isEmpty(vo.getToken())||StringUtils.isEmpty(vo.getAccountCheckResult())||StringUtils.isEmpty(vo.getReceiptNo())){
				json.put("status",1001);
				json.put("msg","参数不能为空");
				return json.toString();
			}
			if(!"P_ABC123".equals(vo.getClientType())){
				json.put("status",1002);
				json.put("msg","平台标识有错");
				return json.toString();
			}
			if(!MD5Util.string2MD5(vo.getRequestId()+vo.getClientType()+"pingan").equals(vo.getToken())){
				json.put("status",1003);
				json.put("msg","密钥错误");
				return json.toString();
			}
			logger.info("fenzhang"+vo.toString());
			json.put("status",200);
			json.put("msg","接收成功");
			//根据vo.getAccountCheckResult()的值对账，3已承保未支付成功（人工处理），5已支付未承保（补做承保动作）
			if("3".equals(vo.getAccountCheckResult())){//3已承保未支付成功（人工处理）发短信或交由客服
				OrderFormVo dto = policyService.getPolicyDtoByRcptNo(vo.getReceiptNo());
				if(dto!=null){
					String emailTitle = "【平安财险】展会责任险-订单问题";
					String  emailContent="<h3>订单对账问题</h3> <p>订单编号为："+dto.getTrade_serial_number()+"请跟进处理</p> ";
				}else{
					String emailTitle = "【平安财险】展会责任险-订单问题";
					String  emailContent="<h3>订单对账问题</h3> <p>投保单号为："+vo.getReceiptNo()+"内部数据不存在</p> ";
				}
			}else if("5".equals(vo.getAccountCheckResult())){//5已支付未承保（补做承保动作）
				policyService.pa_reconciliation_underwrite(vo.getReceiptNo(),vo.getExternalReference());
			}
		}catch (Exception ex){
			logger.error("接收失败",ex);
			json.put("status",300);
			json.put("msg","接收失败");
		}
		return json.toString();
	}

}

