package com.njzscloud.common.localizer.jt808.message;

import cn.hutool.core.date.DateUtil;
import com.njzscloud.common.core.utils.BCD;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@Getter
@Setter
@ToString
@Accessors(chain = true)
public class LocationReportMessage {
    /**
     * 1 1：超速报警 标志维持至报警条件解除
     * 7 1：终端主电源欠压 标志维持至报警条件解除
     * 8 1:声控录音报警
     */
    private long alarmFlag;
    /**
     * 0  0：ACC 关 1：ACC 开
     * 1 0：未定位 1：定位
     * 2  0：北纬 1：南纬
     * 3 0：东经 1：西经
     */
    private long status;
    /**
     * 经度
     */
    private double longitude;
    /**
     * 纬度
     */
    private double latitude;
    /**
     * 海拔
     */
    private int altitude;
    /**
     * 速度
     */
    private double speed;
    /**
     * 方向
     */
    private int direction;
    /**
     * 时间
     */
    private String time;

    /**
     * 是否超速
     */
    private boolean overspeed;
    /**
     * 是否主电源欠压
     */
    private boolean powerUnderVoltage;
    /**
     * 是否声控录音报警
     */
    private boolean soundAlarm;
    /**
     * 是否 ACC 开
     */
    private boolean accOn;
    /**
     * 是否定位
     */
    private boolean position;
    /**
     * 是否南纬
     */
    private boolean south;
    /**
     * 是否西经
     */
    private boolean west;

    public LocationReportMessage(ByteBuf body) {
        this.alarmFlag = body.readUnsignedInt();
        this.status = body.readUnsignedInt();
        double latitude = body.readUnsignedInt() * 1.0 / 1000000;
        this.latitude = isWest() ? -latitude : latitude;
        double longitude = body.readUnsignedInt() * 1.0 / 1000000;
        this.longitude = isSouth() ? -longitude : longitude;
        this.altitude = body.readUnsignedShort();
        this.speed = body.readUnsignedShort() * 1.0 / 10;
        this.direction = body.readUnsignedShort();
        byte[] terminalIdBytes = new byte[6];
        body.readBytes(terminalIdBytes);
        this.time = DateUtil.format(DateUtil.parse(BCD.bcdToStr(terminalIdBytes), "yyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss");
        this.overspeed = (alarmFlag & 0x02) == 0x02;
        this.powerUnderVoltage = (alarmFlag & 0x40) == 0x40;
        this.soundAlarm = (alarmFlag & 0x80) == 0x80;
        this.accOn = (status & 0x01) == 0x01;
        this.position = (status & 0x02) == 0x02;
        this.south = (status & 0x04) == 0x04;
        this.west = (status & 0x08) == 0x08;
    }
}
