package com.data.emqx.service.impl;

import com.alibaba.fastjson.JSON;
import com.data.emqx.MqttSubscribeSample;
import com.data.emqx.domain.LoadCarDataSoure;
import com.data.emqx.mapper.LoadCarDataSoureMapper;
import com.data.emqx.service.ILoaderCarDataSourceService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author licd
 * @className LoaderCarDataSource
 * @description
 * @date 2025/02/17 08:38
 */

@Service
public class LoaderCarDataSourceServiceImpl implements ILoaderCarDataSourceService {

    private static final Logger logger = Logger.getLogger(MqttSubscribeSample.class);


    @Resource
    private LoadCarDataSoureMapper loadCarDataSoureMapper;

    @Override
    public void addLoaderCarDataSource(byte[] payload) throws Exception {

        String json = new String(payload);
        //String json = "{\"deviceID\":789,\"deviceStatus\":\"OK\",\"sendtime\":20250226141512000,\"weight\":-20,\"weightStatus\":0,\"weighttime\":20250226141512000}";
        logger.info("emqx接收到的数据：" + json);
        LoadCarDataSoure loadCarDataSoure = JSON.parseObject(json, LoadCarDataSoure.class);
        if (null == loadCarDataSoure) {
            throw new RuntimeException("接收到的参数不能为空！");
        }
        //如果发送时间没有17位则返回fail提示发送时间异常
        if(null == loadCarDataSoure.getSendTime() || loadCarDataSoure.getSendTime().length() != 17){

            loadCarDataSoureMapper.addEmqx_error(json,loadCarDataSoure.getSendTime(),new Date());
            throw new RuntimeException("发送时间异常sendTime：" + loadCarDataSoure.getSendTime());
        }
        //称重重量小于0异常
        if(null != loadCarDataSoure.getWeight() && loadCarDataSoure.getWeight() < 0 ){
            loadCarDataSoureMapper.addEmqx_error(json,loadCarDataSoure.getSendTime(),new Date());
            throw new RuntimeException("weight异常：" + loadCarDataSoure.getWeight());
        }
        loadCarDataSoure.setId(UUID.randomUUID().toString());
        if (null == loadCarDataSoure.getCardID() || "".equals(loadCarDataSoure.getCardID().trim())) {

            loadCarDataSoure.setCreateTime(Calendar.getInstance().getTime());
            //重量不为空就是装载机数据
            if (null != loadCarDataSoure.getWeight() && !"".equals(loadCarDataSoure.getWeight())) {
                loadCarDataSoureMapper.addLoadCarDataSourceMapper(loadCarDataSoure);
            } else {
                //重量为空就是自卸车数据
                loadCarDataSoureMapper.addUnLoadCarDataSourceMapper(loadCarDataSoure);
            }
        } else {
            loadCarDataSoureMapper.addDeviceCard(loadCarDataSoure);
        }


    }
}
