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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.third.build.yangguang.util.SendUtils;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.third.zzx.yongan.*;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.PolicyTransactionVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
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 java.util.Date;
import java.util.List;

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

	@Autowired
	private PolicyService policyService;
	@Autowired
	private InsTransactionAPIService insTransactionAPIService;
	@Autowired
	private ZZX_YARequestService zZX_YARequestService;

//	private final static String PWD = "1234567890";

	/**
	 * 支付接口回调
	 * @param request 包含签名sign
	 * @param json 请求报文
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="永安展责险-支付接口回调")
	@RequestMapping(value = "/YA-API/ZZX/callbackPay")
	public @ResponseBody String callbackPay(HttpServletRequest request, @RequestBody String json) throws Exception {
		String sign = request.getParameter("sign");//挂在地址栏的签名
		//TODO 发现未知来源频繁请求接口，暂关闭入口
		if(StringUtils.isNotEmpty(sign)){
			return "{\"ret\":\"-2\",\"msg\":\"接口已关闭！\"}";
		}
		String result = "";
		YARequestVo reqVo = JSONObject.parseObject(json, YARequestVo.class);
		logger.info("支付接口回调-callbackPay-YA-ZZX：请求报文-"+reqVo.toString()+", sign-"+sign);
		if(checkSign(sign, json, reqVo)){
			YAReqBodyVo body = reqVo.getBody().get(0);
			OrderFormVo orderVo = policyService.getPolicyDtoByRcptNo(body.getSerialno());
			if(orderVo != null){
				if(StringUtils.isEmpty(orderVo.getExternal_reference())){
					try {
						PolicyTransactionVo vo= new PolicyTransactionVo();
						//保存保单号
						vo.setPolicy_number(body.getPolicyno());
						vo.setPolicy_id(orderVo.getOid());
						insTransactionAPIService.savePolicyExternalReference(vo);
						String path = getDZBDPath(reqVo.getHeader().getUser(), GlobalResources.YA_ZZ_PWD, body.getPolicyno());
						logger.info("支付接口回调-callbackPay-YA-ZZX：获取电子保单地址："+path);
						//保存保单地址
						path = ZZX_YARequestService.unloading_ya(path);//根据保险公司的电子保单下载地址将文件转存到我们自己平台
						vo.setInsure_path(path);//保单地址
						insTransactionAPIService.savePolicyOther(vo);
						result = setResJson(reqVo, "0", "数据处理成功");
					}catch (Exception e){
						logger.error("永安展责支付回调接口-数据更新数据库发生异常："+e.getMessage());
						result = setResJson(reqVo, "1", "数据更新发生异常");
					}
					/*new Thread(()->{ //异步发送保全邮件
						try {
							//返回订单给指定平台
							policyService.returnsAnOrderToTheSpecifiedPlatform(orderVo.getOid());
						} catch(Exception e) {
							logger.error("------------雇主责任险推送百保盾，异常："+e.getMessage());
						}
					}).start();*/
				}else{
					logger.info("支付接口回调-callbackPay-YA-ZZX：已存在保单号-"+orderVo.getExternal_reference()+"，报文保单号-"+body.getPolicyno());
					result = setResJson(reqVo, "0", "保单号已录入");
				}
			}else{
				result = setResJson(reqVo, "1", "未匹配到相应订单信息");
			}
		}else{
			result = setResJson(reqVo, "1", "签名校验失败");
		}
		logger.info("支付接口回调-callbackPay-YA-ZZX：接口返回数据-"+result);
		return result;
	}

	private String setResJson(YARequestVo reqVo, String flag, String message) throws Exception{
		YAResponseVo resVo = new YAResponseVo();
		YAResHeaderVo yhVo = new YAResHeaderVo();
		MyConverUtil.map2PO(MyConverUtil.PO2Map(reqVo.getHeader()), yhVo);
		yhVo.setFlag("0");
		yhVo.setTimestamp(String.valueOf((new Date()).getTime()));
		resVo.setHeader(yhVo);
		List<YAResBodyVo> ybVoList = Lists.newArrayList();
		YAResBodyVo ybVo = new YAResBodyVo();
		ybVo.setFlag(flag);
		ybVo.setMessage(message);
		ybVo.setSerialno(reqVo.getBody().get(0).getSerialno());
		ybVoList.add(ybVo);
		resVo.setBody(ybVoList);
		return JSONObject.toJSONString(resVo);
	}

	private static boolean checkSign(String sign, String json, YARequestVo reqVo){
		if(StringUtils.isNotEmpty(sign)){
			String text = reqVo.getHeader().getUser()+GlobalResources.YA_ZZ_PWD+reqVo.getHeader().getCcardbsnstyp()+json;
			System.out.println("字符串文本："+text);
			String nowSign = MD5Util.string2MD5(text);
			System.out.println("字符串MD5："+nowSign);
			return sign.equals(nowSign);
		}
		return false;
	}

	private String getDZBDPath(String user, String password, String policyno){
		String text = user + password + policyno;
		System.out.println("DZBD-字符串文本："+text);
		String sign = MD5Util.string2MD5(text);
		System.out.println("DZBD-字符串MD5："+sign);
		return zZX_YARequestService.getUrlByTransType("4")+"?user="+user+"&policyno="+policyno+"&sign="+sign;
	}

	public static void main(String[] args) {
		/*String path = getDZBDPath("BCX", "1234567890", "26101026010021180000045");
		System.out.println(path);*/
		/*http://api.yaic.com.cn/yaicservice/apppdfServlet?user=BCX&policyno=23306000010021180000001&sign=5956e2dfec67e6d91ce90a31b48b5508*/
		String json = "{\"body\":[{\"begdate\":\"2018-11-17 00:00:00\",\"bkserial\":\"\",\"enddate\":\"2018-12-16 23:59:59\",\"paytype\":\"07\",\"policyno\":\"23306000010021180000001\",\"riskcode\":\"\",\"riskname\":\"\",\"serialno\":\"1062606496677883904\"}],\"header\":{\"ccardbsnstyp\":\"TIT_BCX\",\"checkcode\":\"3904\",\"code\":\"101\",\"timestamp\":\"1542180531\",\"user\":\"BCX\"}}";
		String sign = "223eea81eb7b0b3b1dcbbb427aea7f90";
		String url = "http://www.bailianbao.cn/YA-API/ZZX/callbackPay?sign=223eea81eb7b0b3b1dcbbb427aea7f90";
        try {
            String a = SendUtils.httpSendReceiverForUTF8(url,json);
            System.out.println(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
		/*YARequestVo reqVo = JSONObject.parseObject(json, YARequestVo.class);
		boolean b = checkSign(sign, json, reqVo);
		System.out.println(b);*/
		//http://tapi.yaic.com.cn/yaicservice/apppdfServlet?user=BDL&policyno=23303000069900150001031&sign=ee627d74e396f4fea4b6fd75f873e82f
	}
}

