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

import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.service.ComBankCodeService;
import com.bcxin.ins.core.util.SysDictUtils;
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.spring.util.JedisUtils;
import com.bcxin.ins.third.tyx.changan.TYX_CARequestService;
import com.bcxin.ins.third.tyx.huatai.TYX_HTRequestService;
import com.bcxin.ins.third.tyx.pingancai.PACRequestService;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.enums.IdType;
import com.bcxin.ins.util.enums.NatureLinkage;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.*;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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


	@Autowired
	private PolicyService policyService;

	@Autowired
	private ProductService productService;

	@Autowired
	private PACRequestService pACRequestService;

	@Autowired
	private TYX_CARequestService tYX_CARequestService;
    @Autowired
    private TYX_HTRequestService tYX_HTRequestService;
	@Autowired
	private ComBankCodeService comBankCodeService;


	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【视图】产品-访问投保页")
	@LoginRequired(methodParamKey={"1#product_id"}, redirectUrl = "/insurance/tyx/policy/policyInit/{product_id}")
	@RequestMapping("/policyInit/{product_id}")
	public ModelAndView policyInit(HttpServletRequest request, @PathVariable Long product_id, ModelMap model) {
		ModelAndView view = new ModelAndView();
		String personNum = request.getParameter("personNum");
		int num = 0;
		if(StringUtils.isNotEmpty(personNum)){
			num = Integer.parseInt(personNum);
		}
		ProductVo pd = productService.getProduct(product_id);
		//请求百保盾返回企业信息及员工信息
		GMRPolicyVo vo = new GMRPolicyVo();
		if(StringUtils.isNotEmpty(pd.getProduct_code())?!pd.getProduct_code().contains(ConstProp.TYX_RB):false){
			MailPolicyVo mVo = new MailPolicyVo();
			mVo.setIs_send_einvoice(ConstProp.DIGIT_ONE);
			vo.setMailPolicyVo(mVo);
		}
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(StringUtils.isEmpty(userdetail.getWeb_type())){
			view.addObject(ConstProp.VO, vo);
			view.addObject(ConstProp.RECOMMEND_CODE,UserSupportUtil.getRecommendCode());
			orderAllotInit(pd, view);
			setTokenByApi(view);
			return view;
		}
		List<RoleSubjectVo> doList = null;
		if(userdetail.getWeb_type().contains(ConstProp.ARS)){
			doList = policyService.getComAndEmpByUserID_BBDAPI(userdetail.getWeb_id(),userdetail.getWeb_type());
		}
		if(userdetail.getWeb_type().contains(ConstProp.SAAS)||userdetail.getWeb_type().contains(ConstProp.PASP)){
			String cacheId = (String) request.getSession().getAttribute("saasCacheId");
			if(StringUtils.isNotEmpty(cacheId)){
				request.getSession().removeAttribute("saasCacheId");
				doList = policyService.getComAndEmpByCacheId_API(cacheId,userdetail.getWeb_type());
			}else{
				doList = policyService.getComAndEmpByUserID_API(userdetail.getWeb_id(),userdetail.getWeb_type());
			}
		}
		if(doList!=null){
			List<RoleSubjectVo> voList = sortRoleList(doList,num,0);
			vo.setRoleSubjectList(voList);
			//最低标准需要3条别保险人，不足就补齐
			if(doList.size()>0&&doList.size()<4){
				int ct = 4-doList.size();
				RoleSubjectVo nullVo = null;
				for(int i = 0; i < ct; i++){
					nullVo = new RoleSubjectVo();
					nullVo.setKind(ConstProp.DIGIT_TWO);
					doList.add(nullVo);
					nullVo = null;
				}
			}
		}
		view.addObject(ConstProp.VO, vo);
		view.addObject(ConstProp.RECOMMEND_CODE,UserSupportUtil.getRecommendCode());
		orderAllotInit(pd, view);
		setTokenByApi(view);
		return view;
	}

	/**
	 * 根据获取到的投保人被保人列表筛选排序
	 * @param doList
	 * @param num 被保人人数限制
	 * @param type 0为初始1为已存在被保险人
	 * @return
	 */
	private List<RoleSubjectVo> sortRoleList(List<RoleSubjectVo> doList,int num,int type){
		List<RoleSubjectVo> results = new ArrayList<RoleSubjectVo>();
		if(doList == null){
			if(num>0){
				RoleSubjectVo appRole = new RoleSubjectVo();
				appRole.setKind(ConstProp.DIGIT_ONE);
				results.add(appRole);
				RoleSubjectVo insRole = null;
				for(int i=0;i<num;i++){
					insRole = new RoleSubjectVo();
					insRole.setKind(ConstProp.DIGIT_TWO);
					insRole.setMajor_group(ConstProp.DIGIT_ONE);
					results.add(insRole);
					insRole = null;
				}
				return results;
			}else{
				return null;
			}
		}
		List<RoleSubjectVo> insurceRoleList = new ArrayList<RoleSubjectVo>();
		for(RoleSubjectVo vo : doList){
			if(ConstProp.DIGIT_ONE.equals(vo.getKind())){
				results.add(vo);
			}else{
				insurceRoleList.add(vo);
			}
		}
		if(results.size() == 0){
			RoleSubjectVo vo = new RoleSubjectVo();
			vo.setKind(ConstProp.DIGIT_ONE);
			results.add(vo);
		}
		if(type != 0){
			results.addAll(insurceRoleList);
			return results;
		}
		//以上筛选投保人，筛选被保险人
		if(insurceRoleList.size()<=0){
			return results;
		}
		int insRoleNum = insurceRoleList.size();
		if(insRoleNum<num){//加载被保险人，被保险人小于限制人数
			results.addAll(insurceRoleList);
			int lastNum = num-insRoleNum;
			for(int i=0;i<lastNum;i++){
				RoleSubjectVo rvo = new RoleSubjectVo();
				rvo.setKind(ConstProp.DIGIT_TWO);
				rvo.setMajor_group(ConstProp.DIGIT_ONE);
				results.add(rvo);
			}
		}else if(insRoleNum==num){
			results.addAll(insurceRoleList);
		}else if(num == 0){
			results.addAll(insurceRoleList);
		}else{
			for(int i=0;i<num;i++){
				results.add(insurceRoleList.get(i));
			}
		}

		return results;
	}

	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/tyx/policy/policy/{order_id}")
	@RequestMapping("/policy/{order_id}")
	public ModelAndView enterInfo(HttpServletRequest request, @PathVariable Long order_id) {
		ModelAndView view = new ModelAndView();
		orderAllot(order_id, 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(IdWorker.getId()));
		view.addObject("sigId", String.valueOf(IdWorker.getId()));//普通的页面标识
		view.addObject(ConstProp.PD,pd);
		view.addObject(ConstProp.DTO,dto);
		view.addObject("comTypeList", IdType.comList());
		view.addObject("personTypeList", IdType.personList());
		view.addObject("natureList", NatureLinkage.getListByProvince(""));
		view.addObject("idOptionList", SysDictUtils.getDictList("idOption"));
		view.addObject("businessAreaList", SysDictUtils.getDictList("businessArea"));
		if(StringUtils.isNotEmpty(pd.getProduct_code())){
			if(ConstProp.TYX.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/tyx/policy/gmr_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, 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(ConstProp.DTO,dto);
			view.addObject("comTypeList", IdType.comList());
			view.addObject("personTypeList", IdType.personList());
			view.addObject("natureList", NatureLinkage.getListByProvince(""));
			view.addObject("idOptionList", SysDictUtils.getDictList("idOption"));
			view.addObject("businessAreaList", SysDictUtils.getDictList("businessArea"));
			view.addObject(ConstProp.DTO,dto);
			if(StringUtils.isEmpty(dto.getProduct_code()) || !ConstProp.TYX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
				return;
			}
			GMRPolicyVo vo = policyService.accordingToOrderIDToGetGMRPolicyVo(order_id);
			view.addObject(ConstProp.VO,vo);
			view.setViewName("/coninsweb/insurance/tyx/policy/gmr_enterBasicInfo");
			if(vo == null){
				return;
			}
			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).getReg_city())){
					view.addObject(ConstProp.AREALIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getRoleSubjectList().get(0).getReg_city()));
				}
				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(vo.getSpecialExhibitionVo() != null){
				if(StringUtils.isNotEmpty(vo.getSpecialExhibitionVo().getEx_province())){
					view.addObject("exCityList", RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getSpecialExhibitionVo().getEx_province()));
				}
				if(StringUtils.isNotEmpty(vo.getSpecialExhibitionVo().getEx_city())){
					view.addObject("exAreaList", RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getSpecialExhibitionVo().getEx_city()));
				}
			}
			if(vo.getMailPolicyVo() != null){
				if(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/tyx/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);
		if(StringUtils.isEmpty(dto.getProduct_code()) ? false : ConstProp.TYX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
			view.setViewName("/coninsweb/insurance/tyx/policy/policyConfirm");
			GMRPolicyVo vo = policyService.accordingToOrderIDToGetGMRPolicyVo(order_id);
			List<NatureLinkage> natureList = NatureLinkage.doList();
			List<IdType> typeList = IdType.doList();
			view.addObject(ConstProp.VO,vo);
			view.addObject("typeList",typeList);
			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()));
			if(vo.getSpecialExhibitionVo() != null){
				view.addObject("ex_pca", RegionUtils.getRegionNameByALLCode(vo.getSpecialExhibitionVo().getEx_province(),vo.getSpecialExhibitionVo().getEx_city(),vo.getSpecialExhibitionVo().getEx_county()));
			}
		}
		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("/pendingGMRPolicyVoPolicy")
	@ResponseBody
	public ResultDto pendingGMRPolicyVoPolicy(GMRPolicyVo vo, HttpServletRequest request, HttpServletResponse response) throws Exception{
		String recommendCode = request.getParameter(ConstProp.RECOMMENDCODE);
		return policyService.pendingGMRPolicyVoPolicy(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/tyx/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())&&productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_ONE){
				AdviceNoteVo anVo = policyService.accordingToOrderIDToGetAdviceNoteVo(order_id);
				view.setViewName("/coninsweb/insurance/tyx/transaction/paymentNotice");
				view.addObject(ConstProp.ANVO, anVo);
				view.addObject(ConstProp.NOWTIME,new Date());
				return view;
			}
			if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_DSH)){
				//待核保
				view.setViewName("/coninsweb/insurance/tyx/transaction/waitOffer");
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_YCB)){
				//核保通过
				view.setViewName("/coninsweb/insurance/tyx/transaction/passUnderwriting");
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_YJB)){
				//拒保
				view.setViewName("/coninsweb/insurance/tyx/transaction/declinature");
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_DZF)){
				//待支付
				if(productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_ONE){
					//跳转泰康支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment");
				}else if(productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_TWO){
					//跳转平安支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment_PA");
				}else if(productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_FOUR){
					//跳转平安支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment_RB");
				}else if(productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_FIVE){
					//跳转平安财支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment_PAC");
					TYX_PAC_Payment(order_id, view, vo);
				}else if(productService.api_request_sign(vo.getProduct_code()) == ConstProp.INT_NUMBER_SIX){
					//跳转长安支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment_CA");
					TYX_CA_Payment(order_id, view, vo);
				}else if(productService.api_request_sign(vo.getProduct_code()) == 7){
					//跳转前海支付页面
					view.setViewName("/coninsweb/insurance/tyx/transaction/policyPayment_QH");
					view.addObject("payurl",vo.getShow_url());
				}else if(productService.api_request_sign(vo.getProduct_code()) == 8){
                    view = new ModelAndView("/coninsweb/insurance/tyx/transaction/policyPayment_HT");
                    TYX_HT_Payment(order_id, view, vo);
                }else{
					//失败界面
				}
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_DCB)){
				//待承保
				view.setViewName("/coninsweb/insurance/tyx/transaction/finishPay");
			}else if(vo.getPolicy_status().equals(DictConst.ORDER_STATUS_YSH)){
				AdviceNoteVo anVo = null;
				if(vo.getProduct_code().contains(ConstProp.TYX_PAC)){
					view.setViewName("/coninsweb/insurance/tyx/transaction/paymentNoticePAC");
					anVo = policyService.accordingToOrderIDToGetAdviceNoteVo(order_id);
				}else if(vo.getProduct_code().contains(ConstProp.TYX_CA)){
					view.setViewName("/coninsweb/insurance/tyx/transaction/paymentNoticeCA");
				}
				view.addObject(ConstProp.ANVO, anVo);
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		view.addObject(ConstProp.NOWTIME,new Date());
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b> 平安财团意险支付页面参数信息 </b>
	 * @author ZXF
	 * @create 2020/09/29 0029 17:29
	 * @version
	 * @注意事项 </b>
	 */
	private void TYX_PAC_Payment(@PathVariable long order_id, ModelAndView view, OrderFormVo vo) throws Exception {
		if(StringUtils.isNotEmpty(vo.getShow_url())){
            view.addObject("payurl",vo.getShow_url());
        }else{
            String result = pACRequestService.requestPAC(Long.parseLong(vo.getOid()), ConstProp.DIGIT_FIVE,null);
            String[] strs = result.split(ConstProp.POUND_SIGN);
            if(ConstProp.CODE_SUCCESS.equals(strs[0])){
                policyService.payUrlChangePAC(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 TYX_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 = tYX_CARequestService.request_ca_tyx(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,strs[1],strs[2]);
				view.addObject("payurl",strs[2]);
			}
		}
	}

    /**
     * <b> 华泰支付页面信息 </b>
     * @author ZXF
     * @create 2020/09/28 0028 10:05
     * @version
     * @注意事项 </b>
     */
    private void TYX_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 = tYX_HTRequestService.request_ht_tyx(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, com.bcxin.mybatisplus.toolkit.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(productService.api_request_sign(vo.getProduct_code()) == 2){
			policyService.HTTP_PAS_TYX_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);
	}

	@RequestMapping("/deleteRoleInPolicyByOid")
	@ResponseBody
	public ResultDto deleteRoleInPolicyByOid(HttpServletRequest request) {
		String role_id = request.getParameter("role_id");
		if(StringUtils.isEmpty(role_id)){
			return new ResultDto("数据丢失，删除失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(policyService.deleteRoleInPolicyByOid(role_id)){
			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);
		}
	}

	@RequestMapping("/delectAllInsRole")
	@ResponseBody
	public ResultDto delectAllInsRole(HttpServletRequest request) {
		String order_id = request.getParameter("order_id");
		if(StringUtils.isEmpty(order_id)){
			return new ResultDto("数据丢失，请刷新后重试！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(policyService.delectAllInsRole(order_id)){
			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);
		}
	}


	/**
	 * excel人员导入处理
	 * @param mFile MultipartFile上传文件
	 * @return
	 * @throws Exception
	 */
	private ResultDto uploadRoleFile(MultipartFile mFile) throws Exception {
		List<RoleSubjectVo> list = null;
		String[] arrStr = {"name_cn","id_type","organization_code","birth_date","sex","mobile","major_group"};
		// Read the Sheet
		list = Lists.newArrayList();
		String msg = "";
		int cum = 0;
		String cds = "";
		try {
			InputStream is = mFile.getInputStream();
			HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
			for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
				HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
				if (hssfSheet == null) {
					continue;
				}
				RoleSubjectVo rsVo = null;
				// Read the Row
				for (int rowNum = 6; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
					HSSFRow hssfRow = hssfSheet.getRow(rowNum);
					//excel的行号
					int hh = rowNum+1;

					if (hssfRow == null) {
						continue;
					}
					//整条记录为空就跳过
					if(StringUtils.isEmpty(String.valueOf(hssfRow.getCell(1)).trim())&&
							StringUtils.isEmpty(String.valueOf(hssfRow.getCell(2)).trim())&&
							StringUtils.isEmpty(String.valueOf(hssfRow.getCell(3)).trim())&&
							StringUtils.isEmpty(String.valueOf(hssfRow.getCell(6)).trim())&&
							StringUtils.isEmpty(String.valueOf(hssfRow.getCell(7)).trim())&&
							StringUtils.isEmpty(String.valueOf(hssfRow.getCell(8)).trim())){
						break;
					}
					HSSFCell cell = null;
					rsVo = new RoleSubjectVo();
					Map<String,String> map = Maps.newHashMap();
					String cd = "";
					for(int i=1;i<8;i++){
						cell = hssfRow.getCell(i);
						String _value = getValue(cell).trim();
						if(StringUtils.isEmpty(_value)){
							String n = i==1?"姓名"
									:i==2?"证件类型"
									:i==3?"证件号"
									:i==4?"出生日期"
									:i==5?"性别"
									:i==6?"手机"
									:"职业";
							msg = msg+ "第 "+hh+" 行："+n+"不能为空;";
							cum = 1;
							continue;
						}
						if("name_cn".equals(arrStr[i-1])){
							if(StringUtils.isNotEmpty(_value)){
								_value = _value.replace(" ","");
							}
						}else if("id_type".equals(arrStr[i-1])){
							if("居民身份证".equals(_value)){
								_value = "0";
							}else if("护照".equals(_value)){
								_value = "3";
							}else if("台胞证".equals(_value)){
								_value = "4";
							}else if("回乡证".equals(_value)){
								_value = "5";
							}
						}else if("sex".equals(arrStr[i-1])){
							if("男".equals(_value)){
								_value = "1";
							}else if("女".equals(_value)){
								_value = "2";
							}
						}else if("birth_date".equals(arrStr[i-1])){
							try {
								if(_value.contains(ConstProp.MINUS)){
									DateUtil.parseDate(_value);
								}else{
									if(HSSFDateUtil.isCellDateFormatted(cell)){
										Date d = cell.getDateCellValue();
										DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
										_value = formater.format(d);
									}
								}
							}catch (Exception e){
								msg = msg+ "第 "+hh+" 行：出生日期有误;";
								cum = 1;
								break;
							}
							if(IdNumberValidator.getAgeFromBirthday(_value)>65||IdNumberValidator.getAgeFromBirthday(_value)<16){
								msg = msg+ "第 "+hh+" 行：人员的年龄超出限制（区间：16-65周岁）;";
								cum = 1;
								break;
							}
						}else if("organization_code".equals(arrStr[i-1])){
							_value = _value.toUpperCase();
							if(!IdCardVerify.isValidatedAllIdcard(_value)){
								msg = msg+ "第 "+hh+" 行：证件号码不是有效证件，请联系客服;";
								cum = 1;
								break;
							}
							cd = _value;
						}else if("mobile".equals(arrStr[i-1])){
							if(_value.contains("E")){
								try {
									DecimalFormat df = new DecimalFormat(ConstProp.POUND_SIGN);
									_value = df.format(cell.getNumericCellValue());
								}catch (Exception e){
									msg = msg+ "第 "+hh+" 行：手机号码格式有误;";
									cum = 1;
									break;
								}
							}
							if(!ValidatorUtil.validatePhone(_value)){
								msg = msg+ "第 "+hh+" 行：手机号码格式有误;";
								cum = 1;
								break;
							}
						}else if("major_group".equals(arrStr[i-1])){
							_value = _value.replace(".0","");
							if(!"1234".contains(_value)){
								msg = msg+ "第 "+hh+" 行：职业编码无效;";
								cum = 1;
								break;
							}
						}
						map.put(arrStr[i-1],_value);
					}
					if(StringUtils.isNotEmpty(cd)&&cds.contains(cd)){
						msg = msg+ "第 "+hh+" 行：该证件号已在本清单中，请勿重复录入;";
						cum = 1;
					}
					cds = cds + cd + ConstProp.SEMICOLON;
					if(rsVo != null&&map.size()>0){
						MyConverUtil.map2PO(map, rsVo);
						list.add(rsVo);
						rsVo = null;
					}
				}
			}
			if(cum == 1){
				return new ResultDto(msg, ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			if(list!=null && !list.isEmpty()){
				if(list.size()>2001||list.size()<3){
					return new ResultDto("请控制导入人数在3~2001人以内！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
				}
				if(setValueSession(list)){
					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);
				}
			}else{
				return new ResultDto("未解析到可用数据！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		} catch (Exception e){
			return new ResultDto("Excel清单模板文件数据解析失败，请使用标准的Excel清单模板上传！\n" +
					"可能原因：\n1.模板文件头部内容被删除或整体样式被改变；\n2.直接它处复制的人员信息附带格式。", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	private static String getValue(HSSFCell hssfRow) {
		if (hssfRow.getCellType() == hssfRow.CELL_TYPE_BOOLEAN) {
			return String.valueOf(hssfRow.getBooleanCellValue());
		} else if (hssfRow.getCellType() == hssfRow.CELL_TYPE_NUMERIC) {
			return String.valueOf(hssfRow.getNumericCellValue());
		} else {
			String value = "";
			try {
				value = String.valueOf(hssfRow.getStringCellValue());
			}catch (Exception e){

			}
			return value;
		}
	}

	/**
	 * excel文件上传并解析,批量导入人员，增员的导入功能
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/gzxUploadRoleFile")
	@ResponseBody
	public ResultDto uploadRoleFile(MultipartHttpServletRequest request) throws Exception {
		MultipartFile roleFile = request.getFile("role_emp");
		if(roleFile != null){
			return uploadRoleFile(roleFile);
		}else{
			return new ResultDto("文件上传失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}

	}

	/**
	 * 人员导入加载到投保页面
	 * @return
	 */
	@RequestMapping("/role_upload_list")
	public ModelAndView role_upload_list(){
		ModelAndView view = new ModelAndView("/coninsweb/insurance/tyx/policy/role_upload_list");
		view.addObject("rsVoList",getValueSession());
		view.addObject("personTypeList", IdType.personList());
		view.addObject("productCode", getRequest().getParameter("productCode"));
		setTokenByApi(view);
		return view;
	}

	private boolean setValueSession(List<RoleSubjectVo> list) {
		JedisUtils.setObject(ConstProp.TB_RS_LIST + getToken(),list,3 * 60);
		return true;
//		HttpServletRequest request = null;
//		if (RequestContextHolder.getRequestAttributes() != null) {
//			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//			HttpSession session = request.getSession();
//			session.setMaxInactiveInterval(60*30);
//			session.setAttribute("rsVoList",list);
//			return true;
//		}else{
//			return false;
//		}
	}

	private List<RoleSubjectVo> getValueSession() {
		List<RoleSubjectVo> list = (List<RoleSubjectVo>)JedisUtils.getObject(ConstProp.TB_RS_LIST + getToken());
		JedisUtils.delObject(ConstProp.TB_RS_LIST + getToken());
//		HttpServletRequest request = null;
//		List<RoleSubjectVo> list = null;
//		if (RequestContextHolder.getRequestAttributes() != null) {
//			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//			HttpSession session = request.getSession();
//			list = (List<RoleSubjectVo>)session.getAttribute("rsVoList");
//			session.removeAttribute("rsVoList");
//		}
		return list;
	}

}
