package com.xhpc.evcs.cdjgpc.notification;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.common.data.redis.CacheRealtimeData;
import com.xhpc.evcs.cdjgpc.dto.CDConnectorChargeStatusInfo;
import com.xhpc.evcs.cdjgpc.dto.CDStationInfo;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.XhpcStationInternetBlacklist;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.ConnectorStatusInfoReq;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcStationInternetBlacklistRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.*;

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

@Component
@Slf4j
public class CDConnectorChargeStatusInfoTask extends CoreDispatcher {

    @Resource
    AuthSecretTokenRepository authSecretTokenRepository;
    @Resource
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    private final Logger logger = LoggerFactory.getLogger(CDConnectorChargeStatusInfoTask.class);

    //9099开放定时任务  9009不开放
    /**
     * 清除5天前数据
     * 实时数据没40秒
     */
    //@Scheduled(fixedDelay = 1000 * 60)
    public void runY() throws Exception{
        Collection<String> realtimeOrder = REDIS.keys("cdjgpc:realTime:*");
        for (String okey : realtimeOrder) {
            String orderNo = REDIS.getCacheObject(okey);
            String format = DateUtil.format(DateUtil.offsetDay(new Date(),-7), "yyMMdd");
            if(Integer.parseInt(format)>Integer.parseInt(orderNo.substring(16,22))){
                REDIS.deleteObject(okey);
            }
        }
    }
    /**
     * 清除7天前数据
     * 实时数据没40秒
     */
    //@Scheduled(fixedDelay = 1000 * 60)
    public void runS() throws Exception{
        Collection<String> realtimeOrder = REDIS.keys("RealtimeOrder:*");
        for (String okey : realtimeOrder) {
            String orderNo = REDIS.getCacheObject(okey);
            String format = DateUtil.format(DateUtil.offsetDay(new Date(),-7), "yyMMdd");
            if(Integer.parseInt(format)>Integer.parseInt(orderNo.substring(16,22))){
                REDIS.deleteObject(okey);
            }
        }
    }
    //9099开放定时任务  9009不开放
    /**
     * 清除5天前数据
     * 实时数据没40秒
     */
    //@Scheduled(fixedDelay = 1000 * 120)
    public void runYu() throws Exception{
        Collection<String> realtimeOrder = REDIS.keys("orderOutpu:*");
        for (String okey : realtimeOrder) {
            String format = DateUtil.format(DateUtil.offsetDay(new Date(),-30), "yyMMdd");
            if(Integer.parseInt(format)>Integer.parseInt(okey.substring(28,33))){
                REDIS.deleteObject(okey);
            }
        }
    }


    //9099开放定时任务  9009不开放
    //@Scheduled(fixedDelay = 1000 * 120)
    public void runYu1() throws Exception{
        Collection<String> realtimeOrder = REDIS.keys("Yu80836000*");
        for (String okey : realtimeOrder) {
            String format = DateUtil.format(DateUtil.offsetDay(new Date(),-30), "yyMMdd");
            if(Integer.parseInt(format)>Integer.parseInt(okey.substring(18,24))){
                REDIS.deleteObject(okey);
            }
        }
    }

    //9099开放定时任务  9009不开放
    //@Scheduled(fixedDelay = 1000 * 120)
    public void orderKeys() throws Exception{
        Collection<String> orderKeys = REDIS.keys("order:*");
        Instant now = Instant.now();
        for (String okey : orderKeys) {
            String orderNo = okey.substring(6);
            if(orderNo.length() < 32){
                logger.error("orderNo[{}] is error", orderNo);
                continue;
            }
            Date otime = com.xhpc.evcs.utils.DateUtil.orderNo2Date(orderNo);
            if (Duration.between(otime.toInstant(), now).toHours() > 24 * 30) {
                REDIS.deleteObject(okey);
                REDIS.deleteObject(okey.replace("order", "pushOrder"));
                logger.info("clear cache..{}", okey);
            }
        }
    }



    //9099开放定时任务  9009不开放
    /**
     * 设备充电中状态变化推送(我们平台推送成都市平台)  --已推送
     * 实时数据没40秒
     */
    //@Scheduled(fixedDelay = 1000 * 120)
    public void run() throws Exception{

        List<Long> longList =new ArrayList<>();

        List<XhpcStationInternetBlacklist> list = xhpcStationInternetBlacklistRepo.findByInternetUserId(6L);
        for (int i = 0; i <list.size() ; i++) {
            XhpcStationInternetBlacklist xhpcStationInternetBlacklist = list.get(i);
            Long chargingStationId = xhpcStationInternetBlacklist.getChargingStationId();
            longList.add(chargingStationId);
        }

        Collection<String> realtimeOrder = REDIS.keys("cdjgpc:realTime:*");

        for (String okey : realtimeOrder) {
            try {
                String orderNo = REDIS.getCacheObject(okey);
                if(orderNo.equals("00000000000000000000000000000000")){
                    REDIS.deleteObject(okey);
                    continue;
                }
                String key = "pile:"+orderNo.substring(0,14);
                Map<String, Object> cachePile = REDIS.getCacheMap(key);
                String stationId = cachePile.get("stationId").toString();
                boolean falen =false;
                if(longList.size()>0){
                    for (int i = 0; i <longList.size() ; i++) {
                        if(stationId.equals(longList.get(i).toString())){
                            REDIS.deleteObject(okey);
                            falen =true;
                        }
                    }
                }
                if(falen){  continue;}
                CacheRealtimeData lord = REDIS.getCacheObject("order:"+orderNo+".lord");
                if(lord ==null){
                    REDIS.deleteObject(okey);
                    continue;
                }
                String formatTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                Map<String, Object> cacheMap =REDIS.getCacheMap("order:"+orderNo+".notification");
                if(cacheMap==null || cacheMap.get("startTime")==null || "".equals(cacheMap.get("startTime"))){
                    cacheMap.put("lastPushTime", formatTime);
                }else{
                    cacheMap.put("lastPushTime", cacheMap.get("pushTime"));
                }
                cacheMap.put("pushTime", formatTime);
                CDConnectorChargeStatusInfo cdConnectorChargeStatusInfo = new CDConnectorChargeStatusInfo();
                Map<String, Object> cacheMapOrder = REDIS.getCacheMap("order:"+orderNo);
                if(cacheMap.get("startTime")==null ){
                    if(cacheMapOrder !=null && cacheMapOrder.get("startTime")!=null){
                        cdConnectorChargeStatusInfo.setStartTime(cacheMapOrder.get("startTime").toString());
                        cacheMap.put("startTime", cacheMapOrder.get("startTime").toString());
                    }
                }else{
                    cdConnectorChargeStatusInfo.setStartTime(cacheMap.get("startTime").toString());
                }
                if(cacheMapOrder !=null && cacheMapOrder.get("status")!=null){
                    if("已结束".equals(cacheMapOrder.get("status").toString())){
                        cdConnectorChargeStatusInfo.setConnectorStatus(1);
                        cdConnectorChargeStatusInfo.setOrderStatus(4);
                    }else{
                        cdConnectorChargeStatusInfo.setConnectorStatus(3);
                        cdConnectorChargeStatusInfo.setOrderStatus(2);
                    }
                }
                REDIS.setCacheMap("order:"+orderNo+".notification",cacheMap);
                cdConnectorChargeStatusInfo.setStartChargeSeq(lord.getOrderNo());
                cdConnectorChargeStatusInfo.setConnectorID(lord.getPileNo()+lord.getGunId());
                cdConnectorChargeStatusInfo.setCurrentA((double)(lord.getWorkingCurrent()/10));
                cdConnectorChargeStatusInfo.setVoltageA((double)(lord.getWorkingVoltage()/10));
                cdConnectorChargeStatusInfo.setSoc((double)lord.getSoc());
                cdConnectorChargeStatusInfo.setEndTime(formatTime);
                cdConnectorChargeStatusInfo.setPushTime(formatTime);
                cdConnectorChargeStatusInfo.setLastPushTime(cacheMap.get("lastPushTime").toString());
                BigDecimal chargingDegree = new BigDecimal(lord.getChargingDegree()).divide(new BigDecimal(10000).setScale(2, BigDecimal.ROUND_UP));
                BigDecimal amountCharged = new BigDecimal(lord.getAmountCharged()).divide(new BigDecimal(10000).setScale(2, BigDecimal.ROUND_UP));
                cdConnectorChargeStatusInfo.setTotalPower(chargingDegree.doubleValue());
                cdConnectorChargeStatusInfo.setTotalMoney(amountCharged.doubleValue());


                cdConnectorChargeStatusInfo.setEquipmentID(orderNo.substring(0,14));
                cdConnectorChargeStatusInfo.setStationID(stationId);

                String stationSey = "cdjgpc:station:".concat(stationId)+".notification";
                CDStationInfo cdStationInfo =REDIS.getCacheObject(stationSey);
                cdConnectorChargeStatusInfo.setOperatorID(cdStationInfo.getOperatorId());
                cdConnectorChargeStatusInfo.setEquipmentOwnerID(cdStationInfo.getEquipmentOwnerId());


                Map<String, Object> cacheOrder = REDIS.getCacheMap("order:" + orderNo);

                if(cacheOrder !=null && cacheOrder.get("rateModelId") !=null){
                    CacheRateModel rateModel = REDIS.getCacheObject("rateModel:" + cacheOrder.get("rateModelId").toString());
                    if(rateModel.getT1SvcPrice().equals(rateModel.getT2SvcPrice()) && rateModel.getT3SvcPrice().equals(rateModel.getT4SvcPrice()) &&
                            rateModel.getT1SvcPrice().equals(rateModel.getT3SvcPrice())){

                        BigDecimal divide = new BigDecimal(rateModel.getT1SvcPrice()).divide(new BigDecimal(100000)).setScale(2, BigDecimal.ROUND_UP);

                        BigDecimal bigDecimal = chargingDegree.multiply(divide).setScale(2, BigDecimal.ROUND_UP);
                        cdConnectorChargeStatusInfo.setSeviceMoney(bigDecimal.doubleValue());
                        BigDecimal subtract = amountCharged.subtract(bigDecimal);
                        cdConnectorChargeStatusInfo.setElecMoney(subtract.doubleValue());
                    }else{
                        //暂时不考虑不同服务费 默认为0.2
                        BigDecimal multiply = chargingDegree.multiply(new BigDecimal(0.2)).setScale(2, BigDecimal.ROUND_UP);;
                        cdConnectorChargeStatusInfo.setSeviceMoney(multiply.doubleValue());
                        BigDecimal subtract = amountCharged.subtract(multiply);
                        cdConnectorChargeStatusInfo.setElecMoney(subtract.doubleValue());
                    }
                    AuthSecretToken authSecretTokenOut = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType("MA6CC2LK7", SECRET_TOKEN_TYPE_OUT).orElse(null);
                    Map<String, Object> map =new HashMap<>();
                    map.put("ConnectorChargeStatusInfo",cdConnectorChargeStatusInfo);
                    String data = JSONUtil.toJSONString(map);
                    CommonRequest<ConnectorStatusInfoReq> commonRequest = new CommonRequest<>();
                    commonRequest.setData(data);
                    String result = ok(commonRequest, "/notification_connector_charge_status", authSecretTokenOut);
                    //System.out.println("===设备充电中状态变化推送====lord.getOrderNo()========"+lord.getOrderNo());
                    //System.out.println("===设备充电中状态变化推送====result========"+result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if("0".equals(jsonObject.get("Ret").toString())){
                       // System.out.println("===设备充电中状态变化推送====okey========"+okey);
                        REDIS.deleteObject(okey);
                    }
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String num =" orderOutpu:80836000030006012409021226448679";
        String format = DateUtil.format(DateUtil.offsetDay(new Date(),-3), "yyMMdd");
        System.out.println(format);
        System.out.println(num.substring(28,33));
        if(Integer.parseInt(format)>Integer.parseInt(num.substring(27,33))){
            System.out.println("==============");
        }else{
            System.out.println("=======4444=======");
        }

    }


}
