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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.third.build.dubang.Build_DBRequestService;
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.RegionUtils;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.List;


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

	private Logger communicatorLog =  LoggerFactory.getLogger(Build_Transaction_Controller.class);

	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipService;

	@Autowired
	private ProductService productService;
	@Autowired
	private PolicyService policyService;
	@Autowired
	private Build_DBRequestService build_DBRequestService;
	@Autowired
	private InsTransactionAPIService insTransactionAPIService;


	@Autowired
	private InsTransactionAPIService transactionService;

	private String CODE = "code";
	private String MSG = "msg";
	private String CODE_301 = "301";
	private String POLICYID = "policyId";
	private String POLICYPAYMENTTYPE = "policyPaymentType";
	private String OID = "oid";
	private String PAYMENT_PATH = "payment_path";
	private String MESSAGE = "message";
	private String STATUS = "status";
	private String ENDUPLOAD = "endUpload";


	/**
	 * <b>业务逻辑处理，选择支付方式，跳转支付平台
	 * 目前默认跳转银联支付 </b> 
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @author luopeng 
	 * @date 2016年12月21日 下午1:50:39
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired
	@RequestMapping("/insurance/build/transaction/policyPayment")
	public void policyPayment(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		response.setCharacterEncoding(ConstProp.ENCODE_UTF8);
		response.setContentType(ConstProp.ENCODE_UTF8_TEXT);
		String oid = request.getParameter(POLICYID);
		String payType = request.getParameter(POLICYPAYMENTTYPE);
		policyService.policyPayment_bd_cpic( oid, payType,userdetail.getOid(), response);
	}
	/**
	 * <b>业务逻辑处理，选择支付方式，跳转支付平台
	 * 目前默认跳转银联支付 </b>
	 *
	 * @param
	 * @param
	 * @throws
	 * @author luopeng
	 * @date 2016年12月21日 下午1:50:39
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#oid"}, redirectUrl = "insurance/build/transaction/policyVerify/{oid}")
	@RequestMapping(value="/insurance/build/transaction/policyVerify/{oid}")
	public ModelAndView policyVerify(@PathVariable("oid") Long oid){
		ModelAndView view = new ModelAndView("/coninsweb/insurance/build/transaction/finishPay");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto != null){
			policyService.port_107002(dto);
			dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
			if(StringUtils.isNotEmpty(dto.getExternal_reference())){
				view.addObject(CODE,ConstProp.CODE_SUCCESS);
				view.addObject(MSG, "支付成功！");
			}if(StringUtils.isEmpty(dto.getExternal_reference())&&StringUtils.isNotEmpty(dto.getPolicy_serial_number())){
				view.addObject(CODE,ConstProp.CODE_FAILURE);
				view.addObject(MSG, "未完成支付！");
			}else if(StringUtils.isEmpty(dto.getPolicy_serial_number())){
				view.addObject(CODE,CODE_301);
				view.addObject(MSG, "未完成支付！");
			}
			view.addObject(ConstProp.DTO, dto);
		}else{
			view.addObject(CODE,CODE_301);
			view.addObject(MSG, "订单信息丢失！");
		}
		setTokenByApi(view);
		return view;
	}

	@LoginRequired
	@RequestMapping(value="/insurance/build/transaction/lastPolicyVerify/{oid}")
	@ResponseBody
	public ResultDto lastPolicyVerify(@PathVariable("oid") Long oid){
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(dto != null){
			policyService.port_107002(dto);

			if(StringUtils.isNotEmpty(dto.getExternal_reference())){
				return new ResultDto("支付成功！", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}if(StringUtils.isEmpty(dto.getExternal_reference())&&StringUtils.isNotEmpty(dto.getPolicy_serial_number())){
				return new ResultDto("未完成支付！！", ConstProp.CODE_FAILURE, dto.getShow_url(), ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}else if(StringUtils.isEmpty(dto.getPolicy_serial_number())){
				return new ResultDto("为完成核保！！", CODE_301, dto.getShow_url(), ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}else{
			return new ResultDto("订单信息丢失！！", CODE_301, dto.getShow_url(), ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("系统出错！！", CODE_301, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}
	

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

	@RequestMapping("/insurance/transaction/uploadPayMentFile")
	@ResponseBody
	public ResultDto uploadPayMentFile(HttpServletRequest request){
		String paymentPath = request.getParameter(PAYMENT_PATH);
		String oid = request.getParameter(OID);
		return policyService.uploadPayMentFile_com( paymentPath, oid);
	}
	
	/**
	 * <b>打印投保单 </b> 
	 * 
	 * @param oid
	 * @return
	 * @author luopeng 
	 * @date 2016年12月21日 下午1:51:18
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#oid"}, redirectUrl = "insurance/transaction/printPolicy/{oid}")
	@RequestMapping("/insurance/transaction/printPolicy/{oid}")
	public ModelAndView printPolicy(@PathVariable long oid){
		ModelAndView view = new ModelAndView("/coninsweb/pc/index");
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(oid);
		view.addObject(ConstProp.DTO, dto);
		if(StringUtils.isEmpty(dto.getProduct_code()) ? false : "BZX-SSBQ".equals(dto.getProduct_code())){
			view.setViewName("/coninsweb/insurance/transaction/policy/policyPrint_ss");
			SpecialLitigationVo_1 vo1 = policyService.accordingToOrderIDToGetSpecialLitigationVo_1(oid);
			SpecialLitigationVo_2 vo2 = policyService.accordingToOrderIDToGetSpecialLitigationVo_2(oid);
			SpecialLitigationVo_3 vo3 = policyService.accordingToOrderIDToGetSpecialLitigationVo_3(oid);
			view.addObject(ConstProp.VO1,vo1);
			view.addObject(ConstProp.VO2,vo2);
			view.addObject(ConstProp.VO3,vo3);
			view.addObject(ConstProp.REG_ROLE, RegionUtils.getRegionNameByALLCode(vo1.getRoleSubjectList().get(0).getReg_province(),vo1.getRoleSubjectList().get(0).getReg_city(),vo1.getRoleSubjectList().get(0).getReg_district()));
		}else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : "BZX-GCLY".equals(dto.getProduct_code())){
			view.setViewName("/coninsweb/insurance/transaction/policy/policyPrint_ly");
			SpecialPerformanceVo_1 vo1 = policyService.accordingToOrderIDToGetSpecialPerformanceVo_1(oid);
			SpecialPerformanceVo_2 vo2 = policyService.accordingToOrderIDToGetSpecialPerformanceVo_2(oid);
			SpecialPerformanceVo_3 vo3 = policyService.accordingToOrderIDToGetSpecialPerformanceVo_3(oid);
			view.addObject(ConstProp.VO1,vo1);
			view.addObject(ConstProp.VO2,vo2);
			view.addObject(ConstProp.VO3,vo3);
			view.addObject(ConstProp.REG_ROLE, RegionUtils.getRegionNameByALLCode(vo2.getRoleSubjectList().get(0).getReg_province(),vo2.getRoleSubjectList().get(0).getReg_city(),vo2.getRoleSubjectList().get(0).getReg_district()));
		}
		setTokenByApi(view);
		return view;
	}
	
	@RequestMapping("/insurance/transaction/uploadInsureFile")
	public JSONObject uploadInsureFile(InsureVo insInsuranceSlip,HttpServletRequest request){
		JSONObject json = new JSONObject();
		String message =ConstProp.BLANK_CHAR;
		String status=ConstProp.CODE_FAILURE;
		boolean endUpload = false;
//		InsurancePolicy oldPolicy = insurancePolicyService.findPolicyByOid(insurancePolicy.getOid());
		InsInsuranceSlip oldPolicy = insInsuranceSlipService.selectById(insInsuranceSlip.getIns_insurance_slip_id());
		InsTransaction transaction = transactionService.getTranctionByorderIDAndStatus(oldPolicy.getIns_insurance_slip_id());
//		String insureFile = request.getParameter("insurePath");
		if(StringUtils.isNotEmpty(insInsuranceSlip.getUser_insure_path())){
			oldPolicy.setUser_insure_path(insInsuranceSlip.getUser_insure_path());
			/*Map<String,String> map = FileUtils.ossFileUpload_sysc(insureFile, "insure/"+oldPolicy.getOid(), true, "");
			String url = map.get("url");
			if(StringUtil.isNotEmpty(url)) {
				oldPolicy.setInsurePath(url);
				System.out.println(url);
			}*/
			if(StringUtils.isNotEmpty(oldPolicy.getUser_insure_path()) && StringUtils.isNotEmpty(transaction.getPay_order_url())){
//				oldPolicy.setPolicyStatus(PolicyStatus.WAITINSURANCE);
				endUpload = true;
			}
			insInsuranceSlipService.updateById(oldPolicy);
//			policyInsureService.insure(oldPolicy);
//			if(insurancePolicyService.saveObj(oldPolicy)){
			if(endUpload){
				//诉讼待支付界面上传支付凭证时传分销创建或更新交易信息记录
				//policyTransactionService.saveOrUpdateTransaction_ss(String.valueOf(oldPolicy.getOid()), oldPolicy.getPaymentPath());
				String emailTitle = "订单已付款提醒";
				String emailContent = "您有订单客户已付款并上传缴费凭证。";
//				userService.sendNotice(oldPolicy.getInsurerUser(), emailTitle, emailContent);
			}
			//完成上传后异步发送邮件
			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("/insurance/transaction/getQRCode/{oid}")
	public @ResponseBody String getQRCode(@PathVariable long oid){
		JSONObject json = new JSONObject();
		String result = build_DBRequestService.requestDB(oid,ConstProp.DIGIT_TWO,null);
		json.put(MESSAGE, result.split(ConstProp.POUND_SIGN)[1]);
		json.put(STATUS, result.split(ConstProp.POUND_SIGN)[0]);
		return json.toJSONString();
	}

	@RequestMapping("/insurance/transaction/isPaySuccess/{oid}")
	public @ResponseBody String isPaySuccess(@PathVariable long oid){
		JSONObject json = new JSONObject();
		List<InsTransaction> tranList = insTransactionAPIService.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("/insurance/transaction/isPolicyUnderwrite/{oid}")
	public @ResponseBody String isPolicyUnderwrite(@PathVariable long oid){
		JSONObject json = new 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("/insurance/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/insurance/build/transaction/finishPay_db");
		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;
	}

	@RequestMapping("/insurance/transaction/uploadInsureFile_user")
	@ResponseBody
	public ResultDto uploadInsureFile_user(InsureVo insInsuranceSlip,HttpServletRequest request){
		InsInsuranceSlip oldPolicy = insInsuranceSlipService.selectById(insInsuranceSlip.getIns_insurance_slip_id());
		if(StringUtils.isNotEmpty(insInsuranceSlip.getUser_insure_path())){
			oldPolicy.setUser_insure_path(insInsuranceSlip.getUser_insure_path());
			insInsuranceSlipService.updateById(oldPolicy);
			return new ResultDto("上传成功！", 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);
		}
	}
	
	/**
	 * <b>完成支付 </b> 
	 * 
	 * @param oid
	 * @return
	 * @author luopeng 
	 * @date 2016年12月21日 下午1:51:30
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#oid"}, redirectUrl = "insurance/transaction/finishPay/{oid}")
	@RequestMapping("/insurance/transaction/finishPay/{oid}")
	public ModelAndView finishPay(@PathVariable long oid){
		ModelAndView view = new ModelAndView("/coninsweb/insurance/transaction/finishPay");
		view.addObject(ConstProp.PD,productService.getProduct(oid));
		view.addObject(ConstProp.DTO,policyService.accordingToOrderIDToGetPolicyDto(oid));
		setTokenByApi(view);
		return view;
	}
}
