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

import com.bcxin.ins.third.gyx.taibao.GYX_TBRequestService;
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.spring.annotation.LoginRequired;
import com.bcxin.mybatisplus.toolkit.IdWorker;
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.io.IOException;
import java.math.BigDecimal;
import java.util.Date;


/**
 * 投保流程结束后，交易流程处理
 * @author zxf
 *
 */
@Controller
public class GYX_Transaction_API_Controller extends BaseController {

	@Autowired
	private GYX_TBRequestService gYX_TBRequestService;

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

	/**
	 * <b> 个意险核保接口，更新数据库 </b>
	 * @author ZXF
	 * @create 2018/03/20 0020 18:13
	 * @version
	 * @注意事项 </b>
	 */
	@LoginRequired
	@RequestMapping("/api/gyx/transaction/API_Underwriting")
	@ResponseBody
	public ResultDto API_Underwriting(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String oid = request.getParameter("policyId");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		String result =ConstProp.BLANK_CHAR;
		String[] strs = null;
		if(ConstProp.GYX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
			result = gYX_TBRequestService.requestTB(Long.parseLong(oid),ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR);
			strs = result.split(ConstProp.POUND_SIGN);
		}else{
			return new ResultDto("产品未匹配到对应接口！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(ConstProp.CODE_SUCCESS.equals(strs[0])){
			if(StringUtils.isNotEmpty(strs[1])){
				PolicyTransactionVo pvo= new PolicyTransactionVo();
				pvo.setPolicy_id(oid);
				pvo.setPolicy_serial_number(strs[1]);//设置投保单号
				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-GYX-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);
		}
	}

	/**
	 * <b>业务逻辑处理，选择支付方式，跳转支付平台
	 * 目前默认跳转银联支付 </b>
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author luopeng
	 * @date 2016年12月21日 下午1:50:39
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("/api/gyx/transaction/getPayUrlByTB")
	public void getPayUrlByTB(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		String result = ConstProp.BLANK_CHAR;
		if(userdetail==null){
			result = "{\"statusCode\":\"300\",\"message\":\"用户已过期，请重新登录\"}";
			renderString(response, result, ConstProp.ENCODE_UTF8_TEXT);
			return;
		}
		String oid = request.getParameter("policyId");
		String payType = request.getParameter("policyPaymentType");
		if(StringUtils.isEmpty(oid)&&StringUtils.isNotEmpty(payType)){
			result = "{\"statusCode\":\"300\",\"message\":\"请选择支付方式\"}";
			renderString(response, result, ConstProp.ENCODE_UTF8_TEXT);
			return;
		}
		try {
			OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
			PolicyTransactionVo vo= new PolicyTransactionVo();
			String payforURL = ConstProp.BLANK_CHAR;
			String msg = ConstProp.BLANK_CHAR;
			vo.setPayment_method(ConstProp.DIGIT_THREE);
			if(ConstProp.GYX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
				String payResult = gYX_TBRequestService.requestTB(Long.parseLong(oid),ConstProp.DIGIT_TWO,payType);
				String[] strs = payResult.split(ConstProp.POUND_SIGN);
				if ( !ConstProp.CODE_SUCCESS.equals(strs[0])) {
					msg = strs[1];
				}
				if ( ConstProp.CODE_SUCCESS.equals(strs[0])&&strs.length > 2 ) {
					payforURL = strs[2];
				}
			}

			if (StringUtils.isNotEmpty(payforURL)) {
				vo.setPay_amount(BigDecimal.valueOf(Double.parseDouble(dto.getGross_premium())));
				vo.setOut_of_pocket(BigDecimal.valueOf(Double.parseDouble(dto.getGross_premium())));
				vo.setStart_time(new Date());
				vo.setDeal_url(payforURL);
				vo.setPolicy_id(oid);
				vo.setPayment_method(ConstProp.DIGIT_ONE);
				vo.setPath_sign(ConstProp.DIGIT_ONE);
				vo.setPay_type(payType);
				vo.setUser_id(Long.parseLong(userdetail.getOid()));
				vo.setTrade_serial_number(String.valueOf(IdWorker.getId()));//设置交易流水号
				policyService.saveTransaction(vo);
				result = "{\"statusCode\":\"200\",\"forwardurl\":\""+payforURL+"\"}";
			} else {
				result = "{\"statusCode\":\"301\",\"message\":\""+msg+"\"}";
			}
		}catch (Exception e){
			result = "{\"statusCode\":\"300\",\"message\":\"支付过程出现异常\"}";
		}
		renderString(response, result, ConstProp.ENCODE_UTF8_TEXT);
	}

	/**
	 * <b>完成支付 </b>
	 *
	 * @param oid
	 * @return
	 * @author luopeng
	 * @date 2016年12月21日 下午1:51:30
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(redirectUrl = "forward:/synopsis/loseView")
	@RequestMapping("/api/gyx/transaction/finishPay/{oid}")
	public ModelAndView finishPay(@PathVariable long oid, HttpServletRequest request){
		ModelAndView view = new ModelAndView("/coninsweb/api/gyx/transaction/finishPay");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
		view.addObject(ConstProp.PD,pd);
		view.addObject(ConstProp.DTO,dto);
		setTokenByApi(view);
		return view;
	}
}
