package com.zsc.edu.gateway.modules.iot.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.framework.redis.RedisUtils;
import com.zsc.edu.gateway.modules.iot.record.entity.RecordData;
import com.zsc.edu.gateway.modules.iot.record.repo.RecordDataRepository;
import com.zsc.edu.gateway.modules.iot.record.service.RecordDataService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author zhuang
 */
@AllArgsConstructor
@Service
public class RecordDataServiceImpl extends ServiceImpl<RecordDataRepository, RecordData> implements RecordDataService {
    RedisUtils redisUtils;
    @Override
    public RecordData create(RecordData record) {
        save(record);
        return record;
    }
    @Override
    public List<RecordData> page(IPage<RecordData> page, String clientId) {
        LambdaQueryWrapper<RecordData> queryWrapper = new LambdaQueryWrapper<>();
        if (clientId != null) {
            queryWrapper.eq(RecordData::getClientId, clientId);
            return baseMapper.selectList(page, queryWrapper);
        }
        return baseMapper.selectList(page, queryWrapper);
    }

    @Override
    public List<RecordData> recordData(String clientId) {
        LocalDateTime recordTime = LocalDateTime.parse(redisUtils.get("serve:sendTime:photograph:" + clientId));
        List<RecordData> records = baseMapper.selectList(new LambdaQueryWrapper<RecordData>()
                .eq(RecordData::getClientId, clientId).le(RecordData::getRecordTime, recordTime));
        Optional<RecordData> first = records.stream().max(Comparator.comparing(RecordData::getRecordTime));
        if (first.isPresent()) {
            String recordTimeStr = (String) first.get().getContent().get("recordTimeStr");
            return baseMapper.findByRecordTimeStr(recordTimeStr);
        } else {
            return records;
        }
    }
}
