package com.xhpc.evcs.cdjgpc.notification;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.xhpc.evcs.cdjgpc.domain.EtPushCdjgFailedOrder;
import com.xhpc.evcs.cdjgpc.dto.CDCancelOrderResponse;
import com.xhpc.evcs.cdjgpc.dto.CDOrderInfo;
import com.xhpc.evcs.cdjgpc.dto.CDStationInfo;
import com.xhpc.evcs.cdjgpc.jpa.EtPushCdjgFailedOrderRepository;
import com.xhpc.evcs.domain.*;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.DTOJsonHelper;
import com.xhpc.evcs.jpa.*;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.notification.NotificationChargeOrderInfo4BonusTask;
import com.xhpc.evcs.utils.DateUtil;
import com.xhpc.evcs.utils.JSONUtil;
import com.xhpc.order.domain.XhpcHistoryOrder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
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 yuyang
 * @date 2023-09-20 9:34
 */
@Component
@Slf4j
@RestController
@RequestMapping("/api/orderInfoTask")
public class CDNotificationOrderInfoTask extends CoreDispatcher {
    @Autowired
    private XhpcHistoryOrderRepository xhpcHistoryOrderRepository;
    @Autowired
    private EtPushCdjgFailedOrderRepository etPushCdjgFailedOrderRepository;
    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private StatisticTimeIntervalRepository statisticTimeIntervalRepository;
    @Autowired
    private OrderMappingRepository orderMappingRepository;
    @Autowired
    private XhpcChargingStationRepository chargingStationRepo;
    @Autowired
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    private final Logger logger = LoggerFactory.getLogger(CDNotificationOrderInfoTask.class);

    /**
     *订单信息推送   ---已推送--推送服务使用
     * @throws IOException
     */
    //9099开放定时任务  9009不开放
    @GetMapping("/infoTask")
    //@Scheduled(fixedRate = 1000 * 30)
    public void run() throws IOException {
        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA6CC2LK7", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo
        // maybe对接第三方
        if (authSecretTokenOut != null) {
            final List<XhpcHistoryOrder> notYetPushOrder =
                    xhpcHistoryOrderRepository.findTop100ByHistoryOrderIdGreaterThanEqualOrderByHistoryOrderIdAsc(authSecretTokenOut.getLastPushOrder());
            for (XhpcHistoryOrder xhpcHistoryOrder : notYetPushOrder) {
                XhpcStationInternetBlacklist xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByChargingStationIdAndInternetUserId(xhpcHistoryOrder.getChargingStationId(),
                                6L).orElse(null);
                if (xhpcStationInternetBlacklist != null) continue;
                List<XhpcStatisticsTimeInterval> statisticTimeIntervalList =
                        statisticTimeIntervalRepository.findByHistoryOrderId(xhpcHistoryOrder.getHistoryOrderId());
                xhpcHistoryOrder.setXhpcStatisticsTimeIntervalList(statisticTimeIntervalList);
                if(!xhpcHistoryOrder.getStartTime().toString().equals(xhpcHistoryOrder.getEndTime().toString())){
                    notify(xhpcHistoryOrder, authSecretTokenOut, false);
                }else{
                    //充电时长不能小于或等于0 不能推送
                   // logger.info("========新平台推送=======responseBody===================充电时长不能小于或等于0==========");
                }

            }
            final List<XhpcHistoryOrder> pushFailedOrders =
                    xhpcHistoryOrderRepository.findTop10JoinPushFailedOrders(authSecretTokenOut.getOperatorId3irdpty());
            for (XhpcHistoryOrder xhpcHistoryOrder : pushFailedOrders) {
                XhpcStationInternetBlacklist xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByChargingStationIdAndInternetUserId(xhpcHistoryOrder.getChargingStationId(),
                                6L).orElse(null);
                if (xhpcStationInternetBlacklist != null) continue;
                List<XhpcStatisticsTimeInterval> statisticTimeIntervalList =
                        statisticTimeIntervalRepository.findByHistoryOrderId(xhpcHistoryOrder.getHistoryOrderId());
                xhpcHistoryOrder.setXhpcStatisticsTimeIntervalList(statisticTimeIntervalList);
                final boolean notify = notify(xhpcHistoryOrder, authSecretTokenOut, true);
                if (notify) {
                    etPushCdjgFailedOrderRepository.deleteById(xhpcHistoryOrder.getHistoryOrderId());
                }
            }
        }
    }

    public boolean notify(XhpcHistoryOrder xhpcHistoryOrder, AuthSecretToken authSecretTokenOut, boolean isRepush) throws IOException {
        String operatorIdEvcs = xhpcHistoryOrder.getOperatorIdEvcs();
        if (operatorIdEvcs == null) {
            Long chargingStationId = xhpcHistoryOrder.getChargingStationId();
            XhpcChargingStation station = chargingStationRepo.findById(chargingStationId).orElse(null);
            if(station == null){
                logger.error("station[{}] is not exits", chargingStationId);
                return false;
            }

            String stationOperatorIdEvcs = station.getOperatorIdEvcs();
            if (stationOperatorIdEvcs == null) {
                logger.error("station[{}] operator id evcs not set", chargingStationId);
                return false;
            }
            if (stationOperatorIdEvcs.length() == 18) {
                operatorIdEvcs = stationOperatorIdEvcs.substring(8, 17);
            } else {
                operatorIdEvcs = stationOperatorIdEvcs;
            }
        }
        Long chargingStationId = xhpcHistoryOrder.getChargingStationId();
        String key = "cdjgpc:station:".concat(chargingStationId.toString())+".notification";
        CDStationInfo cdStationInfo =REDIS.getCacheObject(key);

        EtOrderMapping etOrderMapping = saveOrderMapping(xhpcHistoryOrder, orderMappingRepository, operatorIdEvcs);
        CDOrderInfo cdChargeOrderInfo4BonusReq = new CDOrderInfo(xhpcHistoryOrder,etOrderMapping);
        if(cdStationInfo !=null && cdStationInfo.getOperatorId() !=null){
            cdChargeOrderInfo4BonusReq.setOperatorID(cdStationInfo.getOperatorId());
            cdChargeOrderInfo4BonusReq.setEquipmentOwnerID(cdStationInfo.getEquipmentOwnerId());
        }
        operatorIdEvcs = operatorIdEvcs == null ? "MA6DFCTD5" : operatorIdEvcs;
        Map<String,Object> mapStationInfo =new HashMap<>();
        mapStationInfo.put("OrderInfo",cdChargeOrderInfo4BonusReq);
        String data = JSONUtil.toJSONString(mapStationInfo);
        CommonRequest<CDOrderInfo> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String responseBody = ok(commonRequest, "/notification_orderInfo", authSecretTokenOut);
        logger.info("========新平台推送=======responseBody============================="+cdChargeOrderInfo4BonusReq.getStartChargeSeq());


        CDCancelOrderResponse cdChargeOrder4BonusInfoRes = DTOJsonHelper.parseResponseData(responseBody,
                CDCancelOrderResponse.class, authSecretTokenOut);
        //logger.info("========新平台推送=======responseBody==状态==========================="+cdChargeOrder4BonusInfoRes.getStatus());
        if (!isRepush) {
            authSecretTokenOut.setLastPushOrder(xhpcHistoryOrder.getHistoryOrderId());
            authSecretTokenRepository.save(authSecretTokenOut);
        }
        if (cdChargeOrder4BonusInfoRes != null && cdChargeOrder4BonusInfoRes.getStatus() == 0) {
            return true;
        } else {
            if (!isRepush) {
                EtPushCdjgFailedOrder etPushFailedOrder = new EtPushCdjgFailedOrder();
                etPushFailedOrder.setId(xhpcHistoryOrder.getHistoryOrderId());
                etPushFailedOrder.setOperatorId3rdpty(authSecretTokenOut.getOperatorId3irdpty());
                etPushFailedOrder.setCreateTime(new Date());
                etPushCdjgFailedOrderRepository.save(etPushFailedOrder);
            }
            logger.error(String.format("push CD notification order[%s] failed: %s", xhpcHistoryOrder.getSerialNumber(),
                    responseBody));
            return false;
        }
    }

    private EtOrderMapping saveOrderMapping(XhpcHistoryOrder xhpcHistoryOrder,
                                            OrderMappingRepository orderMappingRepository, String operatorId) {

        String internetSerialNumber = xhpcHistoryOrder.getInternetSerialNumber();
        String xhOrderNo = xhpcHistoryOrder.getSerialNumber();
        return saveOrderMapping(xhOrderNo, internetSerialNumber, orderMappingRepository, operatorId);
    }

    public static String transferInternetOrderNo(String orderKeyOrNo, String operatorId) {
        //80836000010001012110191723410021
        //MA6DFCTD5202201111742100140
        String orderNo = orderKeyOrNo.replace("order:", "");
        if (operatorId.length() > 9) {
            operatorId = operatorId.substring(0, 9);
        }
        return operatorId.concat(DateUtil.getYYYY()).concat(orderNo.substring(18));
    }

    public static EtOrderMapping saveOrderMapping(String xhOrderNo, String internetSerialNumber,
                                                  OrderMappingRepository orderMappingRepository, String operatorId) {

        EtOrderMapping etOrderMapping;
        EtOrderMapping om;
        if (internetSerialNumber != null) {
            om = new EtOrderMapping();
            om.setEvcsOrderNo(internetSerialNumber);
            Example<EtOrderMapping> example = Example.of(om);
            etOrderMapping = orderMappingRepository.findOne(example).orElse(null);
            if (etOrderMapping == null) {
                om.setXhOrderNo(xhOrderNo);
                etOrderMapping = orderMappingRepository.save(om);
            }
        } else {
            om = new EtOrderMapping();
            om.setXhOrderNo(xhOrderNo);
            Example<EtOrderMapping> example = Example.of(om);
            etOrderMapping = orderMappingRepository.findOne(example).orElse(null);
            if (etOrderMapping == null) {
                etOrderMapping = new EtOrderMapping();
                etOrderMapping.setXhOrderNo(xhOrderNo);
                etOrderMapping.setEvcsOrderNo(transferInternetOrderNo(xhOrderNo, operatorId));
                etOrderMapping = orderMappingRepository.save(etOrderMapping);
            }
        }
        return etOrderMapping;
    }

    public static void main(String[] args) {
        String operatorId ="MA6DFCTD5";
        String orderNo ="80836000100002022410110921367394";
        System.out.println(operatorId.concat(DateUtil.getYYYY()).concat(orderNo.substring(18)));
    }
}
