package com.bcxin.ins.coninsweb.order.controller.api.gzx;

import com.bcxin.ins.third.gzx.huatai.GZX_HTRequestService;
import com.bcxin.ins.third.gzx.pingancai.GZX_PACRequestService;
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.core.base.web.BaseController;
import com.bcxin.ins.spring.annotation.LoginRequired;
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
public class GZX_Transaction_API_Controller extends BaseController {

	@Autowired
	private GZX_PACRequestService gZX_PACRequestService;
	@Autowired
	private GZX_HTRequestService gZX_HTRequestService;
	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;

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


	@Autowired
	private InsTransactionAPIService transactionService;


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

	private ResultDto getResultDto(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		String oid = request.getParameter("policyId");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		String result = ConstProp.BLANK_CHAR;
		if(productService.api_request_sign(dto.getProduct_code()) == 2){//平安财
			result = gZX_PACRequestService.requestPAC(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
		} else if(productService.api_request_sign(dto.getProduct_code()) == 1){//华泰
			String hbRet = gZX_HTRequestService.request_ht_gzx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			if(hbRet.contains(ConstProp.CODE_SUCCESS)){
				result = gZX_HTRequestService.request_ht_gzx(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-GZX-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]);//设置投保单号
		if(strs.length == 5){
			if(StringUtils.isNotEmpty(strs[2])){
				pvo.setNotice_no(strs[2]);//通知单号
			}
			if(StringUtils.isNotEmpty(strs[4])){
				pvo.setPay_amount(BigDecimal.valueOf(Double.parseDouble(strs[4])));//保额
			}
			if(StringUtils.isNotEmpty(strs[3])){
				pvo.setOut_of_pocket(BigDecimal.valueOf(Double.parseDouble(strs[3])));//保费
			}
		} else 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]);//保单下载地址
			}
		}
		policyService.saveTransaction(pvo);
		return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

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

		return view;
	}

	/**
	 * 公责险回调地址
	 * @param oid 订单id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/api/gzx/syntony-service/{oid}")
	public ModelAndView syntonyService(@PathVariable("oid") String oid,HttpServletRequest request) {
		logger.info("公责险承保完成后页面展示-star");
		logger.info("公责险承保完成后页面展示-syntony-service：oid:"+oid);
		ModelAndView view = new ModelAndView("/coninsweb/api/gzx/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;
	}

}
