package com.hfkj.service.order;

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.GasPayPriceModel;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.service.agent.BsAgentApiParamService;
import com.hfkj.service.agent.BsAgentMerAccountService;
import com.hfkj.service.agent.BsAgentService;
import com.hfkj.service.discount.BsDiscountUseMerService;
import com.hfkj.service.gas.*;
import com.hfkj.service.merchant.BsMerchantPayConfigService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.agent.BsAgentMerService;
import com.hfkj.service.sec.SecDictionaryService;
import com.hfkj.service.spread.BsUserSpreadRelService;
import com.hfkj.sysenum.agent.AgentStatusEnum;
import com.hfkj.sysenum.gas.GasOrderCreateType;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.merchant.MerchantStatusEnum;
import com.hfkj.sysenum.gas.GasOrderReceiptStatusEnum;
import com.hfkj.sysenum.gas.OrderOilStatus;
import com.hfkj.sysenum.merchant.MerchantAccountRecordSourceTypeEnum;
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.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建订单业务
 * @className: OrderCreateService
 * @author: HuRui
 * @date: 2024/6/7
 **/
@Component
public class OrderCreateService {
    Logger log = LoggerFactory.getLogger(OrderCreateService.class);
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private SecDictionaryService secDictionaryService;
    @Resource
    private BsGasService gasService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsDiscountUseMerService discountUseMerService;
    @Resource
    private BsAgentMerAccountService agentMerAccountService;
    @Resource
    private BsGasClassGroupTaskService gasClassGroupTaskService;
    @Resource
    private BsAgentMerService agentMerService;
    @Resource
    private BsGasStaffService gasStaffService;
    @Resource
    private BsMerchantPayConfigService merPayConfigService;
    @Resource
    private BsGasChannelConfigService gasChannelConfigService;
    @Resource
    private BsGasOrderSpreadService gasOrderSpreadService;
    @Resource
    private BsAgentApiParamService agentApiParamService;
    @Resource
    private BsAgentService agentService;
    /**
     * 加油业务
     * @param order  订单
     * @param orderDeduction 优惠
     * @param orderChild   商品订单
     * @return
     */
    public OrderChildModel oilHandle(BsOrder order, BsOrderDeduction orderDeduction, OrderChildModel orderChild) {
        // 查询油品类型
        SecDictionary gasOilType = secDictionaryService.getDictionary("OIL_NO", orderChild.getGasOilNo());
        if (gasOilType == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知油品类型");
        }
        if (orderChild.getProductPrice().compareTo(new BigDecimal("10")) <= 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "加油金额不能小于10元");
        }
        // 汽油限制加油金额
        if ("1".equals(gasOilType.getExt1())) {
            SecDictionary priceLimit = secDictionaryService.getDictionary("GAS_REFUEL_PRICE_LIMIT", "1");
            if (priceLimit!=null) {
                if (orderChild.getProductPrice().compareTo(new BigDecimal(priceLimit.getCodeName())) > 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "加油单笔限制" + priceLimit.getCodeName()+"元");
                }
            }
        }
        // 下单数量限制
        int createOrderLimit = Integer.parseInt(secDictionaryService.getDictionary("GAS_ORDER_CREATE_LIMIT").get(0).getCodeValue());
        if (gasOrderService.countTodayOrder(order.getUserPhone()) >= createOrderLimit) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "加油订单每日下单限制"+createOrderLimit+"笔");
        }

        if (orderDeduction != null && orderDeduction.getUserCouponDiscountId() != null) {
            if (discountUseMerService.getDetail(orderDeduction.getCouponDiscountNo(), orderChild.getMerNo()) == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "油站不支持该优惠券使用");
            }
        }

        // 查询油站
        BsMerchant merchant = merchantService.getMerchant(orderChild.getMerNo());
        if (merchant == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油站");
        }
        if (!merchant.getStatus().equals(MerchantStatusEnum.status1.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前油站暂停交易");
        }
        if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
            // 查询平台
            BsMerchantPayConfig merPay = merPayConfigService.getConfig(merchant.getMerNo());
            if (merPay == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
            }

        } else if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type2.getNumber())
                || merchant.getSourceType().equals(MerchantSourceTypeEnum.type3.getNumber())) {
            // 查询渠道支付配置
            BsGasChannelConfig payConfig = gasChannelConfigService.getDetail(MerchantSourceTypeEnum.getDataByType(merchant.getSourceType()));
            if (payConfig == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
            }
            if (payConfig.getTradeStatus().equals(false)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "油站维护中暂停交易！");
            }
        }
        BsGasOrder gasOrder = new BsGasOrder();
        gasOrder.setAbnormal(false);
        gasOrder.setMerNo(merchant.getMerNo());
        gasOrder.setChannelType(merchant.getSourceType());
        gasOrder.setOrderNo(orderChild.getOrderNo());
        gasOrder.setOrderChildNo(orderChild.getChildOrderNo());
        gasOrder.setUserId(order.getUserId());
        gasOrder.setUserPhone(order.getUserPhone());
        gasOrder.setMerChainBrandId(merchant.getChainBrandId());
        gasOrder.setMerChainBrandName(merchant.getChainBrandName());
        gasOrder.setMerId(merchant.getId());
        gasOrder.setMerName(merchant.getMerName());
        gasOrder.setMerAddress(merchant.getAddress());
        gasOrder.setStatus(OrderOilStatus.STATUS1.getNumber());
        gasOrder.setReceiptStatus(GasOrderReceiptStatusEnum.status0.getStatus());
        gasOrder.setGasSettlePrice(new BigDecimal("0"));
        gasOrder.setGasAgentSettlePrice(new BigDecimal("0"));

        // 计算价格
        GasPayPriceModel priceModel = gasService.refuelPriceCompute(orderChild.getProductPrice(), merchant.getMerNo(), orderChild.getGasOilNo(), orderChild.getAgentMerId(), orderDeduction.getUserCouponDiscountId());

        // 油站结算 公式 1. 加油升数 * (油枪价 - 优惠价) = 优惠金额  2. 加油金额 - 优惠金额 = 扣款金额
        BigDecimal gasSettlePrice = priceModel.getOilingPrice().subtract(
                // 优惠金额
                priceModel.getOilLiters().multiply(priceModel.getPriceGun().subtract(priceModel.getPriceVip()))
        );
        gasOrder.setGasSettlePrice(gasSettlePrice);

        // 代理商appid
        if (StringUtils.isNotBlank(orderChild.getAgentAppId())) {
            // 代理商参数
            BsAgentApiParam apiParam = agentApiParamService.getParamByAppId(orderChild.getAgentAppId());
            if (apiParam == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理参数接入错误");
            }
            if (!apiParam.getStatus().equals(1)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理参数接入错误");
            }
            // 代理商
            BsAgent agent = agentService.getAgentById(apiParam.getAgentId());
            if (agent == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理参数接入错误");
            }
            if (!agent.getStatus().equals(AgentStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "代理处于异常状态");
            }
            gasOrder.setAgentId(agent.getId());
            gasOrder.setAgentName(agent.getName());
        }

        // 代理、业务员
        if (orderChild.getAgentMerId() != null) {
            // 查询代理
            BsAgentMer agentMer = agentMerService.getDetail(orderChild.getAgentMerId());
            if (agentMer == null || agentMer.getStatus() != 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法交易，代理商二维码已失效");
            }
            try {
                if (MerchantSourceTypeEnum.type1.getNumber().equals(merchant.getSourceType())) {
                    // 扣除代理商商户金额
                    Map<String,Object> param = new HashMap<>();
                    param.put("sourceType", MerchantAccountRecordSourceTypeEnum.type2.getType());
                    param.put("sourceOrderNo", gasOrder.getOrderNo());
                    param.put("sourceOrderContent", "创建加油订单："+gasOrder.getOrderNo());

                    // 代理商结算公式
                    // 1. 加油升数 * (优惠价 -（优惠价 * 代理折扣）) = 优惠金额
                    // 2. 油站(扣款金额)结算 + 优惠金额 = 扣款金额
                    BigDecimal aasAgentSettlePrice = gasOrder.getGasSettlePrice().add(
                            // 代理商优惠金额
                            priceModel.getOilLiters().multiply(priceModel.getPriceVip().subtract(priceModel.getPricePlatform()))
                    );
                    gasOrder.setGasAgentSettlePrice(aasAgentSettlePrice);
                    agentMerAccountService.consume(agentMer.getAgentId(), agentMer.getMerNo(), gasOrder.getGasAgentSettlePrice(), param);
                }
            } catch (BaseException e) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, e.getErrorMsg());
            } catch (Exception e) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "扣款失败，请稍后重新提交订单");
            }
            gasOrder.setAgentId(agentMer.getAgentId());
            gasOrder.setAgentName(agentMer.getAgentName());
            gasOrder.setAgentStaffId(agentMer.getAgentStaffId());
            gasOrder.setAgentStaffName(agentMer.getAgentStaffName());
        }

        gasOrder.setDeductionCouponPrice(priceModel.getDeductionCouponPrice());
        gasOrder.setDeductionOilPrice(priceModel.getDeductionOilPrice());
        gasOrder.setGasServiceFeeRate(priceModel.getServiceFeeRate());
        gasOrder.setGasServiceFeePrice(priceModel.getServiceFeePrice());
        gasOrder.setTotalDeductionPrice(priceModel.getTotalPreferences());
        gasOrder.setPayablePrice(priceModel.getPayPrice());
        gasOrder.setPayablePrice(gasOrder.getPayablePrice().compareTo(new BigDecimal("0"))>=0?gasOrder.getPayablePrice():new BigDecimal("0"));

        // 油价信息
        gasOrder.setGasRefuelPrice(orderChild.getProductPrice());
        gasOrder.setGasOilNo(orderChild.getGasOilNo());
        gasOrder.setGasGunNo(orderChild.getGasGunNo());
        gasOrder.setGasOilType(Integer.parseInt(gasOilType.getExt1()));
        gasOrder.setGasPriceGun(priceModel.getPriceGun());
        gasOrder.setGasPriceVip(priceModel.getPriceVip());
        gasOrder.setGasPriceCost(priceModel.getPriceCost());
        gasOrder.setGasPriceOfficial(priceModel.getPriceOfficial());
        gasOrder.setGasPricePlatform(priceModel.getPricePlatform());
        gasOrder.setGasOilLiters(priceModel.getOilLiters());
        gasOrder.setGasDiscount(priceModel.getDiscount());
        gasOrder.setGasOilSubsidy(priceModel.getPreferentialMargin());
        gasOrder.setGasLitersPreferences(priceModel.getLitersPreferences());
        gasOrder.setGasPricePreferences(priceModel.getPricePreferences());

        // 加油员
        if (orderChild.getGasStaffId() != null) {
            // 查询员工
            BsGasStaff gasStaff = gasStaffService.getStaffDetailById(orderChild.getGasStaffId());
            if (gasStaff == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的加油员");
            }
            if (gasStaff.getMerId().equals(merchant.getId())) {
                gasOrder.setGasStaffId(gasStaff.getId());
                gasOrder.setGasStaffName(gasStaff.getName());
            }
        }

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

        gasOrder.setCreateType(GasOrderCreateType.TYPE1.getNumber());
        gasOrderService.addGasOrder(gasOrder);

        // 推广佣金
        gasOrderSpreadService.createOrderSpread(gasOrder);

        orderChild.setMerNo(merchant.getMerNo());
        orderChild.setProductName(merchant.getMerName());
        orderChild.setProductImg(merchant.getMerLogo());
        orderChild.setProductSpecName("默认");
        orderChild.setProductCount(1);
        orderChild.setProductActualPrice(priceModel.getPayPrice());
        return orderChild;
    }

}
