package com.jsowell.netty.handler;

import com.google.common.primitives.Bytes;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import com.jsowell.common.core.domain.ykc.YKCFrameTypeCode;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.netty.factory.YKCOperateFactory;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileConnectorInfoService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 充电桩心跳包
 */
@Slf4j
@Component
public class HeartbeatRequestHandler extends AbstractHandler {

	private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.HEART_BEAT_CODE.getBytes());

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private IPileBasicInfoService pileBasicInfoService;

	@Autowired
	private IPileConnectorInfoService pileConnectorInfoService;

	@Override
	public void afterPropertiesSet() throws Exception {
		YKCOperateFactory.register(type, this);
	}

	@Override
	public byte[] supplyProcess(YKCDataProtocol ykcDataProtocol, Channel channel) {
		// log.info("[===充电桩心跳包===] param:{}, channel:{}", JSONObject.toJSONString(ykcDataProtocol), channel.toString());
		// 获取消息体
		byte[] msgBody = ykcDataProtocol.getMsgBody();

		int startIndex = 0;
		int length = 7;

		// 桩号
		byte[] pileSnByte = BytesUtil.copyBytes(msgBody, startIndex, length);
		String pileSn = BytesUtil.binary(pileSnByte, 16);

		// 保存时间
		saveLastTime(pileSn);

		// 枪号
		startIndex += length;
		length = 1;
		byte[] pileConnectorNumByte = BytesUtil.copyBytes(msgBody, startIndex, length);
		String pileConnectorNum = String.format("%02d", Integer.parseInt(BytesUtil.binary(pileConnectorNumByte, 16)));

		//枪状态（不回复）
		startIndex += length;
		length = 1;
		byte[] connectorStatusByte = BytesUtil.copyBytes(msgBody, startIndex, length);
		String connectorStatus = BytesUtil.binary(connectorStatusByte, 16);
		// log.info("桩号：{}, 枪号：{}, 枪状态：{}", pileSn, pileConnectorNum, connectorStatus);

		// updateStatus(pileSn, pileConnectorNum, connectorStatus);

		// 公共方法修改状态
		pileBasicInfoService.updateStatus(BytesUtil.bcd2Str(ykcDataProtocol.getFrameType()), pileSn, pileConnectorNum, connectorStatus, null);

		// 心跳应答（置0）
		byte[] flag = Constants.zeroByteArray;

		// 消息体
		byte[] messageBody = Bytes.concat(pileSnByte, pileConnectorNumByte, flag);
		return getResult(ykcDataProtocol, messageBody);
	}

}
