package com.zcxk.charge.web.service.impl;

import com.zcxk.charge.core.entity.MonitorDataEntity;
import com.zcxk.charge.web.service.MonitorDataService;
import com.zcxk.core.utils.ByteArrayUtils;
import com.zcxk.core.utils.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @description
 * @author  wangli
 * @data 2020-12-01 11:09
 */
@Service
@Slf4j
public class MonitorDataServiceImpl implements MonitorDataService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public MonitorDataEntity save(MonitorDataEntity monitorDataEntity) {
        // 缓存数据
        redisUtil.setExpire(("sms_water_"+monitorDataEntity.getDeviceCode()).getBytes(), ByteArrayUtils.objectToBytes(monitorDataEntity).get());
        // 把没有数据的属性去掉再保存
        monitorDataEntity.setDataValues(monitorDataEntity.getDataValues().stream().filter(m -> m.getDataValue()!=null).collect(Collectors.toList()));
        return mongoTemplate.save(monitorDataEntity);
    }

    @Override
    public void remove(Long id) {
        mongoTemplate.remove(id);
    }

    @Override
    public void update(MonitorDataEntity monitorDataEntity) {
        Query query = new Query(Criteria.where("id").is(monitorDataEntity.getId()));
        Update update = new Update();
        update.set("deviceName", monitorDataEntity.getDeviceName());
        mongoTemplate.updateFirst(query, update, MonitorDataEntity.class);
    }

    @Override
    public MonitorDataEntity findById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        MonitorDataEntity monitorDataEntity = mongoTemplate.findOne(query, MonitorDataEntity.class);
        return monitorDataEntity;
    }

}