package com.bcxin.ins.coninsweb.order.controller.api.gyx.taibao;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.common.http.MessageUtils;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.service.order.InsTransactionAPIService;
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.entity.policy_core.InsTransaction;
import com.bcxin.ins.third.gyx.taibao.GYX_PackageMessageTaiBao;
import com.bcxin.ins.third.gyx.taibao.GYX_TBRequestService;
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.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
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 GYX_TB_API_Controller extends BaseController {


	@Autowired
	private GYX_TBRequestService gYX_TBRequestService;
	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;
	@Autowired
	private InsTransactionAPIService insTransactionService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private ProductService productService;

	/**
	 * 支付接口回调
	 * (测试环境-支付结果)http://blb.test.bcxin.com.cn/TBAPI/GYX/callbackPay
	 * (生产环境-支付结果)http://www.bailianbao.cn/TBAPI/GYX/callbackPay
	 * @param response
	 */
	@RequestMapping(value = "/TBAPI/GYX/callbackPay")
	public void callbackPay(HttpServletResponse response, @RequestBody String xml) throws Exception {
		logger.info("支付接口回调-callbackPay-TB-GYX：请求报文-"+xml);
		String analysisXML = GYX_PackageMessageTaiBao.resultAnalysisXML(xml,ConstProp.DIGIT_ONE);
		logger.info("支付接口回调-callbackPay-TB-GYX：解析报文-"+analysisXML);
		OrderFormVo dto = null;
		if(StringUtils.isEmpty(analysisXML)){
			GYX_Result(response, "0", "9999", "报文解析失败-01", dto);
			return;
		}
		String[] strArr = analysisXML.split(ConstProp.POUND_SIGN);
		if(!ConstProp.CODE_SUCCESS.equals(strArr[0])){
			GYX_Result(response, "0", "9999", "报文解析失败-02", dto);
			return;
		}
		//投保单号查订单
		dto = policyService.getPolicyDtoByRcptNo(strArr[1]);
		if(dto == null){
			GYX_Result(response, "0", "9999", "未匹配到订单信息", dto);
			return;
		}
		try {
			List<InsTransaction> tList = insTransactionService.selectInsTransactionByInsOrderForm(Long.parseLong(dto.getOid()));
			if(tList==null?false:tList.size()>0?true:false){
				InsTransaction it = tList.get(0);
				it.setTrade_serial_number(strArr[2]);
				it.setEnd_time(new Date());
				it.setTransaction_status(DictConst.PAY_STATUS_YZF);
				insTransactionService.updateById(it);
			}
			GYX_Result(response, "1", "0000", "业务处理完成", dto);
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			GYX_Result(response, "0", "9999", "业务处理过程出现异常", dto);
		}
	}

	/**
	 * <b> 支付接口回调 返回值处理 </b>
	 * @author ZXF
	 * @create 2020/09/28 0028 17:53
	 * @version
	 * @注意事项 </b>
	 */
	private void GYX_Result(HttpServletResponse response, String sCode, String eCode, String emsg, OrderFormVo dto) throws Exception {
		JSONObject msgJson = new JSONObject();
		msgJson.put("successInd",sCode);
		msgJson.put("errorCode",eCode);
		msgJson.put("errorMessage",emsg);

		String result = gYX_TBRequestService.signXmlResult(dto, msgJson);
		logger.info("接口返回数据-"+result);
		MessageUtils.returnMessage(result,response);
		logger.info("业务结束：end");
	}

	/**
	 * 保单接口回调
	 * (测试环境-承保结果)http://blb.test.bcxin.com.cn/TBAPI/GYX/callbackPolicy
	 * (生产环境-承保结果)http://www.bailianbao.cn/TBAPI/GYX/callbackPolicy
	 * @param response
	 */
	@RequestMapping(value = "/TBAPI/GYX/callbackPolicy")
	public void  callbackPolicy(HttpServletResponse response, @RequestBody String xml) throws Exception {
		logger.info("保单生效接口回调-callbackPolicy-TB-GYX：请求报文-"+xml);
		String analysisXML = GYX_PackageMessageTaiBao.resultAnalysisXML(xml,ConstProp.DIGIT_TWO);
		logger.info("保单生效接口回调-callbackPolicy-TB-GYX：解析报文-"+analysisXML);
		OrderFormVo dto = null;
		if(StringUtils.isEmpty(analysisXML)){
			GYX_Result(response, "0", "9999", "报文解析失败-01", dto);
			return;
		}
		String[] strArr = analysisXML.split(ConstProp.POUND_SIGN);
		if(!ConstProp.CODE_SUCCESS.equals(strArr[0])){
			GYX_Result(response, "0", "9999", "报文解析失败-02", dto);
			return;
		}
		//投保单号查订单
		dto = policyService.getPolicyDtoByRcptNo(strArr[1]);
		if(dto == null){
			GYX_Result(response, "0", "9999", "未匹配到订单信息", dto);
			return;
		}
		try {
			PolicyTransactionVo vo= new PolicyTransactionVo();
			//保存保单号
			vo.setPolicy_number(strArr[2]);
			vo.setPolicy_id(dto.getOid());
			insTransactionService.savePolicyExternalReference(vo);
			if(strArr.length == 4){
				//保存保单地址
				vo.setInsure_path(strArr[3]);
				insTransactionService.savePolicyOther(vo);
			}
			GYX_Result(response, "1", "0000", "业务处理完成", dto);
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			GYX_Result(response, "0", "9999", "业务处理过程出现异常", dto);
		}
	}

	/**
	 * 个意险回调地址
	 * @param oid 订单id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/TBAPI/GYX/syntony-service/{oid}")
	public ModelAndView syntonyService(@PathVariable String oid) {
		ModelAndView view = new ModelAndView("/coninsweb/api/transaction/finish_pay_no_iframe");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if (  userdetail == null ) {
			return new ModelAndView("forward:/synopsis/loseView");
		}
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
		view.addObject(ConstProp.PD,pd);
		view.addObject(ConstProp.DTO,dto);
		view.addObject(ConstProp.USERDETAIL,userdetail);
		return view;
	}
}

