package com.zd.laboratory.socket.service.impl;

import com.zd.laboratory.socket.constant.JXCTPacket;
import com.zd.laboratory.socket.exception.AnalysisException;
import com.zd.laboratory.socket.service.BaseRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author liubo
 *  执行结果
 */
@Service
public class CommandResult implements BaseRouter {
    private static Logger log = LoggerFactory.getLogger(CommandResult.class);

    public CommandResult() {
        routerMap.put("01", this);
    }

    @Override
    public String routePacket(JXCTPacket tracketPacket) throws AnalysisException {

        int count = Integer.parseInt(tracketPacket.deviceNumber.substring(0, 2), 16);
        //        继电器位号，2字节，0x03ff=0b001111111111，按位表示继电器状态，最低位表示第1号继电器，为0表示当前关闭，为1表示当前开启
        if (tracketPacket.body.length() < 10) {
            throw new AnalysisException("继电器上报状态错误");
        }
        //  指令操作反馈，1字节，（0-操作成功，1--操作失败）
        String result = tracketPacket.body.substring(0, 2);
        //        冲突逻辑位号，2字节，（0b0000开头，后12位,以最低位表示第1条互斥逻辑，置1表示该条逻辑冲突，操作标志为2时无意义），暂时不用，将会返回两字节0
        String mutex = tracketPacket.body.substring(2, 6);
        //当前继电器状态，2字节，0x03ff=0b001111111111，按位表示继电器状态，最低位表示第1号继电器，置0表示当前开，置1表示当前关
        String state = tracketPacket.body.substring(6, 10);

        if ("00".equals(result)) {
            log.info(tracketPacket.deviceNumber + " 01 指令执行成功");
            //更新继电器状态
            if (tracketPacket.body.length() > 21) {
                tracketPacket.body = state + tracketPacket.body.substring(10, 22);
            } else {
                log.info(tracketPacket.deviceNumber + " 改设备没上报时间");
                tracketPacket.body = state;
            }
            return BaseRouter.routerMap.get("00").routePacket(tracketPacket);

        } else {
            log.info(tracketPacket.deviceNumber + " 01 指令执行失败");
        }

        return null;
    }
}
