
package com.tmerclub.cloud.flow.service.impl;

import com.tmerclub.cloud.flow.bo.FlowLogBO;
import com.tmerclub.cloud.flow.service.FlowUserMongoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 流量分析—用户访问数据
 *
 * @author YXF
 * @date 2021-05-21 15:25:19
 */
@Service
public class FlowUserMongoServiceImpl implements FlowUserMongoService {

    private static final Logger log = LoggerFactory.getLogger(FlowUserMongoServiceImpl.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Date getBeginDate() {
        FlowLogBO flowLogBO = mongoTemplate.findOne(new Query().with(Sort.by(Sort.Direction.ASC, "_id")), FlowLogBO.class);
        if (Objects.nonNull(flowLogBO)) {
            return flowLogBO.getDt();
        }
        return new Date();
    }

    @Override
    public List<FlowLogBO> getFlowLogByOrderIds(Integer pid, Long userId, String orderIds) {
        Criteria criteria = Criteria.where("pid").is(pid)
                .and("uid").is(userId)
                .and("bid").is(Long.parseLong(orderIds));
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        return mongoTemplate.find(query, FlowLogBO.class);
    }

    @Override
    public FlowLogBO getUserLastLog(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        return mongoTemplate.findOne(query, FlowLogBO.class);
    }

}
