package com.xhpc.pp.logic;

import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.pp.tx.ServiceParameter;
import com.xhpc.pp.tx.ServiceResult;
import com.xhpc.pp.tx.logic.ServiceLogic;
import com.xhpc.pp.utils.HexUtils;
import com.xhpc.pp.utils.security.CRCCalculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;

import static cn.hutool.core.util.NumberUtil.isInteger;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.common.data.redis.StaticBeanUtil.seqHex;

@Lazy
@Component("RateModelValidateLogic")
public class RateModelValidateLogic implements ServiceLogic {

    private static Logger log = LoggerFactory.getLogger(RateModelValidateLogic.class);

    @Override
    public ServiceResult service(ServiceParameter sp) throws Exception {

        Map<String, Object> req = sp.getParameters();
        String pileNo = (String) req.get("pileNo");
        String rateModelIdStr = (String) req.get("rateModelId");
        Map<String, Object> cachePile = REDIS.getCacheMap("pile:".concat(pileNo));
        Integer gunNum = (Integer) cachePile.get("gunNum");
        boolean charging = false;
        for (int gunN = 1; gunN <= gunNum; gunN++) {
            String gunId = String.format("%02d", gunN);
            String gunkey = "gun:".concat(pileNo.concat(gunId));
            Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
            Object status = cacheGun.get("status");
            if (isInteger(status.toString())) {
                charging = true;
            }
        }
        String resultCode = ServiceResult.OK;
        String hexCode = ServiceResult.HEX_00;
        Long rateModelId = Long.valueOf(Integer.parseInt(rateModelIdStr, 16));
        Long csRateModelId = rateModelId;
        if (!charging) {
            ChargingStationDto cacheStation = REDIS.getCacheObject("station:".concat(cachePile.get("stationId").toString()));
            csRateModelId = cacheStation.getRateModelId();
            if (csRateModelId.intValue() != rateModelId) {
                hexCode = ServiceResult.HEX_01;
                resultCode = ServiceResult.FAIL;
            }
        }
        String skey = "pile:".concat(pileNo).concat(".seqhex");
        String seq = seqHex(skey);
        String resultStr =
                "680E".concat(seq).concat("0006").concat(pileNo).concat(String.format("%04X", csRateModelId)).concat(hexCode);
        resultStr = resultStr.concat(CRCCalculator.calcCrc(resultStr));
        return new ServiceResult(HexUtils.toBytes(resultStr), resultCode);
    }

}
