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

import com.bcxin.ins.third.zzx.zhongan.dto.CashierConfig;
import com.bcxin.ins.third.zzx.zhongan.dto.CashierConstant;
import com.bcxin.ins.third.zzx.zhongan.dto.CashierMD5Util;
import com.bcxin.ins.third.zzx.zhongan.dto.CashierSubmitUtil;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/ZA-API")
public class ZZX_ZA_API_Controller extends BaseController {


	@Autowired
	private PolicyService policyService;

	@Autowired
	private ProductService productService;

	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;
	/**
	 * 测试
	 */
	@RequestMapping(value = "/testZA")
	public void  testZA(){

		System.out.println(CashierConfig.APP_KEY);

	}

	/**
	 * 支付接口回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/callbackPay")
	public void  callbackPay(HttpServletRequest request,HttpServletResponse response) throws IOException{
		logger.info("支付接口回调-callbackPay：");
		try {
			Map<String, String[]> requestParams = request.getParameterMap();
			response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
			response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
			Map<String, String> requestMap = new HashMap<String, String>();
			for (String key : requestParams.keySet()) {
				if (requestParams.get(key).length == 0) {
					requestMap.put(key, "");
				} else {
					requestMap.put(key, new String(requestParams.get(key)[0].getBytes(ConstProp.ENCODE_ISO_8859_1), ConstProp.ENCODE_UTF8));
				}
			}
			logger.info("支付接口回调-callbackPay：接收到数据-"+requestMap.toString());
			logger.info("支付接口回调-callbackPay：验签模拟(商户号对应的key)-3-"+CashierMD5Util.verify(requestMap, getMerChantSign("key")));
			// 验签
			if (CashierMD5Util.verify(requestMap, getMerChantSign("key"))) {
				logger.info("支付接口回调-callbackPay：验签成功");
				logger.info("支付接口回调-callbackPay：接收成功-开始数据处理-"+requestMap.toString());
				// TODO 做商户自己的业务 未完成
				if(policyService.ZA_ZZX_SAVE_PAY_MSG(requestMap)){
					logger.info("支付接口回调-callbackPay：数据更新成功-承保完成");
					response.getOutputStream().println("success"); // 不要修改 返回值
				} else {
					logger.info("支付接口回调-callbackPay：承保失败");
					response.getOutputStream().println("fail");
				}
			} else {
				logger.info("支付接口回调-callbackPay：验签失败");
				response.getOutputStream().println("fail");
			}
		}catch (Exception ex){
			logger.info("支付接口回调-callbackPay：接收失败--");
			logger.error("支付接口回调-ERRO:",ex);
			response.getOutputStream().println("fail");
		}
	}

	@RequestMapping("/syntony-service")
	public ModelAndView syntonyService(HttpServletRequest request) throws UnsupportedEncodingException {
		ModelAndView view = new ModelAndView("/coninsweb/api/transaction/finish_pay_iframe");
		Map<String, String[]> requestParams = request.getParameterMap();
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		Map<String, String> requestMap = new HashMap<String, String>();
		for (String key : requestParams.keySet()) {
			if (requestParams.get(key).length == 0) {
				requestMap.put(key, "");
			} else {
				requestMap.put(key, URLDecoder.decode(requestParams.get(key)[0], CashierConfig.CHARSET));
			}
		}
		logger.info("支付接口回调-syntony-service：接收到数据-"+requestMap.toString());
		// 验签
		if (CashierMD5Util.verify(requestMap, CashierConfig.APP_KEY)) {
			if(policyService.ZA_ZZX_SAVE_PAY_MSG(requestMap)){
				OrderFormVo dto = insInsuranceSlipService.getOrderFormVoByTradeSerialNumber(requestMap.get(CashierConstant.OUT_TRADE_NO));
				ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
				view.addObject(ConstProp.PD,pd);
				view.addObject(ConstProp.DTO,dto);
			}
		}
		return view;
	}

	/**
	 * 组装支付数据(众安支付页面)
	 * @param response
	 * @param request 参数oid 订单id,webType 调用支付类型（pc,app）
	 * @return 返回支付页面
	 */
	@RequestMapping(value = "/zaCheckstand")
	@ResponseBody
	public void zaCheckstand(HttpServletResponse response, HttpServletRequest request ){
		String oid = request.getParameter("oid");
		String webType = request.getParameter("webType");
		logger.info("跳转支付页面数据组装-zaCheckstand：star");
		logger.info("跳转支付页面数据组装-zaCheckstand：oid:"+oid);
		try {
			Map<String, String> addOrderMap = null;
			if("pc".equals(webType)){
				addOrderMap = buildRequest_PC(oid);//TODO 需要设置参数
			}else{
				addOrderMap = buildRequest_APP(oid);//TODO 需要设置参数
			}
			logger.info("跳转支付页面数据组装-zaCheckstand：addOrderMap:"+addOrderMap.toString());
//			logger.info("跳转支付页面请求地址-zaCheckstand：url:http://cashier.daily.zhongan.com/za-cashier-web/gateway.do");
			logger.info("跳转支付页面请求地址-zaCheckstand：url:"+GlobalResources.ZN_INS_URL);
			//"http://cashier.itest.zhongan.com/za-cashier-web/gateway.do"
			String getRequest = CashierSubmitUtil.buildRequest(GlobalResources.ZN_INS_URL, addOrderMap, getMerChantSign("key"));
			logger.info("跳转支付页面返回支付页面-zaCheckstand：buildRequest:"+getRequest);
			response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
			response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
			response.getWriter().print(getRequest);
		} catch (Exception e) {
			logger.info("跳转支付页面数据组装-zaCheckstand：ERROR:"+e);
			e.printStackTrace();
		}
		logger.info("跳转支付页面数据组装-zaCheckstand：end");
	}

	private Map<String, String> buildRequest_PC(String oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
//		String valStr = DesUtil.desEncodeCBC(ConstProp.REPORT_KEY, oid);
//		valStr = URLEncoder.encode(valStr, ConstProp.ENCODE_UTF8);
		String returnUrl = GlobalResources.DONOW_PATH+"transaction/common-syntony/"+dto.getOid();
		if(ConstProp.BLB.equals(dto.getWeb_type())){
			returnUrl = GlobalResources.WEB_URL+"/insurance/zzx/transaction/syntony-service/"+dto.getOid();
		}
		Map<String, String> addOrderMap = new HashMap<String, String>();
		addOrderMap.put(CashierConstant.REQUEST_BACK_URL, GlobalResources.DONOW_PATH);
		addOrderMap.put(CashierConstant.BODY, pd.getIntro().replaceAll("</?[^>]+>", "").trim());
		addOrderMap.put(CashierConstant.REQUEST_SRC_TYPE, "pc");
		addOrderMap.put(CashierConstant.SUBJECT, pd.getProduct_name());
		addOrderMap.put(CashierConstant.SIGN_TYPE, "MD5");
		addOrderMap.put(CashierConstant.REQUEST_NOTIFY_URL, GlobalResources.WEB_PRO_URL+"/ZA-API/callbackPay");
		addOrderMap.put(CashierConstant.REQUEST_CHARSET, "UTF-8");
		addOrderMap.put(CashierConstant.OUT_TRADE_NO, dto.getTrade_serial_number());
		addOrderMap.put(CashierConstant.MERCHANT_CODE, getMerChantSign("code"));//商户id
		addOrderMap.put(CashierConstant.REQUEST_RETURN_URL, returnUrl);
		addOrderMap.put(CashierConstant.AMT, dto.getGross_premium());
		addOrderMap.put(CashierConstant.NOTIFY_INFO, "{\"产品名称\":\""+dto.getProduct_name()+"\",\"保障期限\":\""+dto.getInception_date()+"至"+dto.getPlanned_end_date()+"\",\"保费\":\""+dto.getGross_premium()+"\"}");
		addOrderMap.put(CashierConstant.REQUEST_ORDER_INFO, "{\"产品名称\":\""+dto.getProduct_name()+"\",\"保障期限\":\""+dto.getInception_date()+"至"+dto.getPlanned_end_date()+"\",\"保费\":\""+dto.getGross_premium()+"\"}");
		addOrderMap.put(CashierConstant.REQUEST_PAY_CHANNEL, "wxpay^alipay^unionpayB2B");/*^unionpayB2B*/
		addOrderMap.put(CashierConstant.REQUEST_SHOW_URL, GlobalResources.WEB_PRO_URL+"/insurance/lote/product/productInfo/"+pd.getOid());
		return addOrderMap;
	}

	private Map<String, String> buildRequest_APP(String oid) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
		String  return_url=GlobalResources.DONOW_PATH+"/weixin/product/pay/finish/"+dto.getOid();//支付完成的回调地址
//		String return_url=GlobalResources.DONOW_PATH+"/api/lote/syntony-service/"+oid;
		Map<String, String> addOrderMap = new HashMap<String, String>();
		addOrderMap.put(CashierConstant.REQUEST_BACK_URL, GlobalResources.DONOW_PATH+"/weixin/product/win/list"); //app首页
		addOrderMap.put(CashierConstant.BODY, pd.getIntro().replaceAll("</?[^>]+>", "").trim());
		addOrderMap.put(CashierConstant.REQUEST_SRC_TYPE, "mobile");
		addOrderMap.put(CashierConstant.SUBJECT, pd.getProduct_name());
		addOrderMap.put(CashierConstant.SIGN_TYPE, "MD5");
		addOrderMap.put(CashierConstant.REQUEST_NOTIFY_URL, GlobalResources.WEB_PRO_URL+"/ZA-API/callbackPay");//保险公司持续调用这个接口传递
		addOrderMap.put(CashierConstant.REQUEST_CHARSET, "UTF-8");
		addOrderMap.put(CashierConstant.OUT_TRADE_NO, dto.getTrade_serial_number());
		addOrderMap.put(CashierConstant.MERCHANT_CODE, getMerChantSign("code"));//商户id
		addOrderMap.put(CashierConstant.REQUEST_RETURN_URL, return_url); //支付完成的回调地址
		addOrderMap.put(CashierConstant.AMT, dto.getGross_premium());
		addOrderMap.put(CashierConstant.NOTIFY_INFO, "{\"产品名称\":\""+dto.getProduct_name()+"\",\"保障期限\":\""+dto.getInception_date()+"至"+dto.getPlanned_end_date()+"\",\"保费\":\""+dto.getGross_premium()+"\"}");
		addOrderMap.put(CashierConstant.REQUEST_ORDER_INFO, "{\"产品名称\":\""+dto.getProduct_name()+"\",\"保障期限\":\""+dto.getInception_date()+"至"+dto.getPlanned_end_date()+"\",\"保费\":\""+dto.getGross_premium()+"\"}");
		addOrderMap.put(CashierConstant.REQUEST_PAY_CHANNEL, "wxpay^alipay");/*^unionpayB2B*/
		addOrderMap.put(CashierConstant.REQUEST_SHOW_URL, GlobalResources.WEB_PRO_URL+"/weixin/product/win/detail/"+pd.getOid());//产品详情页
		return addOrderMap;
	}

	/**
	 * 根据当前部署环境获取对应众安接口的环境标识
	 * @return
	 */
	private static String getMerChantSign(String keyOrCode){
		if(!GlobalResources.IS_TEST_ENVI){//生成
			if("key".equals(keyOrCode)){
				return "KTOxjLJ8tasruBRXx16K";
			}else{
				return "1709009501";
			}
		}else{//测试
			if("key".equals(keyOrCode)){
				return "B4GNmVUAp0nV0fHJkHRj";
			}else{
				return "1709009501";
			}
		}
	}

}

