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

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.entity.MySysInsCompany;
import com.bcxin.ins.core.service.MySysInsCompanyService;
import com.bcxin.ins.entity.policy_special.SpecialPublicDuty;
import com.bcxin.ins.entity.product_core.ProPrimary;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.order.ComRegionAPIService;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.order.SpecialPublicDutyAPIService;
import com.bcxin.ins.service.product.InsProductAPIService;
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.huatai.util.Policy_ActivityQuota;
import com.bcxin.ins.third.gzx.huatai.util.PremiumCalc;
import com.bcxin.ins.util.Constant;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.RegionUtils;
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.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.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 负责前台公责险投保流程的业务逻辑处理
 *
 * @author zxf
 */
@Controller
@SessionAttributes({"product", "sysInsCompany", "policyExtra"})
@RequestMapping("/insurance/afr/policy")
public class AFRPolicyController extends BaseController {

    @Autowired
    private PolicyService policyService;

    private InsInsuranceSlipAPIService insuranceSlipService;
    @Autowired
    private ComRegionAPIService regionService;
    @Autowired
    private ProductService productService;
    @Autowired
    private InsProductAPIService insProductAPIService;
    @Autowired
    private SpecialPublicDutyAPIService specialPublicDutyAPIService;
    @Autowired
    private MySysInsCompanyService mySysInsCompanyService;

    /**
     * 初始化 投保页面
     *
     * @param request
     * @param product_id
     * @param model
     * @return
     */
    @LoginRequired(methodParamKey={"1#product_id"}, redirectUrl = "insurance/afr/policy/policyInit/{product_id}")
    @RequestMapping("/policyInit/{product_id}")
    public ModelAndView policyInit(@PathVariable Long product_id) {
        ModelAndView view = new ModelAndView("/coninsweb/insurance/afr/policy/afr_enter_basic_info");
        ClientUserVo userdetail = UserSupportUtil.getSessionUser();
        view.addObject(ConstProp.RECOMMEND_CODE,UserSupportUtil.getRecommendCode());
        ProductVo pd = productService.getProduct(product_id);
        ProPrimary product = insProductAPIService.getProduct(product_id);
        MySysInsCompany sysInsCompany = mySysInsCompanyService.selectById(product.getSupplier().getSys_ins_company_id());
        SpecialPublicDutyVo vo = new SpecialPublicDutyVo();
        /*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(), "");
                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("pd", pd);
        view.addObject("product", product);
        view.addObject("sysInsCompany", sysInsCompany);
        view.addObject(ConstProp.PROVINCELIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR));
        setTokenByApi(view);
        return view;
    }


    /**
     * 修改投保信息
     * @param order_id
     * @return
     */
    @LoginRequired(methodParamKey={"1#order_id"}, redirectUrl = "insurance/afr/policy/policyUpdInit/{order_id}")
    @RequestMapping("/policyUpdInit/{order_id}")
    public ModelAndView policyUpdInit(@PathVariable Long order_id) {
        ClientUserVo userdetail = UserSupportUtil.getSessionUser();
        ModelAndView view = new ModelAndView("/coninsweb/insurance/afr/policy/afr_enter_basic_info");
        OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
        ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
        ProPrimary product = insProductAPIService.getProduct(Long.parseLong(dto.getProduct_oid()));
        MySysInsCompany sysInsCompany = mySysInsCompanyService.selectById(product.getSupplier().getSys_ins_company_id());
        view.addObject("product", product);
        view.addObject("sysInsCompany", sysInsCompany);
        view.addObject("pd", pd);
        view.addObject(ConstProp.DTO, dto);
        if (StringUtils.isEmpty(dto.getProduct_code()) ? false : ConstProp.GZX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])) {
            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.addObject(ConstProp.PROVINCELIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR));
            if(vo.getRoleSubjectList() != null){
                view.addObject(ConstProp.CITYLIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getRoleSubjectList().get(0).getReg_province()));
                view.addObject(ConstProp.AREALIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getRoleSubjectList().get(0).getReg_city()));
                //被保险人地址
                view.addObject(ConstProp.REG_CITY_1_LIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_TWO, vo.getRoleSubjectList().get(1).getReg_province()));
                view.addObject(ConstProp.REG_AREA_1_LIST, RegionUtils.findDistrictByParentCode(ConstProp.DIGIT_THREE, vo.getRoleSubjectList().get(1).getReg_city()));
            }
        }
        setTokenByApi(view);
        return view;
    }

    /**
     * 通过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;
    }

    @RequestMapping("/premiumCalc")
    @ResponseBody
    public ResultDto premiumCalc(ModelMap model, HttpServletRequest request, HttpServletResponse response) {

        try {
            /** 获取用户在投保界面选择的计价参数 */
            String activityLocal = request.getParameter("activity_local");
            String guest = request.getParameter("guest");
            String danger = request.getParameter("danger");
            String activityFireFight = request.getParameter("activity_fire_fight");
            String startDate = request.getParameter("report_begin_date"); //开始时间
            String endDate = request.getParameter("report_end_date"); //结束时间
            String policyAmount = request.getParameter("insured_amount");//限额
            String activityType = request.getParameter("report_active");//活动类型
            String policyExtrapeopleNum = request.getParameter("people_num");//活动规模
            //产品类型
            ProPrimary product = (ProPrimary) model.get("product");
            SpecialPublicDuty policyExtra = new SpecialPublicDuty();
            if (StringUtils.isNotEmpty(activityType)) {
                policyExtra.setActivity_type(activityType);
            }
            if (StringUtils.isNotEmpty(policyExtrapeopleNum)) {
                policyExtra.setActivity_scale(policyExtrapeopleNum);
            }
            policyExtra.setPeople_num(policyExtrapeopleNum);
            policyExtra.setActivity_fire_fight(activityFireFight);
            policyExtra.setGuest(guest);
            policyExtra.setDanger(danger);
            policyExtra.setActivity_local(activityLocal);
            policyExtra.setAmount(policyAmount);
            if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                policyExtra.setInsure_days(DateUtil.getDistDates(DateUtil.convertStringToDate(startDate.trim()),
                        DateUtil.convertStringToDate(endDate.trim())) + "");
            }
            PremiumCalc calc = new PremiumCalc();
            model.put("policyExtra", policyExtra);
            /** 计算获取保费 */
            BigDecimal premium = calc.calc(product, policyExtra, Constant.INS_CODE_HT);
            if (premium != null) {
                return new ResultDto("" + premium, 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);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ResultDto("获取保费失败", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }

    }


    @RequestMapping("/limitAmountCalc")
    @ResponseBody
    public String limitAmountCalc(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        String limitStr = "";
        try {
            /** 获取用户在投保界面录入的规模 */

            String policyExtrapeopleNum = request.getParameter("people_num");//活动规模
            if (StringUtils.isEmpty(policyExtrapeopleNum)) {
                policyExtrapeopleNum = "1000";//为空的时候默认为 1000人
            }
            MySysInsCompany sysCompany = (MySysInsCompany) model.get("sysInsCompany");

            SpecialPublicDuty policyExtra = (SpecialPublicDuty) model.get("policyExtra");
            policyExtra.setActivity_quota(policyExtrapeopleNum);
            Policy_ActivityQuota quota = Policy_ActivityQuota.getLevel(policyExtra.getActivity_quota() == null ? ConstProp.DIGIT_ZERO : policyExtra.getActivity_quota());
            Map<String, String> map = Policy_ActivityQuota.calcLimit(quota);
            policyExtra.setMin_limit(map.get("minLimit"));
            policyExtra.setMax_limit(map.get("maxLimit"));
            limitStr = policyExtra.getMin_limit() + ConstProp.POUND_SIGN + policyExtra.getMax_limit();
//            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "500#3500";
        }


        return limitStr.toString();
    }

    /**
     * 暂存   保存的时候会先调用这个 </b>
     */
    @OperationLog(source = OperationLog.SOURCETYPE.FRONT_ORDER,title ="【请求】产品-订单投保")
    @LoginRequired
    @RequestMapping("/policy/pendingAFRPolicyVoPolicy")
    @ResponseBody
    public ResultDto pendingAFRPolicyVoPolicy(SpecialPublicDutyVo vo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ClientUserVo userdetail = UserSupportUtil.getSessionUser();
        if (StringUtils.isEmpty(vo.getOid())) {
            String orderID = "";
            if (StringUtils.isNotEmpty(vo.getProduct_id())) {
                String recommendCode = request.getParameter(ConstProp.RECOMMENDCODE);
                orderID = createOrderAndGetOrderIDByProductID(Long.parseLong(vo.getProduct_id()), Long.parseLong(userdetail.getOid()), recommendCode,"");
            }
            if (StringUtils.isNotEmpty(orderID)) {
                vo.setOid(orderID);
            } else {
                return new ResultDto("订单初始化创建失败，请刷新页面后重试！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }
        Map<String, Object> map = null;
        try {
            if(null==vo.getMailPolicyVo().getNeed_receipt()){
                //设置发票为空问题
                vo.getMailPolicyVo().setNeed_receipt("0");
            }
            if(null==vo.getMailPolicyVo().getNeed_insur_bill()){
                vo.getMailPolicyVo().setNeed_insur_bill("1");
            }
            if(StringUtils.isNotEmpty(vo.getInsured_amount())){
                vo.setInsured_amount(String.valueOf((new BigDecimal(vo.getInsured_amount())).multiply(new BigDecimal("10000"))));
            }
            map = policyService.obtainSpecialPublicDutyVoSetUp(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (map != null) {
            return new ResultDto("当前填写内容已经暂存，稍后您可在【我的账户-我的订单-投保中】 继续完成填写内容。", ConstProp.CODE_SUCCESS, String.valueOf(map.get(ConstProp.ORDER_ID)), "", "");
        } else {
            return new ResultDto("数据丢失，请刷新页面后重试！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }


    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/afr/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 orderAllot(Long order_id, ModelAndView view) {
        try {
            OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
            ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
            view.addObject("pd", pd);
            view.addObject(ConstProp.DTO, dto);
            if (StringUtils.isEmpty(dto.getProduct_code()) ? false : ConstProp.GZX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])) {
                SpecialPublicDutyVo vo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(order_id);
                view.addObject(ConstProp.VO, vo);
                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()));
                view.setViewName("/coninsweb/insurance/afr/policy/afr_policy_confirm");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * <b>修改订单状态 (跳转支付前的页面)</b>
     * <b>
     */
    @LoginRequired
    @RequestMapping("/policy/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, "", "");
        } else {
            return new ResultDto("数据丢失，请刷新页面后重试！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }

    /**
     * <b>业务逻辑处理，保存保单信息
     * 页面流转：点击保单保存，跳转支付页面
     * <b>
     */
    @LoginRequired(methodParamKey={"0#order_id"}, redirectUrl = "insurance/afr/policy/policyPayment/{order_id}")
    @RequestMapping("/policyPayment/{order_id}")
    public ModelAndView savePolicy(@PathVariable long order_id, HttpServletRequest request) {
        OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(order_id);
        ProductVo pd = productService.getProduct(Long.parseLong(vo.getProduct_oid()));
        ModelAndView view = null;
        if (vo.getPolicy_status().equals(DictConst.ORDER_STATUS_DZF)) {//待支付

            view = new ModelAndView("/coninsweb/insurance/afr/policy/afr_policy_pay");
            SpecialPublicDutyVo publicDutyVo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(order_id);
            view.addObject(ConstProp.VO, publicDutyVo);
        } else {
            return new ModelAndView(ConstProp.SLASH);

        }

        view.addObject("pd", pd);
        view.addObject(ConstProp.DTO, vo);
        view.addObject("nowTime", new Date());
        setTokenByApi(view);
        return view;
    }


    /**
     * 订单详情页面
     *
     * @param request
     * @param order_id
     * @return
     */
    @LoginRequired(methodParamKey={"1#order_id"}, redirectUrl = "insurance/afr/policy/detail/{order_id}")
    @RequestMapping("/detail/{order_id}")
    public ModelAndView policyDetail(HttpServletRequest request, @PathVariable Long order_id) {
        OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
        ModelAndView view = new ModelAndView("/coninsweb/insurance/afr/policyDetails/afr_policy_detail");
        ProductVo pd = productService.getProduct(Long.parseLong(dto.getProduct_oid()));
        SpecialPublicDutyVo vo = policyService.accordingToOrderIDToGetSpecialPublicDutyVo(order_id);
        view.addObject("reg_role", RegionUtils.getRegionNameByALLCode(vo.getRoleSubjectList().get(0).getReg_province(),vo.getRoleSubjectList().get(0).getReg_city(),vo.getRoleSubjectList().get(0).getReg_district()));
        view.addObject("reg_role_1", RegionUtils.getRegionNameByALLCode(vo.getRoleSubjectList().get(1).getReg_province(),vo.getRoleSubjectList().get(1).getReg_city(),vo.getRoleSubjectList().get(1).getReg_district()));
        view.addObject("pd", pd);
        view.addObject(ConstProp.DTO, dto);
        view.addObject(ConstProp.VO, vo);
        setTokenByApi(view);
        return view;
    }


}
