package com.xhpc.pp.logic;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.common.data.up.PileConfigReplyData;
import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.mapper.XhpcDeviceMessageMapper;
import com.xhpc.pp.tx.ServiceParameter;
import com.xhpc.pp.tx.ServiceResult;
import com.xhpc.pp.tx.logic.ServiceLogic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.tx.ServiceResult.*;

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

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

    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

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

        Map<String, Object> req = sp.getParameters();
        ObjectMapper objectMapper = new ObjectMapper();
        PileConfigReplyData pileRateModelConfigReplyData = objectMapper.convertValue(req, PileConfigReplyData.class);
        String configResult = pileRateModelConfigReplyData.getConfigResult();

        String result = FAIL;
        if (HEX_01.equals(configResult)) {
//            确定设置成功的rateModelId 可能涉及协议修改
            final String pkey = "pile:".concat(pileRateModelConfigReplyData.getPileNo());
            Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
            ChargingStationDto cacheStation = REDIS.getCacheObject("station:".concat(cachePile.get("stationId").toString()));
            cachePile.put("rateModelId", cacheStation.getRateModelId());
            REDIS.setCacheMap(pkey, cachePile);
            result = OK;
        }

        String remark = "充电桩收到计费模型应答";
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(sp.getPileNo());
        deviceMessage.setRemark(remark);
        deviceMessage.setStatus(0);
        deviceMessage.setContent((String) req.get("hex"));
        deviceMessageMapper.insertByDomain(deviceMessage);

        return new ServiceResult(result);
    }

}
