package com.liquidnet.service.platform.service.basicServices;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.adam.dto.vo.admin.AdminUpushVo;
import com.liquidnet.service.kylin.entity.AdminUpush;
import com.liquidnet.service.kylin.mapper.AdminUpushMapper;
import com.liquidnet.service.kylin.service.admin.IAdminUpushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
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 org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 轮播图 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-05-02
 */
@Service
public class AdminUpushServiceImpl extends ServiceImpl<AdminUpushMapper, AdminUpush> implements IAdminUpushService {

    @Value("${liquidnet.al-oss.imgUrl}")
    private String imgUrl;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisUtil redisUtil;

    public PageInfo<AdminUpushVo> lists(Integer page, Integer size) {
        Query query = Query.query(
                Criteria.where("specifyType").is(2).and("messageType").is(2)
                .and("pushTime").lt(DateUtil.getNowTime())
        );

        long count = mongoTemplate.count(query, AdminUpushVo.class.getSimpleName());

        PageInfo<AdminUpushVo> voPageInfo = null;
        if (count > 0) {
            Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));

            query.with(pageable);

            List<AdminUpushVo> msgList = mongoTemplate.find(
                    query,
                    AdminUpushVo.class,
                    AdminUpushVo.class.getSimpleName()
            );

            if (!CollectionUtils.isEmpty(msgList)) {
                for (AdminUpushVo info : msgList) {
                    if (!info.getImg().isEmpty()) {
                        String img = imgUrl + info.getImg();
                        info.setImg(img);
                    }
                }
            }

            voPageInfo = PageInfo.of(msgList);
            voPageInfo.setTotal(count);
        } else {
            voPageInfo = new PageInfo<>();
        }
        return voPageInfo;
    }

}
