package com.xhpc.pp.server;

import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.pp.logic.RateModelRequestLogic;
import com.xhpc.pp.utils.HexUtils;
import lombok.extern.slf4j.Slf4j;
import org.quickserver.net.server.ClientHandler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.Set;

import static cn.hutool.core.util.NumberUtil.isInteger;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.server.ChargingPileServer.getHandler;

@Slf4j
@Component
public class RateModelTask {

    //111@Scheduled(fixedRate = 10000)
    protected void run() {

        Collection<String> stationKeys = REDIS.keys("station:*");
        for (String stationKey : stationKeys) {
            ChargingStationDto stationDto = REDIS.getCacheObject(stationKey);
            Long rateModelIdStation = stationDto.getRateModelId();
            if (rateModelIdStation != null) {
                Set<String> pks = stationDto.getPiles();
                if (pks != null) for (String pileNo : pks) {
                    String pk = "pile:".concat(pileNo);
                    Long rateModelIdPile = REDIS.getCacheMapValue(pk, "rateModelId");
                    if (!rateModelIdStation.equals(rateModelIdPile)) {
                        String gkPattern = ("gun:").concat(pileNo).concat("*");
                        Collection<String> gks = REDIS.keys(gkPattern);
                        boolean charging = false;
                        for (String gk : gks) {
                            if (gk.length() == 20 && isInteger(REDIS.getCacheMapValue(gk, "status"))) {
                                charging = true;
                                break;
                            }
                        }
                        if (!charging) {
                            ClientHandler handler = getHandler(pileNo);
                            if (handler != null && handler.isOpen()) {
                                String rsmsg = RateModelRequestLogic.translate(pileNo, rateModelIdStation, "0058",
                                        REDIS.getCacheMapValue(pk, "version"));
                                try {
                                    handler.sendClientBinary(HexUtils.toBytes(rsmsg));
                                    log.info("pile[{}] rate model[{}] sent ⚪ {}", pileNo, rateModelIdStation, rsmsg);
                                } catch (IOException e) {
                                    log.error("pile[{}] rate model[{}] not sent ×", pileNo, rateModelIdStation);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
