package com.hai.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.entity.*;
import com.hai.enum_type.OilCardRecordSourceTypeEnum;
import com.hai.openApi.config.PriceComputeConfig;
import com.hai.order.service.OrderPayService;
import com.hai.order.service.OrderPaySuccessService;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderPayType;
import com.hai.order.type.OrderProductType;
import com.hai.order.type.OrderStatus;
import com.hai.service.*;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

/**
 * @className: OrderPayServiceImpl
 * @author: HuRui
 * @date: 2022/9/5
 **/
@Service("orderPayService")
public class OrderPayServiceImpl implements OrderPayService {

    @Resource
    private OrderPaySuccessService orderPaySuccessService;

    @Resource
    private HighUserCardService userCardService;

    @Resource
    private HighOilCardService oilCardService;

    @Resource
    private HighFleetOilCardService fleetOilCardService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private HighGasOrderService gasOrderService;

    @Resource
    private PriceComputeConfig priceComputeConfig;

    @Resource
    private HighOrderService highOrderService;

    @Override
    public HighOrder hltCardPay(HighOrder order, HighUserCard userCard) throws Exception {
        String goodsDesc = "";
        String tranDesc = "";
        String instCode = "11101527";
        String businessType = "hisen_consume";

        if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE5.getNumber())) {
            instCode = "11101526";
            businessType = "sinopec_oil_code";
            goodsDesc = "购买加油券";
            tranDesc = order.getHighChildOrderList().get(0).getGoodsName();

        } else if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE4.getNumber())) {
            goodsDesc = "积分充值" + order.getPayPrice() + "元";
            tranDesc = "嗨森逛积分充值" + order.getPayPrice() + "元";

        } else if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE6.getNumber())) {
            goodsDesc = "加油站加" + order.getPayPrice() + "元油";
            tranDesc = "【" + order.getHighChildOrderList().get(0).getGoodsName() + "】加油" + order.getPayPrice() + "元";

        } else if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE7.getNumber())) {
            goodsDesc = "购买优惠券包";
            tranDesc = "购买" + order.getHighChildOrderList().get(0).getGoodsName() + "优惠券包";

        } else if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE9.getNumber())) {
            goodsDesc = "购买话费";
            tranDesc = "购买" + order.getHighChildOrderList().get(0).getGoodsName();

        } else {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法支付，请使用其他支付方式");
        }

        // 工会卡支付
        JSONObject consumption = HuiLianTongUnionCardConfig.consumption(order.getOrderNo(), userCard.getCardNo(), order.getPayPrice(), businessType, instCode, goodsDesc, tranDesc);
        if (!consumption.getString("respCode").equals("0000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumption.getString("respMessage"));
        }
        // 响应参数
        JSONObject consumptionResult = HuiLianTongUnionCardConfig.resolveResponse(consumption.getString("data"));
        if (consumptionResult.getBoolean("success") != true) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, consumptionResult.getString("message"));
        }

        // 处理订单业务
        return orderPaySuccessService.orderPaySuccessHandle(
                order.getOrderNo(),
                OrderPayType.PAY_TYPE4,
                consumptionResult.getString("orderId"),
                order.getPayPrice(),
                userCard);

    }

    @Override
    public HighOrder oilCardPay(HighOrder order, HighUserCard userCard) {
        // 油卡扣款
        Map<String, Object> consumeMap = new HashMap<>();
        consumeMap.put("sourceType", OilCardRecordSourceTypeEnum.type2.getType());
        consumeMap.put("sourceId", order.getId());
        consumeMap.put("sourceOrderNo", order.getOrderNo());
        consumeMap.put("sourceContent", "订单号：" + order.getOrderNo() + ",消费：￥" + order.getPayPrice());
        oilCardService.consume(userCard.getCardNo(), order.getPayPrice(), consumeMap);

        // 处理订单业务
        return orderPaySuccessService.orderPaySuccessHandle(
                order.getOrderNo(),
                OrderPayType.PAY_TYPE7,
                null,
                order.getPayPrice(),
                userCard);
    }

    @Override
    public HighOrder oilCardFleetPay(HighOrder order, HighUserCard userCard, String carLicensePlate) {
        if (StringUtils.isNotBlank(carLicensePlate)) {
            // 加油订单
            HighGasOrder gasOrder = gasOrderService.getDetailByOrderNo(order.getOrderNo());
            if (gasOrder == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油订单");
            }
            gasOrder.setGasCarLicensePlate(carLicensePlate);
            gasOrderService.updateGasOrder(gasOrder);
        }

        // 油卡扣款
        Map<String, Object> consumeMap = new HashMap<>();
        consumeMap.put("sourceType", OilCardRecordSourceTypeEnum.type2.getType());
        consumeMap.put("sourceId", order.getId());
        consumeMap.put("sourceOrderNo", order.getOrderNo());
        consumeMap.put("sourceContent", "订单号：" + order.getOrderNo() + ",消费：￥" + order.getPayPrice());
        fleetOilCardService.consume(userCard.getCardNo(), order.getMemPhone(), order.getPayPrice(), consumeMap);

        // 处理订单业务
        return orderPaySuccessService.orderPaySuccessHandle(
                order.getOrderNo(),
                OrderPayType.PAY_TYPE8,
                null,
                order.getPayPrice(),
                userCard);
    }

    @Override
    public HighOrder apiMchAmount(String orderNo, ApiMerchants apiMerchants , ApiOrder apiOrder) throws Exception {

        String key = "apiMerchant" + apiMerchants.getMchId();

        // 分布式锁占坑
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, apiOrder.getOrderNo());

        HighOrder order = highOrderService.getOrderByOrderNo(orderNo);

        if(!order.getOrderStatus().equals(OrderStatus.STATUS1.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
        }

        if(Boolean.TRUE.equals(lock)) {

            // 判断金额是否充足
            if (!priceComputeConfig.mchBalance(apiMerchants , apiOrder.getCostPrice() , apiOrder.getMchOrderNo())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.INSUFFICIENT_BALANCE);
            }

            // 处理订单业务
            return orderPaySuccessService.orderPaySuccessHandle(
                    order.getOrderNo(),
                    OrderPayType.PAY_TYPE9,
                    null,
                    order.getPayPrice(),
                    null);
        } else {
            // 加锁失败，重试
            Thread.sleep(100);
            apiMchAmount(orderNo , apiMerchants , apiOrder);
        }
        return null;
    }
}
