package com.goafanti.banners.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.druid.sql.visitor.functions.If;
import com.goafanti.common.bo.MyCollection;
import com.goafanti.common.dao.BannersMapper;
import com.goafanti.common.model.Banners;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;

@Service
public class BannersService extends BaseMybatisDao<BannersMapper> {
	@Autowired
	BannersMapper				bannersMapper;

	private static final Logger	logger	= LoggerFactory.getLogger(BannersService.class);

	public int insertBanner(Banners banners) {
		banners.setId(UUID.randomUUID().toString());
		return bannersMapper.insertSelective(banners);
	}

	public int updateBanner(Banners banners) {
		return bannersMapper.updateByPrimaryKeySelective(banners);
	}

	public int deleteBanner(String id) {
		return bannersMapper.deleteByPrimaryKey(id);
	}
	public Banners selectByPrimaryKey(String id) {
		return bannersMapper.selectByPrimaryKey(id);
	}

	public List<Banners> findBannersList(String apiUrl,Integer client,Integer pageSize,Integer pageNo) {
		return portalBanners(apiUrl, client, pageNo, pageSize);
	}
	
	public int findBannersListCount(String sign) {
		return bannersMapper.findBannerListCount(sign);
	}


	private List<Banners> portalBanners(String apiUrl,Integer client, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<1)pageSize=10;
		if(pageNo==null||pageNo<1)pageNo=1;
		if (StringUtils.isNotBlank(apiUrl)) {
			params.put("apiUrl", apiUrl);
		}
		int pSize=(pageNo - 1) * pageSize;
		params.put("pS", pSize+pageSize);
		params.put("pN", pSize);
		return bannersMapper.findBannerList(params);
	}

	@CacheEvict(value = "BannersListCache", key = "'BannersList:Key:'+#key")
	public void cleanList(String key) {
		LoggerUtils.debug(logger, "清除广告图列表缓存：[%s]", key);
	}
	
	@SuppressWarnings("unchecked")
	public Pagination<Banners> findAdminBannersList(String apiUrl,Integer client,Integer pageSize,Integer pageNo) {
		if(pageNo==null ||pageNo<1)pageNo=1;
		if(pageSize== null ||pageSize<1)pageSize=10;
		 Map<String, Object> params=new HashMap<String,Object>();
		if(StringUtils.isNotBlank(apiUrl)) params.put("apiUrl", apiUrl);
		if(client != null) params.put("client", client);
		return (Pagination<Banners>) findPage("findAdminBannersList", "findAdminBannersCount", params, pageNo, pageSize);
	}
	
}
