package com.xhpc.evcs.cwj.notification;

import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.common.domain.XhpcTerminal;
import com.xhpc.evcs.cdjgpc.dto.CDConnectorStatusInfo;
import com.xhpc.evcs.cdjgpc.dto.CDConnectorStatusInfoReq;
import com.xhpc.evcs.cdjgpc.dto.CDStationInfo;
import com.xhpc.evcs.cwj.dto.CWJConnectorStatusInfo;
import com.xhpc.evcs.cwj.dto.CWJConnectorStatusInfoReq;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.XhpcInternetUser;
import com.xhpc.evcs.domain.XhpcStationInternetBlacklist;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.ConnectorStatusInfo;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcInternetUserRepository;
import com.xhpc.evcs.jpa.XhpcStationInternetBlacklistRepository;
import com.xhpc.evcs.jpa.XhpcTerminalRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.ChangePoleStatus;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.domain.AuthSecretToken.SECRET_TOKEN_TYPE_OUT;
import static com.xhpc.evcs.dto.ConnectorStatusInfo.*;
import static com.xhpc.evcs.dto.ConnectorStatusInfo.CHARGING;

/**
 * @author yuyang
 * @Date 2025-07-16 11:06
 */
@Component
@Slf4j
public class CWJNotificationStationStatusTask extends CoreDispatcher {

    @Autowired
    private AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private XhpcInternetUserRepository xhpcInternetUserRepository;
    @Autowired
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    @Resource
    private XhpcTerminalRepository terminalRepository;
    //9099开放定时任务  9009不开放
    //@Scheduled(fixedRate = 1000 * 60)
    protected void run() throws IOException {

        Collection<String> stationTerminalKeys = REDIS.keys("stationTerminalStatus:*");

        List<XhpcTerminal> terminalList = terminalRepository.selectStatusBySql();
        Map<String,Integer> terminalDBMap = terminalList.stream().collect(Collectors.toMap(XhpcTerminal::getSerialNumber,XhpcTerminal::getStatus));

        Instant now = Instant.now();

        XhpcInternetUser xhpcInternetUser =xhpcInternetUserRepository.findByOperatorIdEvcsLikeAndCooperationStartTimeBeforeAndCooperationEndTimeAfter("MA7D6FPW6", Instant.now(), Instant.now());

        for (String stationTerminalKey : stationTerminalKeys) {
            ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationTerminalKey.replace("stationTerminalStatus",
                    "station"));
            String operatorId = chargingStationDto.getOperatorId();
            Map<String, String> terminalStatusMap = REDIS.getCacheMap(stationTerminalKey);
            Set<ConnectorStatusInfo> connectorStatusInfos = translateStatus(operatorId, terminalStatusMap, terminalDBMap);
            Set<ConnectorStatusInfo> changeStatus = ChangePoleStatus.getChangeStatus(connectorStatusInfos);
            if (!changeStatus.isEmpty()) {
                XhpcStationInternetBlacklist xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByChargingStationIdAndInternetUserId(Long.valueOf(stationTerminalKey.split(":")[1]),
                                xhpcInternetUser.getInternetUserId()).orElse(null);
                if (xhpcStationInternetBlacklist != null) continue;
                AuthSecretToken authSecretTokenOut =authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType("MA7D6FPW6", SECRET_TOKEN_TYPE_OUT).orElse(null);
                log.debug("nss pushing to: {}", "MA7D6FPW6");
                if (authSecretTokenOut != null) {
                    for (ConnectorStatusInfo statusInfo : changeStatus) {
                        notify(stationTerminalKey,statusInfo, authSecretTokenOut);
                    }
                }
            }
        }
    }

    private Set<ConnectorStatusInfo> translateStatus(String operatorId, Map<String, String> terminalStatusMap, Map<String, Integer> terminalDBMap) {

        Set<ConnectorStatusInfo> connectorStatusInfoList = new HashSet<>();
        final Set<String> connectorIds = terminalStatusMap.keySet();
        for (String gunId : connectorIds) {
            ConnectorStatusInfo connectorStatusInfo = new ConnectorStatusInfo();
            connectorStatusInfo.setConnectorID(gunId);
            connectorStatusInfo.setOperatorID(operatorId);
            Integer dbStatus = terminalDBMap.get(gunId);
            if(dbStatus !=null && dbStatus == 0){
                connectorStatusInfo.setStatus(translateStatus(terminalStatusMap.get(gunId)));
            } else {
                connectorStatusInfo.setStatus(0);
            }
            connectorStatusInfoList.add(connectorStatusInfo);
        }
        return connectorStatusInfoList;
    }

    private Integer translateStatus(String statusStr) {

        switch (statusStr) {
            case "空闲":
                return FREE;
            case "离线":
                return OFF_LINE;
            case "插枪":
                return CONNECTED;
            case "故障":
                return ERROR;
            default:
                return CHARGING;
        }
    }

    public void notify(String stationTerminalKey,ConnectorStatusInfo connectorStatusInfo, AuthSecretToken authSecretTokenOut) throws IOException {

        CWJConnectorStatusInfoReq connectorStatusInfoReq = new CWJConnectorStatusInfoReq();

        //System.out.println("=========stationTerminalKey=========="+stationTerminalKey+"======ConnectorID======="+connectorStatusInfo.getConnectorID());
        String key =stationTerminalKey.replace("stationTerminalStatus","cdjgpc:station")+".notification";
        // System.out.println("=========key=========="+key);
        CDStationInfo cdStationInfo =REDIS.getCacheObject(key);
        CWJConnectorStatusInfo cdConnectorStatusInfo =new CWJConnectorStatusInfo();

        cdConnectorStatusInfo.setConnectorID(connectorStatusInfo.getConnectorID());
        cdConnectorStatusInfo.setStatus(connectorStatusInfo.getStatus());

        connectorStatusInfoReq.setConnectorStatusInfo(cdConnectorStatusInfo);
        String data = JSONUtil.toJSONString(connectorStatusInfoReq);
        CommonRequest<CDConnectorStatusInfoReq> commonRequest = new CommonRequest<>();
        commonRequest.setData(data);
        String result = ok(commonRequest, "/notification_stationStatus", authSecretTokenOut);

        System.out.println("==车为家=设备状态变化推送====result========"+result);

    }







}
