package com.hfkj.service.order;

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.entity.*;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.merchant.BsMerchantAccountService;
import com.hfkj.service.merchant.BsMerchantChainBrandAccountService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.merchant.BsMerchantUserService;
import com.hfkj.service.gas.BsGasOrderService;
import com.hfkj.service.sec.SecDictionaryService;
import com.hfkj.sysenum.merchant.MerchantChainBrandSettleTypeEnum;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.gas.OrderOilStatus;
import com.hfkj.sysenum.merchant.MerchantAccountRecordSourceTypeEnum;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: OrderPaySuccessService
 * @author: HuRui
 * @date: 2024/5/7
 **/
@Component
public class OrderPaySuccessService {
    Logger log = LoggerFactory.getLogger(OrderPaySuccessService.class);
    @Resource
    private SecDictionaryService dictionaryService;
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsMerchantUserService merchantUserService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private BsDeviceService deviceService;
    @Resource
    private BsMerchantAccountService merchantAccountService;
    @Resource
    private BsMerchantChainBrandAccountService merchantChainBrandAccountService;

    /**
     * 订单业务处理
     * @param order
     * @throws Exception
     */
    public void orderBusHandle(OrderModel order) {
        for (BsOrderChild childOrder : order.getOrderChildList()) {
            try {
                if (childOrder.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
                    oilHandle(order);
                }
             } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 加油业务
     * @param order
     */
    public BsGasOrder oilHandle(OrderModel order) throws Exception {
        // 查询加油订单
        BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(order.getOrderNo());
        if (gasOrder != null) {
            gasOrder.setPayIntegral(order.getDeduction().getIntegralDiscountPrice());
            gasOrder.setActualPayPrice(order.getPayRealPrice());
            gasOrder.setPayType(order.getPayType());
            gasOrder.setPayTime(order.getPayTime());
            gasOrder.setStatus(OrderOilStatus.STATUS2.getNumber());
            gasOrder.setPaySerialNo(order.getPaySerialNo());
            gasOrder.setPayChannelOrderNo(order.getPayChannelOrderNo());
            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);
            }

            if (StringUtils.isNotBlank(gasOrder.getUserPhone())) {
                // 查询商户会员
                BsMerchantUser merchantUser = merchantUserService.getUser(gasOrder.getMerNo(), gasOrder.getUserPhone());
                if (merchantUser == null) {
                    // 注册商户会员
                    merchantUser = new BsMerchantUser();
                    merchantUser.setMerId(gasOrder.getMerId());
                    merchantUser.setMerNo(gasOrder.getMerNo());
                    merchantUser.setMerName(gasOrder.getMerName());
                    merchantUser.setUserId(gasOrder.getUserId());
                    merchantUser.setUserPhone(gasOrder.getUserPhone());
                    merchantUser.setVipLevel(0);
                    merchantUser.setIntegral(0);
                    merchantUser.setStatus(1);
                    merchantUserService.editData(merchantUser);
                }
                // TODO 赠送积分
            }

            // 子订单完成
            orderService.childOrderComplete(gasOrder.getOrderChildNo());
        }

        return gasOrder;
    }

    /**
     * api加油业务
     * @param gasOrder
     * @return
     * @throws Exception
     */
    public BsGasOrder oilApiHandle(BsGasOrder gasOrder) throws Exception {
        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);
        }

        if (StringUtils.isNotBlank(gasOrder.getUserPhone())) {
            // 查询商户会员
            BsMerchantUser merchantUser = merchantUserService.getUser(gasOrder.getMerNo(), gasOrder.getUserPhone());
            if (merchantUser == null) {
                // 注册商户会员
                merchantUser = new BsMerchantUser();
                merchantUser.setMerId(gasOrder.getMerId());
                merchantUser.setMerNo(gasOrder.getMerNo());
                merchantUser.setMerName(gasOrder.getMerName());
                merchantUser.setUserId(gasOrder.getUserId());
                merchantUser.setUserPhone(gasOrder.getUserPhone());
                merchantUser.setVipLevel(0);
                merchantUser.setIntegral(0);
                merchantUser.setStatus(1);
                merchantUserService.editData(merchantUser);
            }
            // TODO 赠送积分
        }
        return gasOrder;
    }

}
