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

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.service.user.ClientUserService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.service.ComDeployConfigService;
import com.bcxin.ins.third.tyx.pingan.PackageMessagePingAn;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.MD5Util;
import com.bcxin.ins.util.email.EmailModel;
import com.bcxin.ins.util.email.EmailMsgType;
import com.bcxin.ins.util.email.SendEmailAndMsgUtil;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/PA-API")
public class TYX_PA_API_Controller extends BaseController {


	@Autowired
	private PolicyService policyService;

	@Autowired
	private ClientUserService userService;
	@Autowired
	private ComDeployConfigService comDeployConfigService;

	public static final String SUCCESS = "0";

	public static final String FAIL = "-1";

	/**
	 * 撤单
	 */
	@RequestMapping(value = "/testPingAnCheDan")
	public void  testPingAnCheDan(){

		try {
			String json = PackageMessagePingAn.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.pns_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=PackageMessagePingAn.returnAnalysisJson(ret,ConstProp.DIGIT_FOUR);
			logger.info(result);
			logger.info("结束时间"+System.currentTimeMillis());


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

	}

	/**
	 * 支付完成接口回调
	 * PingAnPayVo paVo参数
	 * paVo.setRequestId("1500538274439");
	 * paVo.setClientType("P_ABC123");
	 * paVo.setToken("fcd785e62acaaff5bf832413fae5bce2");
	 * paVo.setBankTradeNo("4000562001201707201742049541");
	 * paVo.setPolicySerialNumber("null");
	 * paVo.setTranCode("200103");
	 * paVo.setStatus("pay_success");
	 * paVo.setRcptno("30000070075862369");
	 * paVo.setBankTranDate("2017-07-20");
	 * paVo.setBankTranTime("16:11:13");
	 * paVo.setBankNo("99033222");
	 * paVo.setBankTranChnl("NBU");
	 * @param response
	 */
	@RequestMapping(value = "/callbackPay")
	@ResponseBody
	public String callbackPay(HttpServletResponse response, PingAnPayVo paVo){

		logger.info("支付接口回调-callbackPay：");
		try {
			JSONObject json = new JSONObject();
			if(StringUtils.isEmpty(paVo.getRequestId())||StringUtils.isEmpty(paVo.getClientType())||StringUtils.isEmpty(paVo.getToken())){
				logger.info("支付接口回调-callbackPay：参数不能为空");
				json.put("status",1001);
				json.put("msg","参数不能为空");
				return json.toString();
			}
			if(!"P_ABC123".equals(paVo.getClientType())){
				logger.info("支付接口回调-callbackPay：平台标识有错");
				json.put("status",1002);
				json.put("msg","平台标识有错");
				return json.toString();
			}
			logger.info("支付接口回调-callbackPay，PingAnPayVo值："+paVo.toString());
			logger.info("支付接口回调-callbackPay，string2MD5值："+MD5Util.string2MD5(paVo.getRequestId()+paVo.getClientType()+"pingan"));
			logger.info("支付接口回调-callbackPay，PingAnPayVo---token："+paVo.getToken());
			if(MD5Util.string2MD5(paVo.getRequestId()+paVo.getClientType()+"pingan").equals(paVo.getToken())){
				logger.info("支付接口回调-callbackPay：接收成功-开始数据处理-"+paVo.toString());
//						policyService.PAS_TYX_SAVE_PAY_MSG(paVo);
				if(policyService.PAS_TYX_SAVE_PAY_MSG(paVo)){
					json.put("status",200);
					json.put("msg","接收成功");
				}else{
					json.put("status",1004);
					json.put("msg","数据处理出错");
				}
			}else{
				logger.info("支付接口回调-callbackPay：密钥错误");
				json.put("status",1003);
				json.put("msg","密钥错误");
			}
			return json.toString();
		}catch (Exception ex){
			logger.info("支付接口回调-callbackPay：接收失败--");
//			ex.printStackTrace();
			logger.error("支付接口回调",ex);
			JSONObject json = new JSONObject();
			json.put("status",300);
			json.put("msg","接收失败");
			return json.toString();
		}
	}

	/**
	 * <b> 特殊数据修复接口，通过保险公司推送的接口信息修复待支付订单为已承保 </b>
	 * @author ZXF
	 * @create 2019/01/15 0015 9:41
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping(value = "/temporary")
	@ResponseBody
	public String temporary(HttpServletResponse response, PingAnPayVo paVo){

		logger.info("支付接口回调-callbackPay：");
		try {
			JSONObject json = new JSONObject();
			if(StringUtils.isEmpty(paVo.getRequestId())||StringUtils.isEmpty(paVo.getClientType())||StringUtils.isEmpty(paVo.getToken())){
				logger.info("支付接口回调-callbackPay：参数不能为空");
				json.put("status",1001);
				json.put("msg","参数不能为空");
				return json.toString();
			}
			if(!"P_ABC123".equals(paVo.getClientType())){
				logger.info("支付接口回调-callbackPay：平台标识有错");
				json.put("status",1002);
				json.put("msg","平台标识有错");
			}else{
				logger.info("支付接口回调-callbackPay，PingAnPayVo值："+paVo.toString());
				logger.info("支付接口回调-callbackPay，string2MD5值："+MD5Util.string2MD5(paVo.getRequestId()+paVo.getClientType()+"pingan"));
				logger.info("支付接口回调-callbackPay，PingAnPayVo---token："+paVo.getToken());
				if(policyService.PAS_TYX_SAVE_PAY_MSG_TEMPORARY(paVo)){
					json.put("status",200);
					json.put("msg","接收成功");
				}else{
					json.put("status",1004);
					json.put("msg","数据处理出错");
				}
			}
			return json.toString();
		}catch (Exception ex){
			logger.info("支付接口回调-callbackPay：接收失败--");
//			ex.printStackTrace();
			logger.error("支付接口回调",ex);
			JSONObject json = new JSONObject();
			json.put("status",300);
			json.put("msg","接收失败");
			return json.toString();
		}
	}

	public static void main(String[] args) {
		String a = "{\n" +
				"\t'requestId': '1545362210123',\n" +
				"\t'clientType': 'P_ABC123',\n" +
				"\t'token': '3ebf1d089573389347dcc36c0649b4b0',\n" +
				"\t'bankTradeNo': '4200000237201812213066850535',\n" +
				"\t'policySerialNumber': 'null',\n" +
				"\t'tranCode': '200103',\n" +
				"\t'status': 'pay_success',\n" +
				"\t'rcptno': '17000070227054176',\n" +
				"\t'bankTranDate': '2018-12-21',\n" +
				"\t'bankTranTime': '11:14:28',\n" +
				"\t'bankNo': '99033222',\n" +
				"\t'bankTranChnl': 'NBU',\n" +
				"\t'policy': '200#GP17002031968046'\n" +
				"}";
		PingAnPayVo paVo = JSONObject.parseObject(a,PingAnPayVo.class);

		String url = "http://localhost:8080/PA-API/temporary";
//		String url = "http://www.bailianbao.cn/PA-API/temporary";
		try {
			String b = SendUtils.httpSendReceiverForUTF8(url,JSONObject.toJSONString(paVo));
			System.out.println(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 组装支付数据(平安收银台)
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/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_PAY_URL;
//				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/tyx/transaction/syntony-service/"+dto.getOid();
				}
				JSONObject json = new JSONObject();
				json.put("expireTime","6");
				json.put("disableBankType","C");
				json.put("proName",dto.getProduct_name());
				String data=PackageMessagePingAn.pay(dto.getPolicy_serial_number(),dto.getGross_premium(),url,returnUrl,json.toString());//收据号，多少钱， 地址
				logger.info("3> "+data);
				return  data;
			}catch (Exception ex){
//				ex.printStackTrace();
				logger.error("组装支付数据(平安收银台)",ex);
			}
		}
		return  "";
	}


	/**
	 * 平安分账(对账)
	 * @param response
	 */
	@RequestMapping(value = "/pa_reconciliation")
	@ResponseBody
	public String pa_reconciliation(PingAnReconciliationVo vo, HttpServletResponse response){
		try {
			JSONObject json = new JSONObject();
//			requestId=System.currentTimeMillis()+"";
			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("pa-fenzhang(pa_reconciliation)-PingAnReconciliationVo:"+vo.toString());
			json.put("status",200);
			json.put("msg","接收成功");
			//根据vo.getAccountCheckResult()的值对账，3已承保未支付成功（人工处理），5已支付未承保（补做承保动作）
			if("3".equals(vo.getAccountCheckResult())){
				//3已承保未支付成功（人工处理）发短信或交由客服
				logger.info("pa-fenzhang(pa_reconciliation)-status(3):已承保未支付成功（人工处理）发短信或交由客服");
				OrderFormVo dto = policyService.getPolicyDtoByRcptNo(vo.getReceiptNo());
				String emailTitle = ConstProp.BLANK_CHAR;
				String emailContent = ConstProp.BLANK_CHAR;
				EmailModel em = new EmailModel(vo.getReceiptNo(), EmailMsgType.PAS_DZ_F);
				if(dto!=null){
					em = new EmailModel(dto.getTrade_serial_number(), EmailMsgType.PAS_DZ_F);
				}
				String[] arrs = comDeployConfigService.getValueByKey("exmail").split(ConstProp.SEMICOLON);
				List<String> emailList = new ArrayList<String>();
				for(int i=0;i<arrs.length;i++){
					if(org.apache.commons.lang3.StringUtils.isNotBlank(arrs[i]) && !arrs[i].contains(ConstProp.COLON)){
						// 发送地址
						emailList.add(arrs[i].trim());
					}
				}
				if(emailList.size()>0){
					em.setTo(emailList);
					SendEmailAndMsgUtil.sendEmail(em);
				}
			}else if("5".equals(vo.getAccountCheckResult())){
				//5已支付未承保（补做承保动作）
				logger.info("pa-fenzhang(pa_reconciliation)-status(5)(pa_reconciliation_underwrite):已支付未承保（补做承保动作）");
				policyService.pa_reconciliation_underwrite(vo.getReceiptNo(),vo.getExternalReference());
			}
			return json.toString();
		}catch (Exception ex){
			logger.error("接收失败",ex);
			JSONObject json = new JSONObject();
			json.put("status",300);
			json.put("msg","接收失败");
			return json.toString();
		}
	}

}

