package com.bcxin.ins.coninsweb.order.stragegy.order.impl;

import com.bcxin.ins.third.build.taibao.TransType;
import com.bcxin.ins.third.gyx.taibao.GYX_TBRequestService;
import com.bcxin.ins.third.gzx.pingancai.GZX_PACRequestService;
import com.bcxin.ins.third.gzzrx.renbao.GZZRX_RBRequestService;
import com.bcxin.ins.third.tyx.pingan.PARequestService;
import com.bcxin.ins.third.tyx.renbao.RBRequestService;
import com.bcxin.ins.third.tyx.taikang.TKRequestService;
import com.bcxin.ins.third.zzx.pingancai.ZZX_PACRequestService;
import com.bcxin.ins.third.zzx.yongan.ZZX_YARequestService;
import com.bcxin.ins.third.zzx.zhongan.ZARequestService;
import com.bcxin.ins.third.xyx.taibao.XYX_TBRequestService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.coninsweb.order.stragegy.order.OrderSupplyStrategy;
import com.bcxin.ins.coninsweb.order.stragegy.order.OrderSupplyType;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * 订单核保策略
 * @author zxf
 * @date 2018/08/30
 * @说明 策略方案提议及案例提供人：hzp 2018/06/12
 */
@Component
@OrderSupplyType(type = OrderSupplyType.OrderSupplyTypeEnum.UNDERWRITING_REQUEST)
public class StragegyUnderwritingRequest implements OrderSupplyStrategy {

    @Autowired
    private PolicyService policyService;

    @Autowired
    private ProductService productService;

    @Autowired
    private TKRequestService tKRequestService;
    @Autowired
    private PARequestService pARequestService;
    @Autowired
    private RBRequestService rBRequestService;
    @Autowired
    private XYX_TBRequestService xYX_TBRequestService;
    @Autowired
    private GZX_PACRequestService gZX_PACRequestService;
    @Autowired
    private GZZRX_RBRequestService gZZRX_RBRequestService;
    @Autowired
    private ZARequestService zARequestService;
    @Autowired
    private ZZX_PACRequestService zZX_PACRequestService;
    @Autowired
    private ZZX_YARequestService zZX_YARequestService;
    @Autowired
    private GYX_TBRequestService gYX_TBRequestService;

    @Override
    public ModelAndView policyInitService(HttpServletRequest request, Long product_id) {
        return null;
    }

    @Override
    public ModelAndView getPolicyService(Long order_id, int page) {
        return null;
    }

    @Override
    public ResultDto pendingPolicyService(Object object, HttpServletRequest request) {
        return null;
    }

    @Override
    public ModelAndView confirmPolicyService(Long order_id) {
        return null;
    }

    @Override
    public ModelAndView paymentRequestService(Long order_id) {
        return null;
    }

    @Override
    public ResultDto underwritingRequestService(HttpServletRequest request) {
        String oid = request.getParameter("policyId");
        OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
        if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.XYX_DQCK)){
            //企业短期暂时没有对接，无核保业务
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.XYX_XWCK)){
            return xyxUnderwriting(dto);
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.BZX_SSBQ)){
            //诉讼暂时没有对接，无核保业务
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.GZX)){
            return gzxUnderwriting(dto);
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.TYX)){
            return tyxUnderwriting(dto);
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.GZZRX)){
            return gzzrxUnderwriting(dto);
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.ZZX)){
            //判断is_phone值是否存在，1（手机请求），0（pc请求）
            int i = StringUtils.isNotEmpty(request.getParameter("is_phone")) ? 1 : 0;
            return zzxUnderwriting(dto,i);
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.GCTB)){
            //暂时业务不符合
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.GCLY)){
            //暂时业务不符合
        }else if(StringUtils.isEmpty(dto.getProduct_code()) ? false : dto.getProduct_code().contains(ConstProp.GYX)){
            return gyxUnderwriting(dto);
        }
        return null;
    }

    @Override
    public ResultDto insuranceCalculationService(HttpServletRequest request) {
        return null;
    }

    @Override
    public ResultDto getElectronicInsuranceService(Long order_id) {
        return null;
    }

    private ResultDto tyxUnderwriting(OrderFormVo dto){
        String result;
        String[] strs;
        try {
            if(productService.api_request_sign(dto.getProduct_code()) == 1){
                result = tKRequestService.requestTK(Long.parseLong(dto.getOid()),"01");
                strs = result.split(ConstProp.POUND_SIGN);
            }else if(productService.api_request_sign(dto.getProduct_code()) == 2){
                result = pARequestService.requestPA(Long.parseLong(dto.getOid()),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(dto.getOid()),ConstProp.DIGIT_ONE,null);
                strs = result.split(ConstProp.POUND_SIGN);
            }else{
                return new ResultDto("产品未匹配到对应接口！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }catch (Exception e) {
            return new ResultDto("核保接口异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                if(productService.api_request_sign(dto.getProduct_code()) == 4) {//如果是人保的返回报文处理
                    String payNo = strs[2].split(",")[0].split("：")[1];
                    String payPath = strs[2].split(",")[1].split("：")[1];
                    PolicyTransactionVo pvo= new PolicyTransactionVo();
                    pvo.setPolicy_id(dto.getOid());
                    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(ConstProp.DIGIT_ZERO);
                    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{
                    //TODO 泰康/平安核保后，获取投保单号设置到数据库
                    PolicyTransactionVo pvo= new PolicyTransactionVo();
                    pvo.setPolicy_id(dto.getOid());
                    pvo.setPolicy_serial_number(strs[1]);//设置投保单号
                    policyService.saveTransaction(pvo);
                }
                return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }else{
                return new ResultDto("（APP-TYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
    private ResultDto gzxUnderwriting(OrderFormVo dto){
        String result = ConstProp.BLANK_CHAR;
        if(productService.api_request_sign(dto.getProduct_code()) == 2){//平安财
            try {
                result = gZX_PACRequestService.requestPAC(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE,null);
            } catch (Exception e) {
                return new ResultDto("（APP-GZX-010）接口请求异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }
        String[] strs = result.split(ConstProp.POUND_SIGN);
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                //TODO 平安财公责险核保后，获取投保单号设置到数据库
                PolicyTransactionVo pvo= new PolicyTransactionVo();
                pvo.setPolicy_id(dto.getOid());
                pvo.setPolicy_serial_number(strs[1]);//设置投保单号
                if(strs.length == 5){
                    if(StringUtils.isNotEmpty(strs[2])){
                        pvo.setNotice_no(strs[2]);//通知单号
                    }
                    if(StringUtils.isNotEmpty(strs[4])){
                        pvo.setPay_amount(new BigDecimal(strs[4]));//保额
                    }
                    if(StringUtils.isNotEmpty(strs[3])){
                        pvo.setOut_of_pocket(new BigDecimal(strs[3]));//保费
                    }
                }
                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("（APP-GZX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
    private ResultDto gzzrxUnderwriting(OrderFormVo dto){
        String result = ConstProp.BLANK_CHAR;
        if(dto.getProduct_code().contains(ConstProp.GZZRX_RB)){//平安财
            try {
                result = gZZRX_RBRequestService.request_rb_gzzrx(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE,null);
            } catch (Exception e) {
                return new ResultDto("（APP-GZZRX-010）接口请求异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }
        String[] strs = result.split(ConstProp.POUND_SIGN);
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                String payNo = strs[2].split(",")[0].split("：")[1];
                String payPath = strs[2].split(",")[1].split("：")[1];
                PolicyTransactionVo pvo= new PolicyTransactionVo();
                pvo.setPolicy_id(dto.getOid());
                pvo.setPolicy_serial_number(strs[1]);//设置投保单号
                pvo.setDeal_url(payPath);
                pvo.setPayment_method(ConstProp.DIGIT_ONE);
                pvo.setPay_type(ConstProp.DIGIT_TWO);//支付方式
                pvo.setPay_amount(new BigDecimal(dto.getGross_premium()));
                pvo.setTransaction_status(ConstProp.DIGIT_ZERO);
                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);
                return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }else{
                return new ResultDto("（APP-GZZRX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
    private ResultDto zzxUnderwriting(OrderFormVo dto,int is_phone){
        String result = ConstProp.BLANK_CHAR;
        try {
            if(productService.api_request_sign(dto.getProduct_code()) == 1){//众安
                result = zARequestService.requestZA(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE,null);
            }else if(productService.api_request_sign(dto.getProduct_code()) == 2){//平安财
                result = zZX_PACRequestService.requestPAC(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE,null);
            }else if(productService.api_request_sign(dto.getProduct_code()) == 3){//永安
                result = zZX_YARequestService.requestYA(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE,null,is_phone);
            }
        } catch (Exception e) {
            return new ResultDto("（APP-ZZX-010）接口请求异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        String[] strs = result.split(ConstProp.POUND_SIGN);
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                //TODO 众安核保后，获取投保单号设置到数据库
                PolicyTransactionVo pvo= new PolicyTransactionVo();
                pvo.setPolicy_id(dto.getOid());
                pvo.setPolicy_serial_number(strs[1]);//设置投保单号
                pvo.setPayment_method(ConstProp.DIGIT_ONE);
                pvo.setPay_amount(new BigDecimal(dto.getGross_premium()));
                pvo.setTransaction_status(ConstProp.DIGIT_ZERO);
                pvo.setPath_sign(ConstProp.DIGIT_ONE);
                pvo.setUser_id(Long.parseLong(dto.getUser_oid()));
                if(productService.api_request_sign(dto.getProduct_code()) == 3) {//永安
                    if(strs.length == 4){
                        if(StringUtils.isNotEmpty(strs[2])){
                            pvo.setNotice_no(strs[2]);//通知单号
                        }
                        if(StringUtils.isNotEmpty(strs[3])){
                            pvo.setDeal_url(strs[3]);//支付地址
                        }
                    }
                }else{
                    if(strs.length == 5){
                        if(StringUtils.isNotEmpty(strs[2])){
                            pvo.setNotice_no(strs[2]);//通知单号
                        }
                        if(StringUtils.isNotEmpty(strs[4])){
                            pvo.setPay_amount(new BigDecimal(strs[4]));//保额
                        }
                        if(StringUtils.isNotEmpty(strs[3])){
                            pvo.setOut_of_pocket(new BigDecimal(strs[3]));//保费
                        }
                    }
                }
                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("（APP-ZZX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
    private ResultDto xyxUnderwriting(OrderFormVo dto){
        String result = ConstProp.BLANK_CHAR;
        try {
            result = xYX_TBRequestService.requestTB(Long.parseLong(dto.getOid()), TransType.EPIC_INS_XW.getValue(),null);
        } catch (Exception e) {
            return new ResultDto("（APP-XYX-010）接口请求异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        if(StringUtils.isEmpty(result)){
            return new ResultDto("（APP-XYX-008）接口请求失败！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        String[] strs = result.split(ConstProp.POUND_SIGN);
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                //TODO 太保信用险核保后，获取投保单号设置到数据库
                PolicyTransactionVo pvo= new PolicyTransactionVo();
                pvo.setPolicy_id(dto.getOid());
                pvo.setPolicy_serial_number(strs[1]);//设置投保单号
                pvo.setTrade_serial_number(IdWorker.getId() + "");
                pvo.setPayment_method(ConstProp.DIGIT_ONE);
                pvo.setPay_type(ConstProp.DIGIT_SIX);
                pvo.setOut_of_pocket(BigDecimal.ZERO);
                pvo.setPay_amount(BigDecimal.ZERO);
                pvo.setPath_sign(ConstProp.DIGIT_ONE);
                pvo.setTransaction_status(ConstProp.DIGIT_TWO);
                pvo.setUser_id(Long.parseLong(dto.getUser_oid()));
                policyService.saveTransaction(pvo);
                return new ResultDto("", ConstProp.CODE_SUCCESS, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }else{
                return new ResultDto("（APP-XYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
    private ResultDto gyxUnderwriting(OrderFormVo dto){
        String result =ConstProp.BLANK_CHAR;
        if(ConstProp.GYX.equals(dto.getProduct_code().split(ConstProp.MINUS)[0])){
            try {
                result = gYX_TBRequestService.requestTB(Long.parseLong(dto.getOid()),ConstProp.DIGIT_ONE, ConstProp.BLANK_CHAR);
            } catch (Exception e) {
                return new ResultDto("（APP-GYX-010）接口请求异常："+e.getMessage(), ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto("（APP-GYX-008）产品未匹配到对应接口！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        String[] strs = result.split(ConstProp.POUND_SIGN);
        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
            if(StringUtils.isNotEmpty(strs[1])){
                PolicyTransactionVo pvo= new PolicyTransactionVo();
                pvo.setPolicy_id(dto.getOid());
                //设置投保单号
                pvo.setPolicy_serial_number(strs[1]);
                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("（APP-GYX-009）数据丢失！", ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto(strs[1], ConstProp.CODE_FAILURE, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }
}
