package com.xhpc.evcs.cdjgpc.notification;

import cn.hutool.core.date.DateUtil;
import com.xhpc.common.data.redis.CacheBmsReqChargerOutputData;
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.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcStationInternetBlacklistRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.cdjgpc.domain.XhpcChargeOrder;
import com.xhpc.evcs.cdjgpc.dto.CDStationPowerlnfo;
import com.xhpc.evcs.cdjgpc.jpa.XhpcChargeOrderRepository;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

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

/**
 * 充电站实时负荷信息推送
 *
 * @author yuyang
 * @Date 2024-08-16 13:57
 */
@Component
@Slf4j
public class CDNotificationStationPowerInfoTask extends CoreDispatcher {
    @Resource
    AuthSecretTokenRepository authSecretTokenRepository;
    @Resource
    XhpcChargeOrderRepository xhpcChargeOrderRepository;
    @Resource
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;

    private final Logger logger = LoggerFactory.getLogger(CDNotificationStationPowerInfoTask.class);

    //不推送
    //@Scheduled(cron = "0 0/1 * * * ? ")
    public void run() throws IOException {
        //不参与合作的电站
        List<XhpcStationInternetBlacklist> xhpcStationInternetBlacklist =xhpcStationInternetBlacklistRepo.findByInternetUserId(6L);
        List<String> stationKeys = new ArrayList<>(REDIS.keys("station:*"));

        AuthSecretToken authSecretTokenOut =
                authSecretTokenRepository.findByOperatorId3irdptyAndOperatorIdAndSecretTokenType(
                        "MA6CC2LK7", "MA6DFCTD5", SECRET_TOKEN_TYPE_OUT).orElse(null); //todo

        for (String stationKey : stationKeys) {
            //查询不合作的电桩
            for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                if (!stationKey.substring(8).equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                    // maybe对接第三方
                    if (authSecretTokenOut != null) {
                        String stationId = xhpcStationInternetBlack.getChargingStationId().toString();
                        //获取所有该场站充电中订单
                        List<XhpcChargeOrder> xhpcChargeOrderList = xhpcChargeOrderRepository.findByStatusAndDelFlagAndChargingStationIdOrderByChargingStationId(0, 0,xhpcStationInternetBlack.getChargingStationId());
                        //获取订单bms数据
                        BigDecimal bigDecimal1 = new BigDecimal(0);
                        for (int i = 0; i < xhpcChargeOrderList.size(); i++) {
                            XhpcChargeOrder xhpcChargeOrder = xhpcChargeOrderList.get(i);
                            String key = "order:".concat(xhpcChargeOrder.getSerialNumber())+".bms";
                            CacheBmsReqChargerOutputData bms = REDIS.getCacheObject(key);
                            BigDecimal bigDecimal = new BigDecimal(bms.getPileVoltageOutput()).multiply(new BigDecimal(bms.getPileCurrentOutput())).divide(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_CEILING);
                            bigDecimal1 = bigDecimal1.add(bigDecimal);
                        }

                        //获取场站信息
                        String key = "cdjgpc:station:".concat(stationId)+".notification";
                        CDStationInfo cdStationInfo =REDIS.getCacheObject(key);

                        CDStationPowerlnfo cdStationPowerlnfo = new CDStationPowerlnfo();
                        cdStationPowerlnfo.setStationID(stationId);
                        cdStationPowerlnfo.setOperatorID(cdStationInfo.getOperatorId());
                        cdStationPowerlnfo.setEquipmentOwnerID(cdStationInfo.getEquipmentOwnerId());
                        cdStationPowerlnfo.setEleNo(cdStationInfo.getAccountNumber());
                        cdStationPowerlnfo.setPower(bigDecimal1.doubleValue());

                        String format = DateUtil.format(new Date(), "yyyymmddhhmm");
                        cdStationPowerlnfo.setTsMin(format);
                        cdStationPowerlnfo.setTsHour(format.substring(0,10));
                        cdStationPowerlnfo.setTsDay(format.substring(0,8));
                        cdStationPowerlnfo.setTsMonth(format.substring(0,6));
                        cdStationPowerlnfo.setTsYear(format.substring(0,4));


                        CommonRequest<CDStationPowerlnfo> commonRequest = new CommonRequest<>();
                        Map<String,Object> mapStationInfo =new HashMap<>();
                        mapStationInfo.put("StationPowerInfo",cdStationPowerlnfo);
                        String data = JSONUtil.toJSONString(mapStationInfo);
                      //  System.out.println("=======data========"+data);
                        commonRequest.setData(data);
                        String result =ok(commonRequest,"/notification_stationPowerInfo",authSecretTokenOut);
                      //  System.out.println("=====充电站实时负荷信息推送==result========"+result);
                    }
                }
            }
        }
    }
}
