package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.dao.AdMapper;
import com.qxgmat.data.dao.entity.Ad;
import com.qxgmat.data.dao.entity.ExaminationStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class AdService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(AdService.class);

    @Resource
    private AdMapper adMapper;

    public List<Ad> all(){
        Example example = new Example(Ad.class);
        Date day = new Date();
        example.and(
                example.createCriteria()
                        .orGreaterThanOrEqualTo("startTime", day)
                        .orIsNull("startTime")
        );
        example.and(
                example.createCriteria()
                        .orLessThan("endTime", day)
                        .orIsNull("endTime")
        );
        example.orderBy("position").asc();
        return select(adMapper);
    }

    public Ad add(Ad ad){
        int result = insert(adMapper, ad);
        ad = one(adMapper, ad.getId());
        if(ad == null){
            throw new SystemException("广告添加失败");
        }
        return ad;
    }

    public Ad edit(Ad ad){
        Ad in = one(adMapper, ad.getId());
        if(in == null){
            throw new ParameterException("广告不存在");
        }
        int result = update(adMapper, ad);
        return ad;
    }

    public boolean delete(Number id){
        Ad in = one(adMapper, id);
        if(in == null){
            throw new ParameterException("广告不存在");
        }
        int result = delete(adMapper, id);
        return result > 0;
    }

    public Ad get(Number id){
        Ad in = one(adMapper, id);

        if(in == null){
            throw new ParameterException("广告不存在");
        }
        return in;
    }

    public Page<Ad> select(int page, int pageSize){
        return select(adMapper, page, pageSize);
    }

    public List<Ad> select(Collection ids){
        return select(adMapper, ids);
    }

}
