package com.fjhx.service.data.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.Condition;
import com.fjhx.constants.RedisConstant;
import com.fjhx.entity.data.DataPacker;
import com.fjhx.mapper.data.DataPackerMapper;
import com.fjhx.service.data.DataPackerService;
import org.springblade.core.redis.cache.BladeRedis;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 包装机数据 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-19
 */
@Service
public class DataPackerServiceImpl extends ServiceImpl<DataPackerMapper, DataPacker> implements DataPackerService {

    @Resource
    private BladeRedis bladeRedis;


    @Override
    public boolean add(JSONObject json) {

        bladeRedis.set(RedisConstant.DATA_PACKER, json);

        // JSONObject module = json.getJSONObject("Module");
        // String machineId = module.getString("MachineId");

        DataPacker dataPacker = new DataPacker();
        dataPacker.setJsonData(json.toJSONString());
        // dataPacker.setMachineId(machineId);
        dataPacker.setCreateTime(new Date());

        return save(dataPacker);
    }

    @Override
    public JSONObject getData(Condition condition) {
        // String nodeId = condition.getStr("nodeId");
        // Assert.notEmpty(nodeId, "设备标识不能够为空");

        JSONObject json = bladeRedis.get(RedisConstant.DATA_PACKER);

        if (json == null) {
            DataPacker dataPacker = getOne(Wrappers.<DataPacker>lambdaQuery()
                    // .eq(DataPacker::getMachineId, nodeId)
                    .orderByDesc(DataPacker::getId)
                    .last("limit 1"));

            if (dataPacker == null) {
                return new JSONObject();
            }

            json = JSONObject.parseObject(dataPacker.getJsonData());
            bladeRedis.set(RedisConstant.DATA_PACKER, json);
        }

        return json;
    }

}
