package com.bcxin.ins.coninsweb.order.controller.api.build.yangguang;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.common.http.MessageUtils;
import com.bcxin.ins.third.build.yangguang.YGGCService;
import com.bcxin.ins.third.build.yangguang.util.SendUtils;
import com.bcxin.ins.third.build.yangguang.yggc.Result;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.ProductVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
 * 生产环境：
 * 网页回调：http://www.bailianbao.cn/YG-API/finishPay/TV5N2213201700379995
 * 数据回调：http://www.bailianbao.cn/YG-API/callbackPay
 * @author ZXF
 * @create 2018/04/26 0026 9:25
 * @version
 * @注意事项 </b>
 */
@Controller
@RequestMapping("/YG-API")
public class Build_YG_API_Controller extends BaseController {



	@Autowired
	private YGGCService yggcService;
	@Autowired
	private ProductService productService;
	@Autowired
	private PolicyService policyService;

	public static final String SUCCESS = "0";
	private static final String finishPay = getViewPath("YG-API/finishPay");
	public static final String FAIL = "-1";

	@RequestMapping(value = "/finishPay/{proposalNo}")
	public ModelAndView finishPayReturn(Model model, @RequestParam Map<Object,Object> params , HttpServletRequest req, HttpServletResponse resp, @PathVariable("proposalNo") String proposalNo) {
		logger.info("阳光工程承保完成后页面展示-star");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if (  userdetail == null ) {
			return new ModelAndView("redirect:/");
		}
		logger.info("阳光工程承保完成后页面展示-syntony-service：proposalNo:"+proposalNo);
		ModelAndView view = new ModelAndView("/coninsweb/api/transaction/finish_pay_no_iframe");
		if(StringUtils.isNotEmpty(proposalNo)){
			OrderFormVo dto = policyService.getPolicyDtoByRcptNo(proposalNo);//根据投保单号获得订单号
			ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));

			view.addObject(ConstProp.PD,pd);
			view.addObject(ConstProp.DTO,dto);
			logger.info("阳光工程承保完成后页面展示-OrderFormVo："+dto.toString());
		}
		view.addObject("proposalNo",proposalNo);
		view.addObject(ConstProp.USERDETAIL,userdetail);
		logger.info("阳光工程承保完成后页面展示-end");
		return view;
	}

	/**
	 * 支付接口回调
	 * 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 void  callbackPay(HttpServletRequest request,HttpServletResponse response,@RequestBody String res){
		logger.info("阳光支付接口回调-callbackPay：");
		logger.info(res);

		Result result =  JSONObject.parseObject(res, Result.class);
		try {

			JSONObject json = new JSONObject();

			String policyNo=result.getTbResultList().get(0).getPolicyNo();;
			String premium=result.getTbResultList().get(0).getPremium();
			String isSuccess=result.getTbResultList().get(0).getIsSuccess();
			String sysFlag=result.getXmlHead().getSysFlag();
			if(StringUtils.isEmpty(policyNo)|| StringUtils.isEmpty(premium)|| StringUtils.isEmpty(isSuccess)){
				logger.info("阳光支付接口回调-callbackPay：参数不能为空");
				json.put("status",1001);
				json.put("msg","fail:Parameter cannot be empty");
			}else{
				if(!"BXBHW".equals(sysFlag)){
					logger.info("阳光支付接口回调-callbackPay：平台标识有错");
					json.put("status",1002);
					json.put("msg","fail:sysFlag error");
				}else{

						logger.info("阳光支付接口回调-callbackPay：接收成功-开始数据处理-"+result.toString());

						if(yggcService.policyYG_callbackPay(result)){
							json.put("status",200);
							json.put("msg","success");
						}else{
							json.put("status",1004);
							json.put("msg","fail:data error");
						}

				}

			}
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			MessageUtils.returnMessage(json.toString(),response);
		}catch (Exception ex){
			logger.info("阳光支付接口回调-callbackPay：接收失败--");
			logger.error("阳光支付接口回调",ex);
			JSONObject json = new JSONObject();
			json.put("status",300);
			json.put("msg","Receive failed");
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			MessageUtils.returnMessage(json.toString(),response);
		}
	}
	@RequestMapping(value = "/sendMess")
	@ResponseBody
	public void  sendMess(HttpServletResponse response){
		String url="http://localhost:8082//YG-API/callbackPay";
		String sendStr="{\"jobName\":\"ServiceBus\",\"interfaceService\":\"policyFlowService\",\"interfaceMethod\":\"surrenderProcess\",\"xmlHead\":{\"sysFlag\":\"BXBHW\",\"transCode\":\"SV000332\"},\"tbresultList\":[{\"policyNo\":\"SV5N2213201700386594\",\"importSN\":\"BXBHW0121903303619sfssd8999997\",\"premium\":\"200\",\"amountUp\":\"壹拾万元整\",\"premiumUp\":\"贰佰元整\",\"isSuccess\":\"true\",\"proposalNo\":\"TV5N2213201700386594\"}]}";

		try {
			SendUtils.httpSendReceiverForUTF8(url,sendStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

