package com.goafanti.news.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.app.bo.AppDiscoveryBo;
import com.goafanti.common.bo.PolicyEntity;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.JtCollectSearchMapper;
import com.goafanti.common.dao.NewsMapper;
import com.goafanti.common.dao.NewsPublishMapper;
import com.goafanti.common.enums.collectType;
import com.goafanti.common.model.JtCollectSearch;
import com.goafanti.common.model.News;
import com.goafanti.common.model.NewsPublish;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.news.bo.NewsPortalList;
import com.goafanti.news.bo.NewsResult;
import com.goafanti.news.bo.NewsSummary;

@Service
@Transactional
public class NewsService extends BaseMybatisDao<NewsMapper> {
	@Autowired
	NewsMapper newsMapper;
	@Autowired
	NewsPublishMapper newsPublishMapper;
	@Autowired
	JtCollectSearchMapper	jtCollectSearchMapper;
	@Value("${spring.profiles.active}")
	private String env;
	@Value(value="${collect_flag}")
	private Boolean collectFlag ;
	
	private static final Logger logger = LoggerFactory.getLogger(NewsService.class);

	@Cacheable(value = "IndexNewsListCache", key = "'NewsList:Page:'+#pageNo+'Type:'+#type+'Size:'+#pageSize")
	public List<NewsSummary> findIndexNewsList(Integer pageNo, Integer type, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		params.put("pageSize", pageSize);
		params.put("pageNo", pageNo);
		return newsMapper.findIndexNewsLists(params);
	}

	@CacheEvict(value = "IndexNewsListCache", allEntries = true)
	public void cleanIndexNewsList() {
		LoggerUtils.debug(logger, "清除首页新闻列表缓存");
	}

	@Cacheable(value = "NewsCache", key = "'News:'+#id")
	public News selectById(Long id) {
		return newsMapper.selectByPrimaryKey(id);
	}

	@Cacheable(value = "NewsListCache", key = "'NewsList:Page:'+#pageNo+'Type:'+#type+'Size:'+#pageSize+'domainName:'+#domainName+'picReq:'+#picRequired")
	public List<NewsSummary> findNewsList(Integer pageNo, Integer type, Integer pageSize, String domainName,
			Boolean picRequired) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		params.put("pageSize", pageSize);
		params.put("pageNo", pageNo);
		if (!StringUtils.equals(env, "dev") && !StringUtils.equals(env, "local")) {
			params.put("website", domainName);
		}
		if (picRequired) {
			params.put("picRequired", picRequired);
		}
		return newsMapper.findList(params);
	}

	@CacheEvict(value = "NewsListCache", allEntries = true)
	public void cleanList() {
		LoggerUtils.debug(logger, "清除新闻列表缓存");
	}

	@CacheEvict(value = "NewsCache", key = "'News:'+#id")
	public void clean(String id) {
		LoggerUtils.debug(logger, "清除新闻缓存:[%s]", id);
	}

	@CachePut(value = "NewsCache", key = "'News:'+#id")
	public News save(Long id, News news) {
		news.setId(id);
		newsMapper.insert(news);
		return news;
	}
	
	public News save(News news,List<String>webPages,List<String>appPages) {
		if (null!=news &&news.getAuditStatus()!=null&& news.getAuditStatus()==2) {
			addJtCollectSearch( news);
		}
		newsMapper.insert(news);
		NewsPublish newsPublish=null;
		if(webPages!=null && webPages.size()>0)
		{
			for(String s:webPages)
			{
			newsPublish=new NewsPublish();
			newsPublish.setId(UUID.randomUUID().toString());
			newsPublish.setPublishPage(s);
			newsPublish.setNewsId(news.getId()+"");
			newsPublish.setIfTop(0);
			newsPublish.setPublishClient(0);
			newsPublish.setPublisher("");
			newsPublish.setPublishPlatform("");
			newsPublish.setPublishTime(new Date());
			newsPublishMapper.insert(newsPublish);
			}
		}
		if(appPages!=null && appPages.size()>0)
		{
			for(String s:appPages)
			{
			newsPublish=new NewsPublish();
			newsPublish.setId(UUID.randomUUID().toString());
			newsPublish.setPublishPage(s);
			newsPublish.setNewsId(news.getId()+"");
			newsPublish.setIfTop(0);
			newsPublish.setPublishClient(1);
			newsPublish.setPublisher("");
			newsPublish.setPublishPlatform("");
			newsPublish.setPublishTime(new Date());
			newsPublishMapper.insert(newsPublish);
			}
		}
		return news;
	}

	@CachePut(value = "NewsCache", key = "'News:'+#id")
	public News update(long id, News news) {
		newsMapper.updateByPrimaryKeyWithBLOBs(news);
		return news;
	}
	public int updateSelectivelyWithoutPages(News news)
	{
		return newsMapper.updateByPrimaryKeySelective(news);
	}
	public int updateSelectively(News news,List<String>webPages,List<String>appPages) {
		if(collectFlag){
			if(news!=null&&news.getAuditStatus()==2)addJtCollectSearch(news);
			if(news!=null&&news.getAuditStatus()==4)updateJtCollectSearch(news);
		}
		newsPublishMapper.deleteByNewsId(news.getId());
		NewsPublish newsPublish=null;
		if(webPages!=null && webPages.size()>0)
		{
			for(String s:webPages)
			{
			newsPublish=new NewsPublish();
			newsPublish.setId(UUID.randomUUID().toString());
			newsPublish.setPublishPage(s);
			newsPublish.setNewsId(news.getId()+"");
			newsPublish.setIfTop(0);
			newsPublish.setPublishClient(0);
			newsPublish.setPublisher("");
			newsPublish.setPublishPlatform("");
			newsPublish.setPublishTime(new Date());
			newsPublishMapper.insert(newsPublish);
			}
		}
		if(appPages!=null && appPages.size()>0)
		{
			for(String s:appPages)
			{
			newsPublish=new NewsPublish();
			newsPublish.setId(UUID.randomUUID().toString());
			newsPublish.setPublishPage(s);
			newsPublish.setNewsId(news.getId()+"");
			newsPublish.setIfTop(0);
			newsPublish.setPublishClient(1);
			newsPublish.setPublisher("");
			newsPublish.setPublishPlatform("");
			newsPublish.setPublishTime(new Date());
			newsPublishMapper.insert(newsPublish);
			}
		}
		return newsMapper.updateByPrimaryKeySelective(news);
	}

	/*
	 * type(0-普通  99-公众号新闻  98-技淘百科)
	 * */
	@SuppressWarnings("unchecked")
	public Pagination<News> listNews(Integer type, String title, String author, String startCreateTime,
			String endCreateTime, String source, Integer hot, Integer pNo, Integer pSize,String auditStatus,String releaseStatus,String publishPage,Integer provinceId) {
		Map<String, Object> params = new HashMap<>();
		if(null !=publishPage) {
			params.put("publishPage", publishPage);
		}
		if (null != auditStatus) {
			params.put("auditStatus", auditStatus);
		}
		
		if (null != releaseStatus) {
			params.put("releaseStatus", releaseStatus);
		}
		
		if (null != type) {
			params.put("type", type);
		}

		if (StringUtils.isNotBlank(title)) {
			params.put("title", title);
		}

		if (StringUtils.isNotBlank(author)) {
			params.put("author", author);
		}

		if (StringUtils.isNotBlank(startCreateTime)) {
			try {
				params.put("sDate", DateUtils.parseDate(startCreateTime, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		if (StringUtils.isNotBlank(endCreateTime)) {
			try {
				params.put("eDate", DateUtils.addDays(DateUtils.parseDate(endCreateTime, AFTConstants.YYYYMMDD), 1));
			} catch (ParseException e) {
			}
		}

		if (StringUtils.isNotBlank(source)) {
			params.put("source", source);
		}
		if (null != provinceId) {
			params.put("provinceId", provinceId);
		}

		if (null != hot) {
			params.put("hot", hot);
		}

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		return (Pagination<News>) findPage("findNewsListByPage", "findNewsCount", params, pNo, pSize);
	}

	public NewsResult findNewsDetail(Long id) {
		NewsResult newsResult=newsMapper.selectByPrimaryKey(id);
		List<NewsPublish> newsPublishs=newsPublishMapper.selectByNewsId(id);
		newsResult.setNewsPublishs(newsPublishs);
		return newsResult;
	}

	public int batchDeleteByPrimaryKey(List<String> id) {
		
		return newsMapper.batchDeleteByPrimaryKey(id);
	}

	@SuppressWarnings("unchecked")
	public Pagination<NewsPortalList> portalNewsList(Integer pSize, Integer pNo, Integer type, Integer hot,
			Integer provinceId, String keyword,Integer auditStatus) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (null != hot) {
			params.put("hot", hot);
		}
		if (null != type) {
			params.put("type", type);
		}
		if (null != provinceId) {
			params.put("provinceId", provinceId);
		}
		if (null != keyword) {
			params.put("keyword", keyword);
		}
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}
		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		if(auditStatus!=null) {
			params.put("auditStatus", auditStatus);
		}
		return (Pagination<NewsPortalList>) findPage("portalNewsList", "portalNewsCount", params, pNo, pSize);
	}

	@CacheEvict(value = "NewsPortalListCache", allEntries = true)
	public void cleanPortalList() {
		LoggerUtils.debug(logger, "清除门户端新闻列表缓存");

	}

	public List<NewsSummary> findJmrhNewsList(String type) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		return newsMapper.findJmrhNewsList(params);
	}

	public List<NewsPortalList> portalNewsPolicy(){
		
		return newsMapper.portalNewsPolicy();
	}
	public List<NewsPortalList> portalNewsQuestion(){
		
		return newsMapper.portalNewsQuestion();
	}
	
	
	public int deleteByPrimaryKey(long id) {
		newsPublishMapper.deleteByNewsId(id);
		if(collectFlag)jtCollectSearchMapper.deleteByrowId(String.valueOf(id));
		return newsMapper.deleteByPrimaryKey(id);
	}
	
	public  List<News>getNewsList(int size){
		List<News>  news=newsMapper.getNewsList(size);
				return news;
	}
	
	public PolicyEntity getPolicyDetail(String id) {
		PolicyEntity res=newsMapper.getPolicyDetail(id);
		return res;
	}

	public NewsPortalList informationDetail(String id) {
		return newsMapper.selectinformationDetail(id);
	}

	
	

	public News findAppNewsDetail(long id) {
		return newsMapper.selectByPrimaryKey(id);
	}

	public void addJtCollectSearch(News news) {
		if(collectFlag){
			JtCollectSearch r=new JtCollectSearch();
			r.setFromTable(collectType.NEWS.getDesc());
			r.setKeyword(news.getKeyword());
			r.setTitle(news.getTitle());
			r.setRowId(news.getId().toString());
			String sum = news.getSummary();
			if(null != sum && sum.length() > 40){
				sum = sum.substring(0,40) + "...";
			}
			r.setSummary(sum);
			jtCollectSearchMapper.insertSelective(r);
		}
		
	}

	public void updateJtCollectSearch(News news) {
		if(collectFlag)jtCollectSearchMapper.deleteByrowId(news.getId().toString());
		
	}
	
	@SuppressWarnings("unchecked")
	public Pagination<AppDiscoveryBo> listTypeNews(Integer type,Integer pageNo, Integer pageSize) {
		Map<String, Object> params=new HashMap<>();
		if (pageNo == null || pageNo < 1)pageNo = 1;
		if (pageSize == null || pageSize < 1 )pageSize = 10;
		if(type!=null)params.put("type", type);
		Pagination<AppDiscoveryBo>p= (Pagination<AppDiscoveryBo>) findPage("selectTypeNewsList", "selectTypeNewsCount", params, pageNo, pageSize);
		List<AppDiscoveryBo> l=(List<AppDiscoveryBo>) p.getList();
		for (AppDiscoveryBo a : l) {
			a.setContent(a.getContent().replaceAll("<p>", "").replaceAll("</p>", ""));
		}
		return p;
	}

	

	
}
