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.DataAutoclaves;
import com.fjhx.mapper.data.DataAutoclavesMapper;
import com.fjhx.service.data.DataAutoclavesService;
import com.fjhx.utils.Assert;
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-11-22
 */
@Service
public class DataAutoclavesServiceImpl extends ServiceImpl<DataAutoclavesMapper, DataAutoclaves> implements DataAutoclavesService {

    @Resource
    private BladeRedis bladeRedis;


    @Override
    public boolean add(JSONObject json) {

        bladeRedis.set(RedisConstant.DATA_AUTOCLAVES, json);

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

        DataAutoclaves dataAutoclaves = new DataAutoclaves();
        dataAutoclaves.setJsonData(json.toJSONString());
        dataAutoclaves.setMachineId(machineId);
        dataAutoclaves.setCreateTime(new Date());

        return save(dataAutoclaves);
    }

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

        JSONObject json = bladeRedis.get(RedisConstant.DATA_AUTOCLAVES + nodeId);

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

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

            json = JSONObject.parseObject(dataAutoclaves.getJsonData());
            bladeRedis.set(RedisConstant.DATA_AUTOCLAVES + nodeId, json);
        }

        return json;
    }

}
