package com.hfkj.openapi.service;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.gas.newlink.NewLinkRequestService;
import com.hfkj.channel.gas.newlink2.NewLink2RequestService;
import com.hfkj.channel.gas.shell.CqShellPetroleumRequestService;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.pay.util.SignatureUtil;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.entity.*;
import com.hfkj.model.GasModel;
import com.hfkj.model.GasOilPriceModel;
import com.hfkj.openapi.model.request.RequestOrderDetailModel;
import com.hfkj.openapi.model.request.RequestOrderPushModel;
import com.hfkj.openapi.model.request.RequestOrderRefundModel;
import com.hfkj.openapi.model.response.OrderRefundNotifyModel;
import com.hfkj.openapi.model.response.ResponseOrderDetailModel;
import com.hfkj.openapi.model.response.ResponseOrderPushModel;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.agent.*;
import com.hfkj.service.gas.*;
import com.hfkj.service.merchant.BsMerchantAccountService;
import com.hfkj.service.merchant.BsMerchantChainBrandAccountService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.order.BsOrderRefundService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.sec.SecDictionaryService;
import com.hfkj.sysenum.gas.*;
import com.hfkj.sysenum.merchant.MerchantAccountRecordSourceTypeEnum;
import com.hfkj.sysenum.merchant.MerchantChainBrandSettleTypeEnum;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.merchant.MerchantStatusEnum;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import com.hfkj.sysenum.order.OrderRefundStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @className: ApiGasOrderService
 * @author: HuRui
 * @date: 2024/11/12
 **/
@Component("apiGasOrderService")
public class ApiGasOrderService {
    @Resource
    private BsAgentMerService agentMerService;
    @Resource
    private BsAgentService agentService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private BsMerchantAccountService merchantAccountService;
    @Resource
    private BsMerchantChainBrandAccountService merchantChainBrandAccountService;
    @Resource
    private BsGasService gasService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsGasClassGroupTaskService gasClassGroupTaskService;
    @Resource
    private BsDeviceService deviceService;
    @Resource
    private SecDictionaryService dictionaryService;
    @Resource
    private BsAgentApiAccountService agentApiAccountService;
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsOrderRefundService orderRefundService;
    @Resource
    private BsGasOilPriceService gasOilPriceService;
    @Resource
    private BsGasOrderAuditService gasOrderAuditService;
    @Resource
    private BsAgentPriceService agentPriceService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private final String LOCK_KEY = "AGENT_API_PUSH_ORDER_LOCK_";
    /**
     * 推送加油订单
     * @param request
     * @return
     */
    @Transactional(propagation= Propagation.NEVER)
    public ResponseOrderPushModel pushOrder(Long agentId,RequestOrderPushModel request) throws Exception {
        // 交易油站权限
        BsAgentMer agentMer = agentMerService.getDetailByAgent(agentId, request.getGasNo());
        if (agentMer == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "油站不可用");
        }
        // 查询油站
        GasModel gasDetail = gasService.getGasDetail(request.getGasNo());
        if (gasDetail == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到油站信息");
        }
        if (!gasDetail.getStatus().equals(MerchantStatusEnum.status1.getNumber())) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "油站不可用");
        }
        // 校验油品
        List<GasOilPriceModel> gasOilPriceModels = gasDetail.getGasOilPrice().stream().filter(o -> o.getOilNo().equals(request.getOilNo())).collect(Collectors.toList());
        if (gasOilPriceModels.isEmpty()) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "油品不可用");
        }
        // 油价
        GasOilPriceModel oilPrice = gasOilPriceModels.get(0);
        // 校验枪号
        if (oilPrice.getGasOilGunNo().stream().noneMatch(o -> o.getGunNo().equals(request.getGunNo()))) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "枪号不可用");
        }
        // 交易订单号
        if (gasOrderService.getDetailByOrderNo(request.getOrderNo()) != null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "订单号已存在");
        }
        // 查询代理商
        BsAgent agent = agentService.getAgentById(agentId);
        if (agent == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未知的接入方");
        }

        return createOrder(agent, gasDetail, oilPrice, request);
    }

    /**
     * 创建订单
     */
    @Transactional(propagation= Propagation.REQUIRES_NEW, rollbackFor= {RuntimeException.class})
    public ResponseOrderPushModel createOrder(BsAgent agent, BsMerchant gasDetail, GasOilPriceModel oilPrice, RequestOrderPushModel request) throws InterruptedException {
        // 锁编号
        String lockKey = LOCK_KEY+agent.getId();
        // 获取锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, "");
        if (Boolean.TRUE.equals(lock)) {
            try {
                // 锁超时时间 15秒
                redisTemplate.expire(lockKey, 15, TimeUnit.SECONDS);
                // 创建加油订单
                BsGasOrder gasOrder = new BsGasOrder();
                gasOrder.setAgentId(agent.getId());
                gasOrder.setAgentName(agent.getName());
                gasOrder.setAbnormal(false);
                gasOrder.setMerNo(gasDetail.getMerNo());
                gasOrder.setChannelType(gasDetail.getSourceType());
                gasOrder.setOrderNo(request.getOrderNo());
                gasOrder.setUserPhone(request.getUserPhone());
                gasOrder.setMerChainBrandId(gasDetail.getChainBrandId());
                gasOrder.setMerChainBrandName(gasDetail.getChainBrandName());
                gasOrder.setMerId(gasDetail.getId());
                gasOrder.setMerName(gasDetail.getMerName());
                gasOrder.setMerAddress(gasDetail.getAddress());
                gasOrder.setStatus(OrderOilStatus.STATUS2.getNumber());
                gasOrder.setReceiptStatus(GasOrderReceiptStatusEnum.status0.getStatus());

                // 油价信息
                gasOrder.setGasRefuelPrice(request.getRefuelingAmount());
                gasOrder.setGasOilNo(request.getOilNo());
                gasOrder.setGasGunNo(request.getGunNo());
                gasOrder.setGasOilType(oilPrice.getOilType());
                gasOrder.setGasPriceGun(oilPrice.getPriceGun());
                // 代理商价格
                BigDecimal priceRate = new BigDecimal("100");
                BsAgentPrice agentPrice = agentPriceService.getPrice(gasOrder.getAgentId(), gasDetail.getId(), oilPrice.getOilNo());
                if (agentPrice != null) {
                    priceRate = agentPrice.getPriceRate();
                }
                gasOrder.setGasPriceVip(oilPrice.getPriceGun().multiply(priceRate.divide(new BigDecimal("100"))).setScale(2, BigDecimal.ROUND_HALF_UP));
                gasOrder.setGasPriceCost(oilPrice.getPriceGun());
                gasOrder.setGasPriceOfficial(oilPrice.getPriceOfficial());
                gasOrder.setGasPricePlatform(gasOrder.getGasPriceVip());
                gasOrder.setGasDiscount(agentPrice!=null?agentPrice.getPriceRate().divide(new BigDecimal("100")):new BigDecimal("0"));
                gasOrder.setGasOilSubsidy(new BigDecimal("0"));
                gasOrder.setGasLitersPreferences(new BigDecimal("0"));
                gasOrder.setGasPricePreferences(new BigDecimal("0"));
                gasOrder.setCreateType(GasOrderCreateType.TYPE2.getNumber());
                gasOrder.setGasOilLiters(gasOrder.getGasRefuelPrice().divide(gasOrder.getGasPriceGun(), 2, BigDecimal.ROUND_HALF_UP));

                // 结算信息
                gasOrder.setTotalDeductionPrice(new BigDecimal("0"));
                gasOrder.setDeductionCouponPrice(new BigDecimal("0"));
                gasOrder.setDeductionOilPrice(new BigDecimal("0"));
                gasOrder.setPayablePrice(request.getRefuelingAmount());
                gasOrder.setGasRefuelPrice(request.getRefuelingAmount());
                gasOrder.setGasServiceFeeRate(new BigDecimal("0"));
                gasOrder.setGasServiceFeePrice(new BigDecimal("0"));
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                    // 油站结算 公式 1. 加油升数 * (油枪价 - 优惠价) = 优惠金额  2. 加油金额 - 优惠金额 = 扣款金额
                    BigDecimal gasSettlePrice = gasOrder.getGasRefuelPrice().subtract(
                            // 优惠金额
                            gasOrder.getGasOilLiters().multiply(oilPrice.getPriceGun().subtract(oilPrice.getPriceVip())));
                    gasOrder.setGasSettlePrice(gasSettlePrice);
                } else {
                    gasOrder.setGasSettlePrice(gasOrder.getGasRefuelPrice());
                }

                // 代理商结算
                // 代理结算金额=加油金额-（加油金额/挂牌价(升数) *（挂牌价-优惠价））
                BigDecimal agentSettlePrice = gasOrder.getGasRefuelPrice()
                        .subtract(gasOrder.getGasOilLiters()
                        .multiply((gasOrder.getGasPriceGun().subtract(gasOrder.getGasPriceVip()).setScale(2, BigDecimal.ROUND_HALF_DOWN))));
                gasOrder.setGasAgentSettlePrice(agentSettlePrice);

                // 油站是否开启班组
                BsGasClassGroupTask groupTask = gasClassGroupTaskService.getCurrentTaskByMerId(gasDetail.getId());
                if (groupTask != null) {
                    gasOrder.setGasClassGroupId(groupTask.getGasClassGroupId());
                    gasOrder.setGasClassGroupName(groupTask.getGasClassGroupName());
                    gasOrder.setGasClassGroupTaskId(groupTask.getId());
                }
                gasOrderService.addGasOrder(gasOrder);

                // 代理商扣款
                Map<String,Object> consumeParam = new HashMap<>();
                consumeParam.put("sourceType", MerchantAccountRecordSourceTypeEnum.type2.getType());
                consumeParam.put("sourceOrderNo", gasOrder.getOrderNo());
                consumeParam.put("sourceOrderContent", "加油单号："+gasOrder.getOrderNo()+",加油金额："+ gasOrder.getGasRefuelPrice());
                agentApiAccountService.consume(agent.getId(), gasOrder.getGasAgentSettlePrice(), consumeParam);

                // 处理支付后的加油业务
                oilHandle(gasOrder);
                // 加油业务是否异常
                if (gasOrder.getAbnormal().equals(true)) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, gasOrder.getAbnormalContent());
                }
                ResponseOrderPushModel response = new ResponseOrderPushModel();
                response.setOrderNo(gasOrder.getOrderNo());
                response.setChannelType(gasOrder.getChannelType());
                response.setChannelOrderNo(gasOrder.getChannelOrderNo());
                // 释放锁
                redisTemplate.delete(lockKey);
                return response;

            } catch (BaseException e) {
                // 释放锁
                redisTemplate.delete(lockKey);
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, e.getErrorMsg());
            } catch (Exception e) {
                // 释放锁
                redisTemplate.delete(lockKey);
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "创建订单失败");
            }
        } else {
            Thread.sleep(100);
            createOrder(agent,gasDetail,oilPrice,request);
        }
        throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "创建加油订单失败");
    }


    /**
     * 退款订单
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional(propagation= Propagation.REQUIRES_NEW,isolation = Isolation.SERIALIZABLE,rollbackFor= {RuntimeException.class})
    public String refundOrder(Long agentId,RequestOrderRefundModel request) {
        // 查询加油订单
        BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(request.getOrderNo());
        if (gasOrder == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到订单");
        }
        if (!Objects.equals(agentId, gasOrder.getAgentId())) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到订单");
        }
        if (!gasOrder.getStatus().equals(OrderOilStatus.STATUS2.getNumber())
            && !gasOrder.getStatus().equals(OrderOilStatus.STATUS6.getNumber())) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "订单状态暂时无法申请退款");
        }
        // 创建退款订单
        BsOrderRefund orderRefund = new BsOrderRefund();
        orderRefund.setMerId(gasOrder.getMerId());
        orderRefund.setMerNo(gasOrder.getMerNo());
        orderRefund.setOrderNo(gasOrder.getOrderNo());
        orderRefund.setUserPhone(gasOrder.getUserPhone());
        // 退款订单号 退款标识：R + 时间 + 随机3位数字
        orderRefund.setRefundOrderNo("R"+ DateUtil.date2String(new Date(), "yyMMddHHmmss") + RandomUtils.number(3, false));
        orderRefund.setRefundPayType(gasOrder.getPayType());
        // 全部退款
        orderRefund.setRefundPrice(gasOrder.getGasRefuelPrice());
        orderRefund.setRefundIntegral(0L);
        orderRefund.setRefundRemark(request.getRefundReason());
        orderRefund.setRefundStatus(OrderRefundStatusEnum.status1.getCode());
        orderRefund.setCreateType(GasOrderCreateType.TYPE2.getNumber());
        orderRefundService.editData(orderRefund);

        // 修改订单状态
        gasOrder.setStatus(OrderOilStatus.STATUS5.getNumber());
        gasOrderService.updateGasOrder(gasOrder);

        BsGasOrderAudit gasOrderAudit = new BsGasOrderAudit();
        gasOrderAudit.setAuditType(GasOrderAuditTypeEnum.type1.getCode());
        gasOrderAudit.setAuditNo(System.currentTimeMillis()+"");
        gasOrderAudit.setOrderNo(gasOrder.getOrderNo());
        gasOrderAudit.setChannelType(gasOrder.getChannelType());
        gasOrderAudit.setChannelOrderNo(gasOrder.getChannelOrderNo());
        gasOrderAudit.setAgentId(gasOrder.getAgentId());
        gasOrderAudit.setAgentName(gasOrder.getAgentName());
        gasOrderAudit.setUserPhone(gasOrder.getUserPhone());
        gasOrderAudit.setMerId(gasOrder.getMerId());
        gasOrderAudit.setMerName(gasOrder.getMerName());
        gasOrderAudit.setMerNo(gasOrder.getMerNo());
        gasOrderAudit.setGasRefuelPrice(gasOrder.getGasRefuelPrice());
        gasOrderAudit.setGasGunNo(gasOrder.getGasGunNo());
        gasOrderAudit.setGasOilNo(gasOrder.getGasOilNo());
        gasOrderAudit.setGasPayTime(gasOrder.getPayTime());
        gasOrderAudit.setRemark(request.getRefundReason());
        gasOrderAudit.setStatus(GasOrderAuditStatusEnum.type1.getCode());
        gasOrderAuditService.create(gasOrderAudit);

        return "ok";
    }

    /**
     * 退款金额
     * @param gasOrder
     * @param orderRefund
     * @return
     */
    public void refundPrice(BsGasOrder gasOrder, BsOrderRefund orderRefund) {
        // 异常订单
        if (gasOrder.getAbnormal().equals(true)) {
            try {
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type3.getNumber())) {
                    // 未出现异常
                    if (gasOrder.getAbnormal().equals(false)) {
                        // 请求重庆壳牌渠道退款
                        CqShellPetroleumRequestService.gasSyncRefund(gasOrder.getPayTime(), gasOrder.getOrderNo());
                    }
                }
                // 代理商退款退款
                agentApiAccountService.refund(gasOrder.getAgentId(),gasOrder.getGasRefuelPrice(), orderRefund);
                // 退款到油站
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                    merchantAccountService.refund(gasOrder.getMerNo(),gasOrder.getGasSettlePrice(),orderRefund);
                }
                orderRefund.setRefundStatus(OrderRefundStatusEnum.status2.getCode());
                orderRefund.setFinishTime(new Date());
                orderRefundService.editData(orderRefund);

                gasOrder.setStatus(OrderOilStatus.STATUS4.getNumber());
                gasOrder.setRefundTime(orderRefund.getFinishTime());
                gasOrderService.updateGasOrder(gasOrder);

            } catch (Exception e) {
                throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "请求退款失败");
            }
        } else {
            // 正常订单
            // 渠道退款
            if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type2.getNumber())) {
                // 团油
                try {
                    // 请求团油渠道申请退款
                    JSONObject object = NewLinkRequestService.refuelingOrderRefund(gasOrder.getUserPhone(), gasOrder.getOrderNo(), orderRefund.getRefundRemark());
                    if (object == null || !object.getString("code").equals("200")) {
                        gasOrder.setAbnormal(true);
                        gasOrder.setAbnormalContent("渠道申请退款失败！原因：" + object.getString("message"));
                        gasOrderService.updateGasOrder(gasOrder);
                    }
                } catch (Exception e) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "请求退款失败");
                }

            } else {
                // 重庆壳牌
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type3.getNumber())) {
                    try {
                        // 请求重庆壳牌渠道退款
                        CqShellPetroleumRequestService.gasSyncRefund(gasOrder.getPayTime(), gasOrder.getOrderNo());
                    } catch (Exception e) {
                        throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "请求退款失败");
                    }
                }
                try {
                    // 代理商退款退款
                    agentApiAccountService.refund(gasOrder.getAgentId(),gasOrder.getGasRefuelPrice(), orderRefund);
                    // 退款到油站
                    if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                        merchantAccountService.refund(gasOrder.getMerNo(),gasOrder.getGasSettlePrice(),orderRefund);
                    }
                    orderRefund.setRefundStatus(OrderRefundStatusEnum.status2.getCode());
                    orderRefund.setFinishTime(new Date());
                    orderRefundService.editData(orderRefund);

                    gasOrder.setStatus(OrderOilStatus.STATUS4.getNumber());
                    gasOrder.setRefundTime(orderRefund.getFinishTime());
                    gasOrderService.updateGasOrder(gasOrder);

                } catch (Exception e) {
                    throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "请求退款失败");
                }
            }
        }
    }

/*    @Transactional(propagation= Propagation.REQUIRES_NEW,isolation = Isolation.SERIALIZABLE,rollbackFor= {RuntimeException.class})
    private void newLinkNotify(BsGasOrder gasOrder,String refundFailReason) {
        BsOrderRefund orderRefund = orderRefundService.getRefundByOrderNo(gasOrder.getOrderNo());
        try {
            if (orderRefund != null) {
                orderRefund.setRefundStatus(OrderRefundStatusEnum.status2.getCode());
                orderRefund.setFinishTime(new Date());
                orderRefund.setRefundFailReason(refundFailReason);
                orderRefundService.editData(orderRefund);
            }
            // 代理商退款退款
            agentApiAccountService.refund(gasOrder.getAgentId(),gasOrder.getGasRefuelPrice(), orderRefund);
            // 退款到油站
            if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                merchantAccountService.refund(gasOrder.getMerNo(),gasOrder.getGasSettlePrice(),orderRefund);
            }
            gasOrder.setStatus(OrderOilStatus.STATUS4.getNumber());
            gasOrder.setRefundTime(new Date());
            gasOrderService.updateGasOrder(gasOrder);
        } catch (Exception e) {
            if (orderRefund != null) {
                orderRefund.set
            }
        }
    }*/

    /**
     * 查询订单详情
     * @param request
     * @return
     * @throws Exception
     */
    public ResponseOrderDetailModel queryOrderDetail(Long agentId,RequestOrderDetailModel request) {
        // 查询加油订单
        BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(request.getOrderNo());
        if (gasOrder == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到订单");
        }
        if (!Objects.equals(agentId, gasOrder.getAgentId())) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.COMMON_ERROR, "未找到订单");
        }
        ResponseOrderDetailModel response = new ResponseOrderDetailModel();
        response.setOrderNo(gasOrder.getOrderNo());
        response.setUserPhone(gasOrder.getUserPhone());
        response.setRefuelPrice(gasOrder.getGasRefuelPrice());
        response.setGasNo(gasOrder.getMerNo());
        response.setGasName(gasOrder.getMerName());
        response.setOilNo(gasOrder.getGasOilNo());
        response.setGunNo(gasOrder.getGasGunNo());
        response.setLitre(gasOrder.getGasOilLiters());
        response.setPriceOfficial(gasOrder.getGasPriceOfficial());
        response.setPriceGun(gasOrder.getGasPriceGun());
        response.setStatus(gasOrder.getStatus());
        response.setChannelType(gasOrder.getChannelType());
        response.setChannelOrderNo(gasOrder.getChannelOrderNo());
        response.setCreateTime(gasOrder.getCreateTime());
        return response;
    }

    /**
     * 油站业务
     * @param gasOrder
     */
    public BsGasOrder oilHandle(BsGasOrder gasOrder) throws Exception {
        // 查询加油订单
        if (gasOrder != null) {
            gasOrder.setActualPayPrice(gasOrder.getGasRefuelPrice());
            gasOrder.setPayType(OrderPayTypeEnum.type4.getCode());
            gasOrder.setPayTime(new Date());
            gasOrderService.updateGasOrder(gasOrder);

            if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                // 自建站
                // 打印小票
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                    deviceService.printGasOrder(gasOrder.getMerId(), gasOrder, false);
                }
                // 查询油站
                BsMerchant merchant = merchantService.getMerchant(gasOrder.getMerNo());
                if (merchant != null) {
                    // 连锁商户
                    if (merchant.getChainBrandId() != null) {
                        if (merchant.getChainBrandSettleType().equals(MerchantChainBrandSettleTypeEnum.type1.getNumber())) {
                            // 连锁额度
                            Map<String,Object> consumeMap = new HashMap<>();
                            consumeMap.put("sourceType", MerchantAccountRecordSourceTypeEnum.type2.getType());
                            consumeMap.put("sourceId", gasOrder.getId());
                            consumeMap.put("sourceOrderNo", gasOrder.getOrderNo());
                            merchantChainBrandAccountService.consume(merchant.getChainBrandId(), gasOrder.getMerNo(), gasOrder.getGasSettlePrice(), consumeMap);

                        } else if (merchant.getChainBrandSettleType().equals(MerchantChainBrandSettleTypeEnum.type2.getNumber())) {
                            // 商户额度
                            Map<String,Object> consumeMap = new HashMap<>();
                            consumeMap.put("sourceType", MerchantAccountRecordSourceTypeEnum.type2.getType());
                            consumeMap.put("sourceId", gasOrder.getId());
                            consumeMap.put("sourceOrderNo", gasOrder.getOrderNo());
                            merchantAccountService.consume(gasOrder.getMerNo(), gasOrder.getGasSettlePrice(), consumeMap);
                        }
                    } else {
                        // 商户额度
                        Map<String,Object> consumeMap = new HashMap<>();
                        consumeMap.put("sourceType", MerchantAccountRecordSourceTypeEnum.type2.getType());
                        consumeMap.put("sourceId", gasOrder.getId());
                        consumeMap.put("sourceOrderNo", gasOrder.getOrderNo());
                        merchantAccountService.consume(gasOrder.getMerNo(), gasOrder.getGasSettlePrice(), consumeMap);
                    }
                }

            } else if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type2.getNumber())) {
                try {
                    // 能链【团油】
                    Map<String, Object> param = new HashMap<>();
                    param.put("gasId", gasOrder.getMerNo());
                    param.put("oilNo", gasOrder.getGasOilNo());
                    param.put("gunNo", Integer.parseInt(gasOrder.getGasGunNo()));
                    param.put("priceGun", gasOrder.getGasPriceGun());  // 油站价
                    param.put("priceVip", gasOrder.getGasPriceCost());  // 成本价
                    param.put("driverPhone", gasOrder.getUserPhone());
                    param.put("thirdSerialNo", gasOrder.getOrderNo());
                    param.put("refuelingAmount", gasOrder.getGasRefuelPrice());
                    // 查询账户
                    SecDictionary newLinkAccount = dictionaryService.getDictionary("NEW_LINK_ACCOUNT", "" + gasOrder.getGasOilType());
                    if (newLinkAccount != null) {
                        param.put("accountNo", newLinkAccount.getCodeName());
                    }
                    JSONObject pushResult = NewLinkRequestService.refuelingOrderPush(param);
                    if (pushResult != null && pushResult.getString("code").equals("200")) {
                        gasOrder.setChannelOrderNo(pushResult.getJSONObject("result").getString("orderNo"));
                        gasOrder.setAbnormal(false);
                        gasOrder.setAbnormalContent(null);
                    } else {
                        gasOrder.setAbnormal(true);
                        gasOrder.setAbnormalContent(pushResult.getString("message"));
                    }
                } catch (Exception e) {
                    gasOrder.setAbnormal(true);
                    gasOrder.setAbnormalContent("推送订单未知异常！请稍后重新推送");
                }
                gasOrderService.updateGasOrder(gasOrder);

            } else if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type3.getNumber())) {
                try {
                    // 推送加好油【重庆壳牌】
                    CqShellPetroleumRequestService.gasSyncPayment(gasOrder.getOrderNo(),
                            gasOrder.getMerNo(),
                            gasOrder.getPayTime(),
                            gasOrder.getGasRefuelPrice(),
                            gasOrder.getGasOilNo(),
                            gasOrder.getGasGunNo(),
                            gasOrder.getPayablePrice(),
                            gasOrder.getTotalDeductionPrice()
                    );
                    gasOrder.setAbnormal(false);
                    gasOrder.setAbnormalContent(null);

                } catch (BaseException e) {
                    gasOrder.setAbnormal(true);
                    gasOrder.setAbnormalContent(e.getErrorMsg());
                }  catch (Exception e) {
                    gasOrder.setAbnormal(true);
                    gasOrder.setAbnormalContent("推送订单未知错误！请稍后重新推送");
                }
                gasOrderService.updateGasOrder(gasOrder);

            } else if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type4.getNumber())) {
                try {
                    // 油站信息
                    BsMerchant merchant = merchantService.getMerchant(gasOrder.getMerNo());
                    if (merchant == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站");
                    }
                    // 查询油价信息
                    JSONObject getPriceInfo = NewLink2RequestService.getPriceInfo(gasOrder.getMerNo(), gasOrder.getGasRefuelPrice(), gasOrder.getGasOilNo(), gasOrder.getGasGunNo());
                    if (!getPriceInfo.getString("code").equals("200")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取报价的快照失败："+getPriceInfo.getString("msg"));
                    }
                    Map<String,Object> createParam = new HashMap<>();
                    createParam.put("gasId", gasOrder.getMerNo());
                    createParam.put("fuelAmount", gasOrder.getGasRefuelPrice().toString());
                    createParam.put("oilNo", gasOrder.getGasOilNo());
                    createParam.put("gunNo", gasOrder.getGasGunNo());
                    createParam.put("snapshotPriceId", getPriceInfo.getJSONObject("data").getString("snapshotPriceId"));
                    createParam.put("longitude", merchant.getLongitude());
                    createParam.put("latitude", merchant.getLatitude());
                    createParam.put("uuid", gasOrder.getOrderNo());
                    createParam.put("thirdPartyDiscountAmount", gasOrder.getPayablePrice());
                    createParam.put("phone", gasOrder.getUserPhone());
                    // 下单
                    JSONObject createOrder = NewLink2RequestService.createOrder(createParam);
                    if (!createOrder.getString("code").equals("200")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败："+createOrder.getString("msg"));
                    }
                    gasOrder.setChannelOrderNo(createOrder.getJSONObject("data").getString("orderNo"));
                    gasOrderService.updateGasOrder(gasOrder);

                    // 支付回告
                    JSONObject payCallBack = NewLink2RequestService.payCallBack(
                            gasOrder.getChannelOrderNo(),
                            3,
                            null,
                            gasOrder.getOrderNo()
                    );
                    if (!payCallBack.getString("code").equals("200")) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "下单失败："+createOrder.getString("msg"));
                    }
                    gasOrder.setAbnormal(false);
                    gasOrder.setAbnormalContent(null);

                } catch (BaseException e) {
                    gasOrder.setAbnormal(true);
                    gasOrder.setAbnormalContent(e.getErrorMsg());
                }  catch (Exception e) {
                    gasOrder.setAbnormal(true);
                    gasOrder.setAbnormalContent("推送订单未知错误！请稍后重新推送");
                }
                gasOrderService.updateGasOrder(gasOrder);
            }
        }
        return gasOrder;
    }



}
