package com.bcxin.ins.coninsweb.order.controller.export;

import com.bcxin.ins.third.build.taibao.TransType;
import com.bcxin.ins.third.xyx.taibao.XYX_TBRequestService;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.InsProductRuleXWCKAPIService;
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.util.IdWorker;
import com.bcxin.ins.util.RegionUtils;
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 XYX_Transaction_API_Controller extends BaseController {

	@Autowired
	private XYX_TBRequestService xYX_TBRequestService;

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

	@Autowired
	private InsTransactionAPIService transactionService;


	/**
	 * 太保信用险核保接口
	 * @param request 参数policyId 订单id
	 * @param response
	 * @return 返回200成功，300失败
	 * @throws Exception
	 */
	@LoginRequired
	@RequestMapping("/api/xyx/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 {
		String oid = request.getParameter("policyId");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		String result = xYX_TBRequestService.requestTB(Long.parseLong(oid), TransType.EPIC_INS_XW.getValue(),null);
		String[] strs = result.split(ConstProp.POUND_SIGN);
		if(ConstProp.CODE_SUCCESS.equals(strs[0])){
			if(StringUtils.isNotEmpty(strs[1])){
				//TODO 太保信用险核保后，获取投保单号设置到数据库
				PolicyTransactionVo pvo= new PolicyTransactionVo();
				pvo.setPolicy_id(oid);
				//设置投保单号
				pvo.setPolicy_serial_number(strs[1]);
				pvo.setTrade_serial_number(IdWorker.getId() + ConstProp.BLANK_CHAR);
				pvo.setPayment_method(ConstProp.DIGIT_ONE);
				pvo.setPay_type(DictConst.PAY_TYPE_XX);
				pvo.setOut_of_pocket(BigDecimal.ZERO);
				pvo.setPay_amount(BigDecimal.ZERO);
				pvo.setPath_sign(ConstProp.DIGIT_ONE);
				pvo.setTransaction_status(DictConst.PAY_STATUS_WZF);
				pvo.setUser_id(Long.parseLong(dto.getUser_oid()));
				policyService.saveTransaction(pvo);
				return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}else{
				return new ResultDto("（APP-GZX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}else{
			return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	/**
	 * 太保信用险承保接口
	 * @param request 参数policyId 订单id
	 * @param response
	 * @return 返回200成功，300失败
	 * @throws Exception
	 */
	@LoginRequired
	@RequestMapping("/api/xyx/transaction/API_Underwriting_Later")
	@ResponseBody
	public ResultDto API_Underwriting_Later(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return getResultDto_Later(request, response);
	}

	private ResultDto getResultDto_Later(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 = xYX_TBRequestService.requestTB(Long.parseLong(oid),ConstProp.DIGIT_TWO,null);
		}
		String[] strs = result.split(ConstProp.POUND_SIGN);
		if(ConstProp.CODE_SUCCESS.equals(strs[0])){
			if(StringUtils.isNotEmpty(strs[1])){
				//TODO 太保信用险承保后，获取保单号和电子保单设置到数据库
				PolicyTransactionVo vo= new PolicyTransactionVo();
				//保存保单号
				vo.setPolicy_number(strs[1]);
				vo.setPolicy_id(String.valueOf(oid));
				transactionService.savePolicyExternalReference(vo);
				if(strs.length == 3){
					//保存保单地址
					vo.setInsure_path(strs[2]);
					transactionService.savePolicyOther(vo);
				}
				return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}else{
				return new ResultDto("（APP-GZX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}else{
			return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

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

	/**
	 * 公责险回调地址
	 * @param oid 订单id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/api/xyx/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/xyx/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;
	}

	/**
	 * <b>打印投保单 </b>
	 *
	 * @param oid
	 * @return
	 * @author luopeng
	 * @date 2016年12月21日 下午1:51:18
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/api/xyx/printPolicy/{oid}")
	public ModelAndView printPolicy(@PathVariable long oid){
		ModelAndView view = new ModelAndView("/coninsweb/insurance/customs/transaction/print_customs_1");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		view.addObject(ConstProp.DTO, dto);
		MicroExportVo vo = policyService.accordingToOrderIDToGetMicroExportVo(oid);
		RuleXWCKVo rxvo = insProductRuleXWCKAPIService.getRuleXWCKVoByProductIDAndCity(dto.getProduct_oid(), vo.getRoleSubjectList().get(0).getReg_city());
		view.addObject("rxvo", rxvo);
		view.addObject(ConstProp.REG_ROLE, RegionUtils.getRegionNameByALLCode(vo.getRoleSubjectList().get(0).getReg_province(),vo.getRoleSubjectList().get(0).getReg_city(),vo.getRoleSubjectList().get(0).getReg_district()));
		view.addObject(ConstProp.REG_RULE, RegionUtils.getRegionNameByALLCode(vo.getLawsuit_province(),vo.getLawsuit_city(),vo.getLawsuit_area())+vo.getLawsuit_address());
		view.addObject("quyu", RegionUtils.getRegionNameByALLCode(vo.getLawsuit_province(),vo.getLawsuit_city(),ConstProp.BLANK_CHAR));
		view.addObject(ConstProp.VO,vo);
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b>打印承诺书 </b>
	 *
	 * @param oid
	 * @return
	 * @author luopeng
	 * @date 2016年12月21日 下午1:51:18
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/api/xyx/print-promissory-note/{oid}")
	public ModelAndView print_promissory_note(@PathVariable long oid){
		ModelAndView view = new ModelAndView("/coninsweb/insurance/customs/transaction/print_customs_2");
		MicroExportVo vo = policyService.accordingToOrderIDToGetMicroExportVo(oid);
		view.addObject("cityName", RegionUtils.getRegionNameByCode(vo.getRoleSubjectList().get(0).getReg_city()));
		setTokenByApi(view);
		return view;
	}

}
