package com.imdroid.sideslope.service;

import com.imdroid.secapi.dto.*;
import com.imdroid.sideslope.message.BaseMessage;
import com.imdroid.sideslope.message.D342LocationMessage;
import com.imdroid.sideslope.message.D3F0SelfCheckMessage;
import com.imdroid.sideslope.message.D3F2StopIndicationMessage;
import com.imdroid.sideslope.sal.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 设备数据持久化实现
 *
 * @author LiGang
 */
@Service
public class DataPersistServiceImpl implements DataPersistService {

    @Autowired
    private GnssStatusMapper deviceStateRepository;

    @Autowired
    private GnssStatusMsgMapper statusMsgMapper;

    @Autowired
    private GnssTrxMsgMapper trxMsgMapper;
    @Autowired
    private GnssMsgMapper msgMapper;
    @Autowired
    WarningService warningService;

    @Override
    public GnssStatus getDeviceState(String deviceId)
    {
        return deviceStateRepository.getByDeviceId(deviceId);
    }

    @Override
    public void updateDeviceState(GnssStatus gnssStatus){
        deviceStateRepository.updateById(gnssStatus);
    }
    @Override
    public void saveDeviceState(D3F0SelfCheckMessage message) {
        try {
            // 保存到statusmsg数据表里
            GnssStatusMsg statusMsg = message.getStatusMsg();
            statusMsg.setTenantid(message.getTenantId());
            statusMsgMapper.insert(statusMsg);

            //新增或更新到status数据表里
            GnssStatus deviceState = deviceStateRepository.getByDeviceId(message.getId());
            boolean new_flag = false;
            if(null == deviceState) {
                deviceState = new GnssStatus();
                new_flag = true;
            }
            //deviceState.setId(SequenceUtil.getSequence());
            deviceState.setTenantid(message.getTenantId());
            deviceState.setDeviceid(message.getId());
            deviceState.setUpdatetime(statusMsg.getCreatetime());
            deviceState.setDevicetime(statusMsg.getDevicetime());
            deviceState.setRoll(statusMsg.getRoll());
            deviceState.setPitch(statusMsg.getPitch());
            deviceState.setYaw(statusMsg.getYaw());
            deviceState.setRssi(statusMsg.getRssi());
            deviceState.setVoltage(statusMsg.getVoltage());
            deviceState.setTemperature(statusMsg.getTemperature());
            deviceState.setHumidity(statusMsg.getHumidity());

            // 检测状态和告警
            deviceState.setState(GnssStatus.STATE_ACTIVE);
            warningService.checkDeviceStatus(statusMsg, deviceState);

            if(new_flag) deviceStateRepository.insert(deviceState);
            else deviceStateRepository.updateById(deviceState);

            // 保存消息摘要
            if(message.getImei()!=null) {
                saveMsg(message, "IMEI:" + message.getImei() + ", ver:" + message.getFirmwareVersion());
            }
            else{
                saveMsg(message, "ver:" + message.getFirmwareVersion());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveDeviceTrxStat(D3F2StopIndicationMessage message, boolean isUploading, Device device) {
        try {
            // 添加到trxmsg里
            GnssTrxMsg trxMsg = message.getTrxMsg();
            trxMsgMapper.insert(trxMsg);
            if(device.getDeviceType() == GnssDevice.TYPE_ROVER) {
                saveMsg(message, "d341 num: "+device.getD341Count()+","+message.getOtherInfo());
            }
            else{
                saveMsg(message, "d331 num: "+device.getD3xxCount()+","+message.getOtherInfo());
            }

            // 检测该对象是否已存在
            GnssStatus deviceState = deviceStateRepository.getByDeviceId(message.getId());
            //新增或更新到status数据表里
            if(null != deviceState) {
                // 记录服务端收发统计
                deviceState.setUpdatetime(trxMsg.getCreatetime());
                deviceState.setDevicetime(trxMsg.getDevicetime());
                deviceState.setD3xxbytes(trxMsg.getD3xxbytes());
                deviceState.setB562bytes(trxMsg.getB562bytes());
                deviceState.setSatelliteinuse(device.getSatelitesInUse());
                deviceState.setLatitude(device.getLatitude());
                deviceState.setLongitude(device.getLongitude());
                deviceState.setAltitude(device.getAltitude());
                deviceState.setState(isUploading?GnssStatus.STATE_UPLOADING:GnssStatus.STATE_IDLE);
                deviceStateRepository.updateById(deviceState);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void saveMsg(BaseMessage message,String content){
        GnssMsg gnssMsg = new GnssMsg();
        gnssMsg.setTenantid(message.getTenantId());
        gnssMsg.setCreatetime(message.getCreateTime());
        gnssMsg.setDeviceid(message.getId());
        gnssMsg.setMsgtype(message.getHeader());
        gnssMsg.setMsglen(message.getLen());
        gnssMsg.setTx(false);
        if(content!=null) {
            if (content.length() <= 128) {
                gnssMsg.setContent(content);
            } else {
                gnssMsg.setContent(content.substring(0, 120) + "...");
            }
        }
        msgMapper.insert(gnssMsg);
    }

    @Override
    public void saveD342Stat(D342LocationMessage message, Device device){
        saveMsg(message, "d342 num:"+device.getD342Count()+
                ", bytes:"+device.getD342Bytes()+
                ", total d341 num:"+device.getD341In42Count()+", session done");
    }
}
