package com.xhpc.pp.logic;

import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.pp.mapper.XhpcDeviceMessageMapper;
import com.xhpc.pp.server.ChargingPileServer;
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.quickserver.net.server.ClientHandler;
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.Calendar;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.common.data.redis.StaticBeanUtil.seqHex;

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

    private static final Logger log = LoggerFactory.getLogger(HBLogic.class);
    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;
    public static final String[] stable = {"空闲", "故障"};

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

        Map<String, Object> req = sp.getParameters();
        String pileNo = (String) req.get("pileNo");
        String gunId = (String) req.get("gunId");
        Integer gunStatus = (Integer) req.get("gunStatus");
        String gunkey = "gun:".concat(pileNo).concat(gunId);
        Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
        cacheGun.put("hbtime", Calendar.getInstance().getTimeInMillis());
        String status = (String) cacheGun.get("status");
        if ("离线".equals(status) || "故障".equals(status)) {
            cacheGun.put("status", stable[gunStatus]);
        }
        ClientHandler handler = ChargingPileServer.getHandler(pileNo);
        if (handler == null) return new ServiceResult(ServiceResult.FAIL);
        REDIS.setCacheMap(gunkey, cacheGun);
        String skey = gunkey.concat(".seqhex");
        //String seq = seqHex(skey);
        String seq =(String) req.get("hex");

        String resultStr = "680D".concat(seq.substring(4,8)).concat("0004").concat(pileNo).concat(gunId).concat(ServiceResult.HEX_00);
        resultStr = resultStr.concat(CRCCalculator.calcCrc(resultStr));


        // 写入设备日志表数据
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(pileNo);
        deviceMessage.setRemark("充电桩心跳");
        deviceMessage.setStatus(0);
        deviceMessage.setContent((String) req.get("hex"));
        deviceMessageMapper.insertByDomain(deviceMessage);


        return new ServiceResult(HexUtils.toBytes(resultStr), ServiceResult.OK);
    }

}
