package com.bcxin.ins.coninsweb.order.controller.insurance.zzx;

import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.rest.UserSupportUtil;
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.spring.annotation.LoginRequired;
import com.bcxin.ins.third.gzx.huatai.GZX_HTRequestService;
import com.bcxin.ins.third.zzx.changan.ZZX_CARequestService;
import com.bcxin.ins.third.zzx.huatai.ZZX_HTRequestService;
import com.bcxin.ins.third.zzx.pingancai.ZZX_PACRequestService;
import com.bcxin.ins.third.zzx.yongan.ZZX_YARequestService;
import com.bcxin.ins.third.zzx.zhongan.ZARequestService;
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.PathVariable;
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.math.BigDecimal;

/**
 * 投保流程结束后，交易流程处理
 * @author zxf
 *
 */
@Controller
@RequestMapping("/insurance/zzx/transaction")
public class ZZXTransactionController extends BaseController {

	@Autowired
	private ZARequestService zARequestService;
	@Autowired
	private ZZX_PACRequestService zZX_PACRequestService;
	@Autowired
	private ZZX_CARequestService zZX_CARequestService;
	@Autowired
	private ZZX_YARequestService zZX_YARequestService;
	@Autowired
	private ZZX_HTRequestService zZX_HTRequestService;
	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;

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


	@Autowired
	private InsTransactionAPIService transactionService;
	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipAPIService;

	/**
	 * 展责险核保接口
	 * @param request 参数policyId 订单id
	 * @param response
	 * @return 返回200成功，300失败
	 * @throws Exception
	 */
	@LoginRequired
	@RequestMapping("/API_Underwriting")
	@ResponseBody
	public ResultDto API_Underwriting(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return getResultDto(request, response,0);
	}

	private ResultDto getResultDto(HttpServletRequest request, HttpServletResponse response, int is_phone) throws Exception {
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		String oid = request.getParameter("policyId");
		String isPayFee = request.getParameter("isPayFee");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		//设置是否见费，默认见费
		insInsuranceSlipAPIService.updateIsPolicyBeforePayFee(StringUtils.isEmpty(isPayFee)?1:Integer.parseInt(isPayFee),Long.parseLong(oid));
		String result = ConstProp.BLANK_CHAR;
		if(productService.api_request_sign(dto.getProduct_code()) == 1){//众安
			result = zARequestService.requestZA(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 2){//平安财
			result = zZX_PACRequestService.requestPAC(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 3){//永安
			result = zZX_YARequestService.requestYA(Long.parseLong(oid),ConstProp.DIGIT_ONE,null,is_phone);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 4){//长安
			result = zZX_CARequestService.request_ca_zzx(Long.parseLong(oid),ConstProp.DIGIT_ONE);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 5){//华泰
			String hbRet = zZX_HTRequestService.request_ht_zzx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			if(hbRet.contains(ConstProp.CODE_SUCCESS)){
				result = zZX_HTRequestService.request_ht_zzx(Long.parseLong(oid),"25",null);
			} else {
				return new ResultDto("（APP-GZX-001）"+hbRet.split(ConstProp.POUND_SIGN)[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}
		String[] strs = result.split(ConstProp.POUND_SIGN);
		if(!ConstProp.CODE_SUCCESS.equals(strs[0])){
			return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(StringUtils.isEmpty(strs[1])){
			return new ResultDto("（APP-ZZX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		//TODO 众安核保后，获取投保单号设置到数据库
		PolicyTransactionVo pvo= new PolicyTransactionVo();
		pvo.setPolicy_id(oid);
		pvo.setPolicy_serial_number(strs[1]);//设置投保单号
		pvo.setPayment_method(ConstProp.DIGIT_ONE);
		pvo.setPay_amount(new BigDecimal(dto.getGross_premium()));
		pvo.setTransaction_status(DictConst.PAY_STATUS_WZF);
		pvo.setPath_sign(ConstProp.DIGIT_ONE);
		pvo.setUser_id(Long.parseLong(dto.getUser_oid()));
		if(productService.api_request_sign(dto.getProduct_code()) == 3) {//永安
			if(strs.length == 4&&StringUtils.isNotEmpty(strs[2])){
				pvo.setNotice_no(strs[2]);//通知单号
			}
			if(strs.length == 4&&StringUtils.isNotEmpty(strs[3])){
				pvo.setDeal_url(strs[3]);//支付地址
			}
		}else if(productService.api_request_sign(dto.getProduct_code()) == 4) {//长安
			if(strs.length == 5&&StringUtils.isNotEmpty(strs[2])){
				pvo.setPay_amount(new BigDecimal(strs[2]));//保额
			}
			if(strs.length == 5&&StringUtils.isNotEmpty(strs[3])){
				pvo.setOut_of_pocket(new BigDecimal(strs[3]));//保费
			}
		}else if(productService.api_request_sign(dto.getProduct_code()) == 5) {//华泰
			if(strs.length == 6){
				if(StringUtils.isNotEmpty(strs[4])){
					pvo.setNotice_no(strs[1]+"_"+strs[4]);//通知单号 = 投保单号+"_"+保单号
				}
				if(StringUtils.isNotEmpty(strs[2])){
					pvo.setLg_path(strs[2]);//保函下载地址
				}
				if(StringUtils.isNotEmpty(strs[3])){
					pvo.setInsure_path(strs[3]);//保单下载地址
				}
			}
		}else{
			if(strs.length == 5&&StringUtils.isNotEmpty(strs[2])){
				pvo.setNotice_no(strs[2]);//通知单号
			}
			if(strs.length == 5&&StringUtils.isNotEmpty(strs[4])){
				pvo.setPay_amount(new BigDecimal(strs[4]));//保额
			}
			if(strs.length == 5&&StringUtils.isNotEmpty(strs[3])){
				pvo.setOut_of_pocket(new BigDecimal(strs[3]));//保费
			}
		}
		policyService.saveTransaction(pvo);
		return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	@RequestMapping("/failMessage")
	public ModelAndView failMessage(HttpServletRequest request) {
		String msg = request.getParameter("msg");
		ModelAndView view = new ModelAndView("/coninsweb/insurance/zzx/transaction/failMessage");
		view.addObject("msg", msg);
		setTokenByApi(view);

		return view;
	}

	/**
	 * 展责险回调地址
	 * @param oid 订单id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/syntony-service/{oid}")
	public ModelAndView syntonyService(@PathVariable("oid") String oid,HttpServletRequest request) {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail!=null&&userdetail.getWeb_type().contains(ConstProp.PSS)){
			ModelAndView view = new ModelAndView("forward:/api/lote/syntony-service/"+oid);
			setTokenByApi(view);
			return view;
		}
		logger.info("展责险承保完成后页面展示-star");
		logger.info("展责险承保完成后页面展示-syntony-service：oid:"+oid);
		ModelAndView view = new ModelAndView("/coninsweb/insurance/zzx/transaction/finishPay");
		if(StringUtils.isNotEmpty(oid)){
			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);
			logger.info("展责险承保完成后页面展示-OrderFormVo："+dto.toString());
		}
		view.addObject("oid",oid);
		logger.info("展责险承保完成后页面展示-end");
		setTokenByApi(view);
		return view;
	}

}
