package com.xhpc.evcs.notification;

import com.xhpc.common.data.redis.CacheOrderData;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.XhpcRate;
import com.xhpc.evcs.dto.ChargeOrderInfo;
import com.xhpc.evcs.dto.ChargeOrderInfoResponse;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcRateRepository;
import com.xhpc.evcs.utils.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.domain.AuthSecretToken.SECRET_TOKEN_TYPE_OUT;

/**
 * 用于进行充电历史订单的推送
 *
 * @author WH
 * @date 2021/11/7 14:39
 * @since version-1.0
 */
public class NotificationChargeOrderInfo extends CoreDispatcher {

    @Autowired
    private RedisService redisService;

    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;

    @Autowired
    private XhpcRateRepository xhpcRateRepository;


    public static void main(String[] args) {

    }

    public void pushChargeOrderInfo() throws IOException {

        //获取Redis中的所有订单的状态数据
        Collection<String> pushOrders = REDIS.keys("pushOrder:*");

        for (String pushOrderKey : pushOrders) {
            Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderKey);
            Boolean isStopNotified = (Boolean) pushOrder.get("isStopNotified");
            if (isStopNotified) {
                continue;
            }
            String orderNo = pushOrderKey.substring(10);
            Map<String, Object> order = REDIS.getCacheMap("order:" + orderNo);
            String operatorId3rdpty = (String) pushOrder.get("operatorId3rdpty");
            if (operatorId3rdpty == null) {
                continue;
            }
            AuthSecretToken authSecretTokenOut =
                    authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId3rdpty,
                            SECRET_TOKEN_TYPE_OUT).orElse(null);
            if (authSecretTokenOut == null) {
                continue;
            }
            CommonRequest<ChargeOrderInfo> commonRequest = new CommonRequest<>();
            //封装数据的实体类
            ChargeOrderInfo chargeOrderInfo = new ChargeOrderInfo();
            //判断是否是结束了的充电订单
            if (isStopNotified) {
                //充电订单号（内部对应的第三方充电订单号）
                CacheOrderData orderData = (CacheOrderData) order.get("orderData");
                String internetSerialNumber = (String) pushOrder.get("internetSerialNumber");
                chargeOrderInfo.setStartChargeSeq(internetSerialNumber);
                if (orderData != null) {
                    //使用指定包装类封装数据
                    //充电设备接口编码
                    chargeOrderInfo.setConnectorID(orderData.getPileNo() + orderData.getGunId());
                    //开始充电时间
                    chargeOrderInfo.setStartTime(orderData.getStartTime());
                    //结束充电时间
                    chargeOrderInfo.setEndTime(orderData.getEndTime());
                    //累计充电量
                    chargeOrderInfo.setTotalPower(Double.parseDouble(orderData.getTotalPowerQuantity().toString()) / 10000);
                    //总电费
                    Map<String, Double> map = getTotalElecMoneyAndTotalServiceMoney(orderNo);
                    Double totalPowerPrice = map.get("totalPowerPrice");
                    chargeOrderInfo.setTotalPower(totalPowerPrice);
                    //总服务费
                    Double totalServicePrice = map.get("totalServicePrice");
                    chargeOrderInfo.setTotalSeviceMoney(totalServicePrice);
                    //累计总金额
                    Double sumMoney = totalPowerPrice + totalServicePrice;
                    chargeOrderInfo.setTotalMoney(sumMoney);
                    //充电结束原因
                    chargeOrderInfo.setStopReason(0);

                    //将其转换为json
                    String jsonData = JSONUtil.toJSONString(chargeOrderInfo);
                    commonRequest.setData(jsonData);
                    String result = ok(commonRequest, "/notification_charge_order_info", authSecretTokenOut);

                    ChargeOrderInfoResponse chargeOrderInfoResponse = JSONUtil.readParams(result, ChargeOrderInfoResponse.class);
                    Integer confirmResult = chargeOrderInfoResponse.getConfirmResult();
                    //无视争议订单，对结果不进行处理，在下面的推送中在进行处理
                }
            }
        }
    }

    private Map<String, Double> getTotalElecMoneyAndTotalServiceMoney(String orderNo) {

        //获取结算后的订单
        Map<String, Object> cacheMap = redisService.getCacheMap("order:" + orderNo);
        CacheOrderData cacheOrderData = (CacheOrderData) cacheMap.get("orderData");
        //总金额
        BigDecimal bigDecimal = new BigDecimal(10000);
        BigDecimal money = new BigDecimal(cacheOrderData.getCost()).divide(bigDecimal);
        //00: 尖费率 01: 峰费率 02: 平费率 03: 谷费率
        BigDecimal t1powerFee = new BigDecimal(0);
        BigDecimal t2powerFee = new BigDecimal(0);
        BigDecimal t3powerFee = new BigDecimal(0);
        BigDecimal t4powerFee = new BigDecimal(0);
        //费率计费模型
        Long rateModelId = (Long) cacheMap.get("rateModelId");
        List<XhpcRate> rateModelList = xhpcRateRepository.findByRateModelId(rateModelId);
        for (XhpcRate xhpcRate : rateModelList) {
            if ("00".equals(xhpcRate.getRateValue())) {
                t1powerFee = xhpcRate.getPowerFee();
            }
            if ("01".equals(xhpcRate.getRateValue())) {
                t2powerFee = xhpcRate.getPowerFee();
            }
            if ("02".equals(xhpcRate.getRateValue())) {
                t3powerFee = xhpcRate.getPowerFee();
            }
            if ("03".equals(xhpcRate.getRateValue())) {
                t4powerFee = xhpcRate.getPowerFee();
            }
        }
        //总电费
        BigDecimal powerPrice = new BigDecimal(0);
        Integer totalPower = 0;
        if (!"0".equals(cacheOrderData.getT1PowerQuantity().toString())) {
            BigDecimal multiply = new BigDecimal(cacheOrderData.getT1PowerQuantity()).divide(bigDecimal).multiply(t1powerFee);
            totalPower = totalPower + cacheOrderData.getT1PowerQuantity();
            powerPrice = powerPrice.add(multiply);
        }
        if (!"0".equals(cacheOrderData.getT2PowerQuantity().toString())) {
            BigDecimal multiply = new BigDecimal(cacheOrderData.getT2PowerQuantity()).divide(bigDecimal).multiply(t2powerFee);
            totalPower = totalPower + cacheOrderData.getT2PowerQuantity();
            powerPrice = powerPrice.add(multiply);
        }
        if (!"0".equals(cacheOrderData.getT3PowerQuantity().toString())) {
            BigDecimal multiply = new BigDecimal(cacheOrderData.getT3PowerQuantity()).divide(bigDecimal).multiply(t3powerFee);
            totalPower = totalPower + cacheOrderData.getT3PowerQuantity();
            powerPrice = powerPrice.add(multiply);
        }
        if (!"0".equals(cacheOrderData.getT4PowerQuantity().toString())) {
            BigDecimal multiply = new BigDecimal(cacheOrderData.getT4PowerQuantity()).divide(bigDecimal).multiply(t4powerFee);
            totalPower = totalPower + cacheOrderData.getT4PowerQuantity();
            powerPrice = powerPrice.add(multiply);
        }
        powerPrice = powerPrice.setScale(2, BigDecimal.ROUND_DOWN);
        //总服务费
        BigDecimal servicePrice = money.subtract(powerPrice);

        HashMap<String, Double> data = new HashMap<>(7);
        data.put("totalPowerPrice", servicePrice.doubleValue());
        data.put("totalServicePrice", servicePrice.doubleValue());

        return data;
    }

}
