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 AttributeResult implements BaseRouter {
    private static Logger log = LoggerFactory.getLogger(AttributeResult.class);

    public AttributeResult() {
        routerMap.put("04", this);
    }

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


        //指令1字节
        String command = tracketPacket.body.substring(0, 2);
        if ("00".equals(command)) {//配置指令字返回
            //配置继电器属性反馈的标志，1字节，（0-操作成功，1-操作失败）
            String result = tracketPacket.body.substring(2, 4);
            log.info(tracketPacket.deviceNumber + " 配置结果：" + result);
            if ("00".equals(result)) {
                log.info("属性保护时间配置成功");
            } else {
                log.info("属性保护时间配置失败");
            }

        } else if ("01".equals(command)) {//清空继电器属性返回
            //配置继电器属性反馈的标志，1字节，（0-操作成功，1-操作失败）
            String result = tracketPacket.body.substring(2, 4);
            log.info(tracketPacket.deviceNumber + " 属性反馈：" + result);
        } else if ("02".equals(command)) {//问询继电器属性返回
            //继电器位号，2字节，但一次只有1位置1
            String positoin = tracketPacket.body.substring(2, 8);
            //前保护时间，1字节，单位：秒
            String beforeTime = tracketPacket.body.substring(8, 10);
            //后保护时间，1字节，单位：秒
            String afterTime = tracketPacket.body.substring(10, 12);

            int pos = Integer.parseInt(positoin, 16);
            int before = Integer.parseInt(beforeTime, 16);
            int after = Integer.parseInt(afterTime, 16);
            if ((pos & 0xffff) == 0) {//全部问询
                for (int i = 0; i < 16; i++) {
                    //前保护时间，1字节，单位：秒
                    beforeTime = tracketPacket.body.substring(8 + i * 2, 10 + i * 2);
                    //后保护时间，1字节，单位：秒
                    afterTime = tracketPacket.body.substring(10 + i * 2, 12 + i * 2);
                    before = Integer.parseInt(beforeTime, 16);
                    after = Integer.parseInt(afterTime, 16);
                    log.info("继电器位号:" + (i + 1) + " > " + pos + "  前保护时间:" + beforeTime + " > " + before + "  后保护时间:" + afterTime + " > " + after);
                }
            } else {//非全部问询
                log.info("继电器位号:" + positoin + " > " + pos + "  前保护时间:" + beforeTime + " > " + before + "  后保护时间:" + afterTime + " > " + after);
            }
        }
        return null;
    }
}
