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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.common.dto.AjaxResult;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.service.ComBankCodeService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.spring.annotation.LoginRequired;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.third.gzx.changan.GZX_CARequestService;
import com.bcxin.ins.third.gzx.huatai.GZX_HTRequestService;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.RegionUtils;
import com.bcxin.ins.util.enums.IdType;
import com.bcxin.ins.util.enums.NatureLinkage;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.IdWorker;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 负责前台展责险投保流程的业务逻辑处理
 * @author zxf
 *
 */
@Controller
@RequestMapping("/insurance/gzx/policy")
public class GZXPolicyController extends BaseController {


	@Autowired
	private PolicyService policyService;

	@Autowired
	private ProductService productService;

	@Autowired
	private GZX_CARequestService gZX_CARequestService;
	@Autowired
	private GZX_HTRequestService gZX_HTRequestService;

	@Autowired
	private ComBankCodeService comBankCodeService;

	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【视图】产品-访问投保页")
	@LoginRequired(methodParamKey={"1#product_id"}, redirectUrl = "/insurance/gzx/policy/policyInit/{product_id}")
	@RequestMapping("/policyInit/{product_id}")
	public ModelAndView policyInit(HttpServletRequest request, @PathVariable Long product_id, ModelMap model) {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		//请求百保盾返回企业信息及员工信息
		SpecialPublicDutyVo vo = new SpecialPublicDutyVo();
		ProductVo pd = productService.getProduct(product_id);
		MailPolicyVo mVo = new MailPolicyVo();
		ModelAndView view = new ModelAndView();
		vo.setMailPolicyVo(mVo);
		if(StringUtils.isEmpty(userdetail.getWeb_type())){
			view.addObject(ConstProp.VO, vo);
			view.addObject(ConstProp.RECOMMEND_CODE,UserSupportUtil.getRecommendCode());
			orderAllotInit(pd, view);
			return view;
		}
		/*if(userdetail.getWeb_type().contains(ConstProp.PSS)){
			List<BLBCommunicationDto> actList = policyService.getBLBCommunicationDtoByUserID_PSSAPI(userdetail.getWeb_id(),pd.getProduct_code().split(ConstProp.MINUS)[2],userdetail.getWeb_type(),"");
			List<RoleSubjectVo> roleList = policyService.getRoleSubjectVoByUserID_PSSAPI(userdetail.getWeb_id(),userdetail.getWeb_type());
			if(roleList != null){
				vo.setRoleSubjectList(roleList);
			}
			view.addObject("acts", actList);
		}*/

		view.addObject(ConstProp.VO, vo);
		view.addObject(ConstProp.RECOMMEND_CODE,UserSupportUtil.getRecommendCode());
		orderAllotInit(pd, view);
		setTokenByApi(view);
		return view;
	}

	private String createOrderAndGetOrderIDByProductID(Long product_id, Long user_id, String recommendCode,String trade_serial_number){
		Map<String, Object> map = policyService.createOrderFormByProductOid(product_id, user_id, recommendCode, trade_serial_number);
		if(map.get(ConstProp.ORDER_ID) != null){
			return (String)map.get(ConstProp.ORDER_ID);
		}
		return "";
	}

	/**
	 * <b>通过订单ID跳转到投保界面 </b>
	 *
	 * @param request
	 * @param order_id
	 * @return
	 * @author ZXF
	 * @date 2016年12月21日 下午1:46:44
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"1#order_id"}, redirectUrl = "/insurance/gzx/policy/policy/{order_id}")
	@RequestMapping("/policy/{order_id}")
	public ModelAndView enterInfo(HttpServletRequest request, @PathVariable Long order_id) {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		ModelAndView view = new ModelAndView();
		orderAllot(order_id,userdetail, view);
		setTokenByApi(view);
		return view;
	}

	private void orderAllotInit(ProductVo pd, ModelAndView view) {
		OrderFormVo dto = new OrderFormVo();
		dto.setProduct_oid(pd.getOid());
		dto.setProduct_code(pd.getProduct_code());
		dto.setGross_premium(pd.getPremium_min());
		dto.setTrade_serial_number(String.valueOf(com.bcxin.ins.util.IdWorker.getId()));
		view.addObject("sigId", String.valueOf(com.bcxin.ins.util.IdWorker.getId()));//普通的页面标识
		view.addObject(ConstProp.PD,pd);
		view.addObject(ConstProp.DTO,dto);
		view.addObject("comTypeList", IdType.comList());
		view.addObject("natureList", NatureLinkage.getListByProvince(""));
		if(StringUtils.isNotEmpty(pd.getProduct_code())){
			if(ConstProp.GZX.equals(pd.getProduct_code().split(ConstProp.MINUS)[0])){
				try {
					view.addObject(ConstProp.PROVINCELIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR));
				}catch (Exception e){
					e.printStackTrace();
				}
				view.setViewName("/coninsweb/insurance/gzx/policy/gzx_enterBasicInfo");
			}
		}
	}

	@RequestMapping(value = "/natureChange")
	@ResponseBody
	public Map<String, String> natureChange(HttpServletRequest request) {
		String nID = request.getParameter("nID");
		if(StringUtils.isNotEmpty(nID)){
			Map<String, String> map = NatureLinkage.getMapByProvince(nID);
			return map;
		}
		return null;
	}

	private void orderAllot(Long order_id,ClientUserVo userdetail, ModelAndView view) {
		try {
			OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
			ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
			view.addObject(ConstProp.PD,pd);
			view.addObject("comTypeList", IdType.comList());
			view.addObject("natureList", NatureLinkage.getListByProvince(""));
			view.addObject(ConstProp.DTO,dto);
			if(StringUtils.isEmpty(dto.getProduct_code()) || !ConstProp.GZX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
				return;
			}
			SpecialPublicDutyVo vo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(order_id);
			/*if(StringUtils.isNotEmpty(userdetail.getWeb_type())){
				if(userdetail.getWeb_type().contains(ConstProp.PSS)){
					List<BLBCommunicationDto> actList = policyService.getBLBCommunicationDtoByUserID_PSSAPI(userdetail.getWeb_id(),pd.getProduct_code().split(ConstProp.MINUS)[2],userdetail.getWeb_type(),vo.getThr_order_id());
					view.addObject("acts", actList);
				}
			}*/
			view.addObject(ConstProp.VO,vo);
			view.setViewName("/coninsweb/insurance/gzx/policy/gzx_enterBasicInfo");
			if(vo != null){
				view.addObject(ConstProp.PROVINCELIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR));
				if(vo.getRoleSubjectList() != null){
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getNature_two())
							&&StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getCom_nature())){
						view.addObject("natureTwoList", NatureLinkage.getListByProvince(vo.getRoleSubjectList().get(0).getCom_nature()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getReg_province())){
						view.addObject(ConstProp.CITYLIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getRoleSubjectList().get(0).getReg_province()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getBank_province())){
						view.addObject("bankCityList", RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getRoleSubjectList().get(0).getBank_province()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getBank_city())){
						view.addObject("bankTypeList", comBankCodeService.getAllBankType(vo.getRoleSubjectList().get(0).getBank_city()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getBank_type())){
						view.addObject("bankAddrList", comBankCodeService.getAllBankAddr(vo.getRoleSubjectList().get(0).getBank_city(),vo.getRoleSubjectList().get(0).getBank_type()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(0).getReg_city())){
						view.addObject(ConstProp.AREALIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getRoleSubjectList().get(0).getReg_city()));
					}
					//被保险人地址
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(1).getNature_two())
							&&StringUtils.isNotEmpty(vo.getRoleSubjectList().get(1).getCom_nature())){
						view.addObject("natureTwoList1", NatureLinkage.getListByProvince(vo.getRoleSubjectList().get(1).getCom_nature()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(1).getReg_province())){
						view.addObject(ConstProp.REG_CITY_1_LIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getRoleSubjectList().get(1).getReg_province()));
					}
					if(StringUtils.isNotEmpty(vo.getRoleSubjectList().get(1).getReg_city())){
						view.addObject(ConstProp.REG_AREA_1_LIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getRoleSubjectList().get(1).getReg_city()));
					}
				}
				if(vo.getMailPolicyVo() != null&&StringUtils.isNotEmpty(vo.getMailPolicyVo().getBank_province())){
					view.addObject(ConstProp.BANKCITYLIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getMailPolicyVo().getBank_province()));
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	/**
	 * <b>展责险投保界面跳转到确认页面中间的业务 </b>
	 *
	 * @param order_id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author ZXF
	 * @date 2016年12月28日 下午4:21:44
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#order_id"}, redirectUrl = "/insurance/gzx/policy/confirmPage/{order_id}")
	@RequestMapping("/confirmPage/{order_id}")
	public ModelAndView confirmPage(@PathVariable Long order_id, HttpServletRequest request) throws Exception{
		ModelAndView view = new ModelAndView();
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
		view.addObject(ConstProp.PD,pd);
		view.addObject(ConstProp.DTO,dto);
		view.addObject("comTypeList", IdType.comList());
		if(StringUtils.isEmpty(dto.getProduct_code()) ? false : ConstProp.GZX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
			view.setViewName("/coninsweb/insurance/gzx/policy/policyConfirm");
			List<NatureLinkage> natureList = NatureLinkage.doList();
			SpecialPublicDutyVo vo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(order_id);
			view.addObject(ConstProp.VO,vo);
			view.addObject("natureList",natureList);
			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_ROLE_1, RegionUtils.getRegionNameByALLCode(vo.getRoleSubjectList().get(1).getReg_province(), vo.getRoleSubjectList().get(1).getReg_city(), vo.getRoleSubjectList().get(1).getReg_district()));
		}
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b>展责险投保单客户填一半暂存，方法 </b>
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author ZXF
	 * @date 2016年12月21日 下午1:47:55
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_ORDER,title ="【请求】产品-订单投保")
	@RequestMapping("/pendingSpecialPublicDutyVoPolicy")
	@ResponseBody
	public ResultDto pendingSpecialPublicDutyVoPolicy(SpecialPublicDutyVo vo, HttpServletRequest request, HttpServletResponse response) throws Exception{
		String recommendCode = request.getParameter(ConstProp.RECOMMENDCODE);
		return policyService.pendingSpecialPublicDutyVoPolicy(vo, recommendCode);
	}

	/**
	 * <b>修改订单状态</b>
	 *
	 * @return
	 * @throws Exception
	 * @author ZXF
	 * @date 2016年12月21日 下午1:47:55
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired
	@RequestMapping("/updateOrderFormStatus")
	@ResponseBody
	public ResultDto updateOrderFormStatus(HttpServletRequest request) throws Exception{
		String order_id = request.getParameter(ConstProp.ORDER_ID);
		String status = request.getParameter("status");
		if(StringUtils.isEmpty(order_id) || StringUtils.isEmpty(status)){
			return new ResultDto("数据丢失，请刷新页面后重试！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		OrderFormVo vo = new OrderFormVo();
		vo.setOid(String.valueOf(order_id));
		vo.setPolicy_status(status);
		String orderID = policyService.updateOrderFormStatus(vo);
		if(StringUtils.isNotEmpty(orderID)){
			return new ResultDto("订单录入成功。", ConstProp.CODE_SUCCESS, orderID, ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR);
		}else{
			return new ResultDto("数据丢失，请刷新页面后重试！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	/**
	 * <b>业务逻辑处理，保存保单信息
	 * 页面流转：点击保单保存，跳转支付页面 </b>
	 *
	 * @param order_id 保单id
	 * @return
	 * @author ZXF
	 * @date 2016年12月21日 下午1:48:20
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#order_id"}, redirectUrl = "/insurance/gzx/policy/policyPayment/{order_id}")
	@RequestMapping("/policyPayment/{order_id}")
	public ModelAndView savePolicy(@PathVariable long order_id, HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		try {
			OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(order_id);
			ProductVo pd = productService.getProduct(Long.parseLong(vo.getProduct_oid()));
			view.addObject(ConstProp.PD,pd);
			view.addObject(ConstProp.DTO,vo);
			if(StringUtils.isNotEmpty(vo.getPay_methods())){
				AdviceNoteVo anVo = policyService.accordingToOrderIDToGetAdviceNoteVo(order_id);
				view.setViewName("/coninsweb/insurance/gzx/transaction/paymentNotice");
				view.addObject(ConstProp.ANVO, anVo);
				view.addObject(ConstProp.NOWTIME,new Date());
				return view;
			}
			if(vo.getPolicy_status().equals(ConstProp.DIGIT_TWO)){
				//待核保
				view.setViewName("/coninsweb/insurance/gzx/transaction/waitOffer");
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_YSH)){
				AdviceNoteVo anVo = null;
				if(vo.getProduct_code().contains(ConstProp.ZZX_CA)){
					view = new ModelAndView("/coninsweb/api/gzx/transaction/paymentNoticeCA");
					anVo = policyService.accordingToOrderIDToGetAdviceNoteVo(order_id);
				}
				view.addObject(ConstProp.ANVO, anVo);
			}else if(vo.getPolicy_status().equals(ConstProp.DIGIT_SIX)){
				//核保通过
				view.setViewName("/coninsweb/insurance/gzx/transaction/passUnderwriting");
			}else if(vo.getPolicy_status().equals(ConstProp.DIGIT_FIFTEEN)){
				//拒保
				view.setViewName("/coninsweb/insurance/gzx/transaction/declinature");
			}else if(vo.getPolicy_status().equals(ConstProp.DIGIT_FOUR)){
				//待支付
				if(productService.api_request_sign(vo.getProduct_code()) == 2){
					//平安财
					view.setViewName("/coninsweb/insurance/gzx/transaction/policyPayment_PAC");
				}else if(productService.api_request_sign(vo.getProduct_code()) == 3){
					view = new ModelAndView("/coninsweb/api/gzx/transaction/policyPaymentCA");
					GZX_CA_Payment(order_id, view, vo);
				}else if(productService.api_request_sign(vo.getProduct_code()) == 1){
					view = new ModelAndView("/coninsweb/insurance/gzx/transaction/policyPayment_HT");
					GZX_HT_Payment(order_id, view, vo);
				}
			}else if(vo.getPolicy_status().equals(ConstProp.DIGIT_FIVE)){
				//待承保
				view.setViewName("/coninsweb/insurance/gzx/transaction/finishPay");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		view.addObject(ConstProp.NOWTIME,new Date());
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b> 长安支付页面信息 </b>
	 * @author ZXF
	 * @create 2020/09/28 0028 10:05
	 * @version
	 * @注意事项 </b>
	 */
	private void GZX_CA_Payment(@PathVariable long order_id, ModelAndView view, OrderFormVo vo) throws Exception {
		//判断是否为当天的支付号，如果不是就从新获取支付地址
		String yxDate = DateUtil.convertDateToString(new Date(),DateUtil.FORMAT6);
		boolean boo = StringUtils.isEmpty(vo.getPay_order_number())?false:vo.getPay_order_number().contains(yxDate);
		if(StringUtils.isNotEmpty(vo.getShow_url()) && boo){
			view.addObject("payurl",vo.getShow_url());
		}else{
			String result = gZX_CARequestService.request_ca_gzx(Long.parseLong(vo.getOid()), TransTypeEnum.ZFDZ.getValue());
			String[] strs = result.split(ConstProp.POUND_SIGN);
			if(ConstProp.CODE_SUCCESS.equals(strs[0])){
				policyService.payUrlChangeCA(order_id,strs[1],strs[2]);
				view.addObject("payurl",strs[2]);
			}
		}
	}

	/**
	 * <b> 长安支付页面信息 </b>
	 * @author ZXF
	 * @create 2020/09/28 0028 10:05
	 * @version
	 * @注意事项 </b>
	 */
	private void GZX_HT_Payment(@PathVariable long order_id, ModelAndView view, OrderFormVo vo) throws Exception {
		//判断是否为当天的支付号，如果不是就从新获取支付地址
		String yxDate = DateUtil.convertDateToString(new Date(),DateUtil.FORMAT6);
		boolean boo = StringUtils.isEmpty(vo.getPay_order_number())?false:vo.getPay_order_number().contains(yxDate);
		if(StringUtils.isNotEmpty(vo.getShow_url()) && boo){
			view.addObject("payurl",vo.getShow_url());
		}else{
			String result = gZX_HTRequestService.request_ht_gzx(Long.parseLong(vo.getOid()), TransTypeEnum.ZFDZ.getValue(),null);
			String[] strs = result.split(ConstProp.POUND_SIGN);
			if(ConstProp.CODE_SUCCESS.equals(strs[0])){
				policyService.payUrlChangeCA(order_id, IdWorker.getId()+"",strs[1]);
				view.addObject("payurl",strs[1]);
			}
		}
	}

	@RequestMapping("/requestEPolicy/{oid}")
	@ResponseBody
	public ResultDto requestEPolicy(@PathVariable Long oid) throws Exception {
		OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(oid);
		if(vo.getProduct_code().indexOf(ConstProp.GZX_PAC)!=-1&&StringUtils.isEmpty(vo.getInsure_path())){
			policyService.HTTP_PAC_GZX_DZBD(oid,null,vo);
		}
		if(StringUtils.isNotEmpty(vo.getInsure_path())){
			return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS, vo.getInsure_path(), ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		return new ResultDto("电子保单生成中(这可能需要半个小时，请稍后重试)...", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	@RequestMapping("/sessionInfo")
	@ResponseBody
	public ResultDto sessionInfo(HttpServletRequest reqeust, ModelMap model) {
		String name = reqeust.getParameter("name");
		String base64 = reqeust.getParameter("base64");
		model.addAttribute(name, base64);
		return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
	}

	/**
	 * 通过pss的订单id去调用pss提供的查询活动详细信息接口获取活动相关及发票相关BLBCommunicationDto
	 * @param thr_order_id pss的订单id
	 * @return BLBCommunicationDto的jsonToString
	 */
	@RequestMapping("/getActivityByPss/{thr_order_id}")
	@ResponseBody
	public String getActivityByPss(@PathVariable String thr_order_id) {
		String result = ConstProp.BLANK_CHAR;
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail == null){
			return result;
		}
		try {
			BLBCommunicationDto dto = policyService.getBLBCommunicationDtoByOrderID_PSSAPI(thr_order_id, userdetail.getWeb_type());
			if(dto != null){
				result = JSONObject.toJSONString(dto);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
}
