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

import com.bcxin.ins.entity.common.ComTaskResidual;
import com.bcxin.ins.third.tyx.changan.TYX_CARequestService;
import com.bcxin.ins.third.tyx.huatai.TYX_HTRequestService;
import com.bcxin.ins.third.tyx.pingan.PARequestService;
import com.bcxin.ins.third.tyx.pingancai.PACRequestService;
import com.bcxin.ins.third.tyx.qianhai.TYX_QHRequestService;
import com.bcxin.ins.third.tyx.renbao.RBRequestService;
import com.bcxin.ins.third.tyx.taikang.TKRequestService;
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.InsInsuranceSlip;
import com.bcxin.ins.entity.policy_core.InsTransaction;
import com.bcxin.ins.spring.annotation.LoginRequired;
import com.bcxin.ins.util.Constant;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import net.sf.json.JSONObject;
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;
import java.util.List;

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

	@Autowired
	private TKRequestService tKRequestService;
	@Autowired
	private PARequestService pARequestService;
	@Autowired
	private PACRequestService pACRequestService;
	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;

	@Autowired
	private ProductService productService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private RBRequestService rBRequestService;
	@Autowired
	private TYX_CARequestService tYX_CARequestService;
	@Autowired
	private TYX_QHRequestService tYX_QHRequestService;
	@Autowired
	private TYX_HTRequestService tYX_HTRequestService;


	@Autowired
	private InsTransactionAPIService transactionService;

	private String ONLINE = "ONLINE";
	private String OFFLINE = "OFFLINE";


	/**
	 * <b>业务逻辑处理，选择支付方式，跳转支付平台
	 * 目前默认跳转银联支付 </b>
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author luopeng
	 * @date 2016年12月21日 下午1:50:39
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired
	@RequestMapping("/api/gmr/transaction/policyPayment")
	@ResponseBody
	public ResultDto policyPayment(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String oid = request.getParameter("policyId");
		String payType = request.getParameter("payType");
		String doType = ConstProp.BLANK_CHAR;
		if(ONLINE.equals(payType)){
			doType = ConstProp.DIGIT_THREE;
		}else if(OFFLINE.equals(payType)){
			doType = ConstProp.DIGIT_SIX;
		}
//		System.currentTimeMillis()+"";
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(StringUtils.isNotEmpty(doType)){
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPay_amount(new BigDecimal(dto.getGross_premium()));
			pvo.setStart_time(new Date());
			pvo.setPayment_method(ConstProp.DIGIT_ONE);
			pvo.setPay_type(doType);
			pvo.setPolicy_id(oid);
			pvo.setUser_id(Long.parseLong(userdetail.getOid()));
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			pvo.setTrade_serial_number(String.valueOf(idWorker.nextId()));//设置交易流水号
			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("支付方式丢失", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	@LoginRequired
	@RequestMapping("/api/gmr/transaction/API_Underwriting")
	@ResponseBody
	public ResultDto API_Underwriting(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String user_id = request.getParameter("user_id");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		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;
		String[] strs = null;
		if(productService.api_request_sign(dto.getProduct_code()) == 1){
			result = tKRequestService.requestTK(Long.parseLong(oid),"01");
			strs = result.split(ConstProp.POUND_SIGN);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 2){
			result = pARequestService.requestPA(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			strs = result.split(ConstProp.POUND_SIGN);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 4){
			result = rBRequestService.request_rb_tyx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			strs = result.split(ConstProp.POUND_SIGN);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 5){
			result = pACRequestService.requestPAC(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			strs = result.split(ConstProp.POUND_SIGN);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 6){
			result = tYX_CARequestService.request_ca_tyx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			strs = result.split(ConstProp.POUND_SIGN);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 7){
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			result = tYX_QHRequestService.request_qh_tyx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			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-TYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			String payNo = String.valueOf(idWorker.nextId());
			String payPath = strs[2];
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			//设置投保单号
			pvo.setPolicy_serial_number(strs[1]);
			pvo.setDeal_url(payPath);
			pvo.setPayment_method(ConstProp.DIGIT_ONE);
			//支付方式
			pvo.setPay_type(DictConst.PAY_TYPE_XS);
			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()));
			pvo.setPay_order_number(payNo);
			pvo.setTrade_serial_number(String.valueOf(idWorker.nextId()));
			policyService.saveTransaction(pvo);
			return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 8){//华泰
			String hbRet = tYX_HTRequestService.request_ht_tyx(Long.parseLong(oid),ConstProp.DIGIT_ONE,null);
			if(hbRet.contains(ConstProp.CODE_SUCCESS)){
				result = tYX_HTRequestService.request_ht_tyx(Long.parseLong(oid),"25",null);
				strs = result.split(ConstProp.POUND_SIGN);
			} 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);
			}
		}else{
			return new ResultDto("产品未匹配到对应接口！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		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-TYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(productService.api_request_sign(dto.getProduct_code()) == 4) {//如果是人保的返回报文处理
			String payPath = "",payNo = "";
			if(strs[2].contains("：")){
				payNo = strs[2].split(",")[0].split("：")[1];
				payPath = strs[2].split(",")[1].split("：")[1];
			}
			if(StringUtils.isEmpty(payNo)||StringUtils.isEmpty(payPath)){
				return new ResultDto("未获取到支付信息！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			pvo.setPolicy_serial_number(strs[1]);//设置投保单号
			pvo.setDeal_url(payPath);
			pvo.setPayment_method(ConstProp.DIGIT_ONE);
			pvo.setPay_type(DictConst.PAY_TYPE_WX);//支付方式
			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()));
			pvo.setPay_order_number(payNo);
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			pvo.setTrade_serial_number(String.valueOf(idWorker.nextId()));
			policyService.saveTransaction(pvo);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 5) {//如果是平安财的返回报文处理
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			pvo.setPolicy_serial_number(strs[1]);//设置投保单号
			pvo.setNotice_no(strs[2]);//通知单号
			policyService.saveTransaction(pvo);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 6) {//如果是长安的返回报文处理
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			pvo.setPolicy_serial_number(strs[1]);//设置投保单号
			policyService.saveTransaction(pvo);
		}else if(productService.api_request_sign(dto.getProduct_code()) == 8) {//华泰
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			pvo.setPolicy_serial_number(strs[1]);//设置投保单号
			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);
		}else{
			//TODO 泰康/平安核保后，获取投保单号设置到数据库
			PolicyTransactionVo pvo= new PolicyTransactionVo();
			pvo.setPolicy_id(oid);
			pvo.setPolicy_serial_number(strs[1]);//设置投保单号
			policyService.saveTransaction(pvo);
		}
		return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

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

	@RequestMapping("/api/gmr/transaction/finish_iframe/{oid}")
	public ModelAndView finish_iframe(@PathVariable long oid) {
		ModelAndView view = new ModelAndView("/coninsweb/api/gmr/gmr_order_finish");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if (  userdetail == null ) {
			return new ModelAndView(Constant.LOGIN_URL+"/api/gmr/transaction/finish_iframe/"+oid);
		}
		view.addObject(ConstProp.USERDETAIL,userdetail);
		view.addObject(ConstProp.ORDER_ID, String.valueOf(oid));
		setTokenByApi(view);
		return view;
	}

	/**
	 * 平安回调地址
	 * @param oid  订单id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/api/syntony-service/{oid}")
	public ModelAndView syntonyService(@PathVariable long oid) {
		ModelAndView view = new ModelAndView("/coninsweb/api/gmr/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;
	}


	@RequestMapping("/api/gmr/transaction/uploadPayMentFile")
	public JSONObject uploadPayMentFile(InsureVo insInsuranceSlip, HttpServletRequest request){
		JSONObject json = new JSONObject();
		String message =ConstProp.BLANK_CHAR;
		String status=ConstProp.CODE_FAILURE;
		boolean endUpload = false;
		String paymentPath = request.getParameter("paymentPath");
		InsInsuranceSlip oldPolicy = insInsuranceSlipService.selectById(insInsuranceSlip.getIns_insurance_slip_id());
		InsTransaction transaction = transactionService.getTranctionByorderIDAndStatus(oldPolicy.getIns_insurance_slip_id());
		if(StringUtils.isNotEmpty(paymentPath)){
			transaction.setPay_order_url(paymentPath);
			if(StringUtils.isNotEmpty(oldPolicy.getInsure_path()) && StringUtils.isNotEmpty(transaction.getPay_order_url())){
				endUpload = true;
			}
			transactionService.updateById(transaction);
			if(endUpload){
				//诉讼待支付界面上传支付凭证时传分销创建或更新交易信息记录
				policyService.saveOrUpdateTransaction_ss(String.valueOf(oldPolicy.getIns_insurance_slip_id()), transaction.getPay_order_url(),"",transaction.getPath_sign());
				/*if(!oldPolicy.getEmt().equals(EmailMsgType.ACCOUNTPAID)){//说明已经发送邮件
					//TODO 给保险公司该业务负责人及我司该业务负责人用邮件及短信方式发送通知
					notifyService.policy_applyFor(oldPolicy, EmailMsgType.ACCOUNTPAID);
				}*/
			}
			//完成上传后异步发送邮件
			new Thread(()->{
				policyService.JFPZ_SendEmail(oldPolicy.getIns_insurance_slip_id(),transaction.getPay_order_url());
			}).start();
			message ="上传成功！";
			status =ConstProp.CODE_SUCCESS;
		} else {
			message = "上传文件异常，请重试";
		}
		json.put("message", message);
		json.put("status", status);
		json.put("endUpload", endUpload);
		return json;
	}

	@RequestMapping("/api/com/gmr/transaction/uploadPayMentFile")
	@ResponseBody
	public ResultDto uploadPayMentFile(HttpServletRequest request){
		String doPayments = request.getParameter("doPayments");
		String payAmount = request.getParameter("payAmount");
		String oid = request.getParameter("oid");
		String paymentPath = request.getParameter("paymentPath");
		if(StringUtils.isEmpty(doPayments) || StringUtils.isEmpty(payAmount) || StringUtils.isEmpty(oid)|| StringUtils.isEmpty(paymentPath)){
			return new ResultDto("数据丢失，操作失败！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}else{
			String orderID = policyService.uploadPayMentFileToTranction(paymentPath, oid, doPayments, payAmount);
			if(StringUtils.isNotEmpty(orderID)){
				//完成上传后异步发送邮件
				new Thread(()->{
					policyService.JFPZ_SendEmail(Long.parseLong(oid),paymentPath);
				}).start();
				return new ResultDto("上传成功！", ConstProp.CODE_SUCCESS, "true", ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}else{
				return new ResultDto("数据存储失败！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}
	}

	/**
	 * <b>完成支付 </b>
	 *
	 * @param oid
	 * @return
	 * @author luopeng
	 * @date 2016年12月21日 下午1:51:30
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(redirectUrl = "forward:/synopsis/loseView")
	@RequestMapping("/api/gmr/gmr/transaction/finishPay/{oid}")
	public ModelAndView finishPay(@PathVariable long oid, HttpServletRequest request){
		ModelAndView view = new ModelAndView("/coninsweb/api/gmr/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;
	}

	@RequestMapping("/api/gmr/transaction/isPaySuccess/{oid}")
	public @ResponseBody String isPaySuccess(@PathVariable long oid){
		com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
		List<InsTransaction> tranList = transactionService.selectInsTransactionByInsOrderForm(oid);
		String status = ConstProp.CODE_FAILURE;
		if(tranList.size()>0){
			InsTransaction it = tranList.get(0);
			if(DictConst.PAY_STATUS_YZF.equals(it.getTransaction_status())){
				status = ConstProp.CODE_SUCCESS;
			}
		}
		json.put("status", status);
		return json.toJSONString();
	}

	@RequestMapping("/api/gmr/transaction/isPolicyUnderwrite/{oid}")
	public @ResponseBody String isPolicyUnderwrite(@PathVariable long oid){
		com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
		OrderFormVo orderVo = policyService.accordingToOrderIDToGetPolicyDto(oid);
		String status = ConstProp.CODE_FAILURE;
		if(orderVo != null){
			if(DictConst.ORDER_STATUS_YCB.equals(orderVo.getPolicy_status())){
				status = ConstProp.CODE_SUCCESS;
			}
		}
		json.put("status", status);
		return json.toJSONString();
	}

	/**
	 * 团意险支付完成页面-都邦
	 * @param oid 订单id
	 * @param request
	 * @return
	 */
	@RequestMapping("/api/gmr/transaction/policyUnderwrite/{oid}")
	public ModelAndView policyUnderwrite(@PathVariable("oid") String oid,HttpServletRequest request) {
		logger.info("团意险承保完成后页面展示-star");
		logger.info("团意险承保完成后页面展示-policyUnderwrite：oid:"+oid);
		ModelAndView view = new ModelAndView("/coninsweb/api/gmr/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;
	}
}
