package com.lerx.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;
import org.apache.lucene.search.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.exception.EmptyQueryException;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.entities.Albgenre;
import com.lerx.entities.Album;
import com.lerx.entities.AlbumArticle;
import com.lerx.entities.AlbumArticleContent;
import com.lerx.entities.AlbumArticleHistory;
import com.lerx.entities.AlbumPartner;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.HtmlFileStatic;
import com.lerx.entities.Poll;
import com.lerx.entities.SearchTotalModel;
import com.lerx.entities.Team;
import com.lerx.entities.User;
import com.lerx.entities.VisitorsBook;
import com.lerx.hql.entities.Rs;
import com.lerx.hql.util.HibernateCallbackUtil;
import com.lerx.hql.util.HibernateUtil;
import com.lerx.hql.util.RsUtil;
import com.lerx.portal.obj.PortalStatInfo;
import com.lerx.portal.obj.WeightValuesOfVisit;
import com.lerx.sys.util.StringUtil;
import com.lerx.v6.util.AlbumArticleUtil;

public class AlbumArticleDaoImpl extends HibernateDaoSupport implements IAlbumArticleDao {

	@Override
	public AlbumArticle add(AlbumArticle albumArticle) {
		long currTime=System.currentTimeMillis();
		if (albumArticle.getCreationTime()==0L) {
			albumArticle.setCreationTime(currTime);
			albumArticle.setCreationTimeOldest(currTime);
		}
		
		this.getHibernateTemplate().save(albumArticle);
		AlbumArticleContent content=albumArticle.getContent();
		if (content==null) {
			content=new AlbumArticleContent();
		}
		content.setArt(albumArticle);
		content.setEditTime(System.currentTimeMillis());
		/*if (content.getTitleImg() == null || content.getTitleImg().trim().equals("")) {
			content.setThumbnail(null);
		} else {
			content.setThumbnail(content.getTitleImg());
		}*/
		content.setSubject(StringUtil.htmlFilter(content.getSubject()));
		this.getHibernateTemplate().save(content);
		albumArticle.setStatus(true);
		albumArticle.setTmpSubject(content.getSubject());
		albumArticle.setTmpContent(content.getContent());
		albumArticle.setLastModifyTime(System.currentTimeMillis());
		this.getHibernateTemplate().update(albumArticle);
		
		VisitorsBook vbook = albumArticle.getVbook();
		Poll poll=albumArticle.getPoll();
		CommentBridge cb=albumArticle.getCb();
		Team team=cb.getObjTeam();
		this.getHibernateTemplate().save(team);
		cb.setObjTeam(team);
		HtmlFileStatic hfs=albumArticle.getHfs();
		this.getHibernateTemplate().save(vbook);
		this.getHibernateTemplate().saveOrUpdate(cb);
		this.getHibernateTemplate().save(poll);
		this.getHibernateTemplate().save(hfs);
		this.getHibernateTemplate().save(albumArticle);
		cb.setObjID(albumArticle.getId());
		this.getHibernateTemplate().update(cb);
		//记入历史
		AlbumArticleHistory history = new AlbumArticleHistory();
		history.setArt(albumArticle);
		history.setContent(content);
		history.setDescription("add");
		history.setUser(content.getEditor());
		history.setOperateDatetime(System.currentTimeMillis());
		this.getHibernateTemplate().save(history);
		return albumArticle;
	}

	@Override
	public void modify(AlbumArticle a, boolean whis,User operator) {
		AlbumArticleContent content=a.getContent();
		content.setEditTime(System.currentTimeMillis());
		if (whis) {
			content.setId(0);
			this.getHibernateTemplate().save(content);
		}else {
			this.getHibernateTemplate().update(content);
		}
		
		a.setTmpContent(content.getContent());
		a.setTmpSubject(content.getSubject());
		CommentBridge cb=a.getCb();
		cb.setObjTitle(a.getContent().getSubject());
		if (cb.getParent()==null) {
			cb.setParent(a.getAlbum().getCb());
		}
		Team team=a.getAlbum().getCb().getObjTeam();
		cb.setObjTeam(team);
		
		a.setLastModifyTime(System.currentTimeMillis());
		
		Poll poll=a.getPoll();
		if (poll.getParent()==null) {
			poll.setParent(a.getAlbum().getPoll());
		}
		
		HtmlFileStatic hfs=a.getHfs();
		if (hfs.getId()==0){
			this.getHibernateTemplate().save(hfs);
		}else{
			this.getHibernateTemplate().update(hfs);
		}
		
		
		SearchTotalModel srt=a.getSrt();
		if (srt==null) {
			srt = new SearchTotalModel();
			srt=AlbumArticleUtil.srtUpdate(srt, a);
		}
		if (srt.getId()==0) {
			this.getHibernateTemplate().save(srt);
			a.setSrt(srt);
		}else {
			this.getHibernateTemplate().update(srt);
		}
		
		this.getHibernateTemplate().update(a);
		this.getHibernateTemplate().update(cb);
		this.getHibernateTemplate().update(poll);
		
		
		
		
		//记入历史
		if (whis) {
			AlbumArticleHistory history = new AlbumArticleHistory();
			history.setArt(a);
			history.setContent(content);
			history.setDescription("modify");
			history.setUser(operator);
			history.setOperateDatetime(System.currentTimeMillis());
			this.getHibernateTemplate().save(history);
		}

	}

	@Override
	public AlbumArticle findByID(long id) {
		AlbumArticle article = this.getHibernateTemplate().get(AlbumArticle.class, id);
		if (article==null) {
			return null;
		}
		AlbumArticle target=article.getTarget();
		if (target!=null) {
			article.setContent(target.getContent());
			return article;
		}
		/*String hql = "select max(c.id) from AlbumArticleContent c where c.art.id="
				+ article.getId();*/
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticleContent.class);
		criteria.createAlias("art", "a");
		criteria.add(Restrictions.eq("a.id", article.getId() ) );
		criteria.setProjection(Projections.max("id"));
		
		@SuppressWarnings("unchecked")
		List<Long> list= (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		AlbumArticleContent content;
		if (list.get(0) != null) {
			long cid = list.get(0);
			content = this.getHibernateTemplate().get(AlbumArticleContent.class, cid);
		} else {
			content = new AlbumArticleContent();
		}

		article.setContent(content);
		
		return article;
	}
	
	@Override
	public AlbumArticle findByUuid(String uuid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("uuid", uuid ) );
		@SuppressWarnings("unchecked")
		List<AlbumArticle> lu = (List<AlbumArticle>) this.getHibernateTemplate().findByCriteria(criteria);
		if (lu.size() > 0) { 
			return lu.get(0);
		}else{
			return null;
		}
	}

	@Override
	public boolean delByID(long id,User deler) {
		AlbumArticle article = this.getHibernateTemplate().get(AlbumArticle.class, id);
		article.setStatus(false);
		article.setDeler(deler);
		this.getHibernateTemplate().update(article);
		//记入历史
		AlbumArticleHistory history = new AlbumArticleHistory();
		history.setArt(article);
		history.setContent(article.getContent());
		history.setDescription("delete");
		history.setUser(deler);
		history.setOperateDatetime(System.currentTimeMillis());
		this.getHibernateTemplate().save(history);
		return true;
	}
	
	@Override
	public void undelByID(long id) {
		AlbumArticle article = this.getHibernateTemplate().get(AlbumArticle.class, id);
		article.setStatus(true);
		article.setDeler(null);
		article.setLastModifyTime(System.currentTimeMillis());
		this.getHibernateTemplate().update(article);
	}
	
	@Override
	public void modifyProhibitByID(long id,User arbitrator) {
		AlbumArticle article = this.getHibernateTemplate().get(AlbumArticle.class, id);
		AlbumArticleContent content=article.getContent();
		article.setArbitrator(arbitrator);
		article.setProhibit(true);
		article.setStatus(false);
		this.getHibernateTemplate().update(article);
		CommentBridge cb=article.getCb();
		cb.setStatus(false);
		this.getHibernateTemplate().update(cb);
		Poll poll=article.getPoll();
		poll.setStatus(false);
		this.getHibernateTemplate().update(poll);
		
		//记入历史
		AlbumArticleHistory history = new AlbumArticleHistory();
		history.setArt(article);
		history.setContent(content);
		history.setDescription("prohibit");
		history.setUser(arbitrator);
		history.setOperateDatetime(System.currentTimeMillis());
		this.getHibernateTemplate().save(history);
		
	}
	
	@Override
	public void modifyReleaseByID(long id,User arbitrator) {
		AlbumArticle article = this.getHibernateTemplate().get(AlbumArticle.class, id);
		AlbumArticleContent content=article.getContent();
		article.setArbitrator(null);
		article.setProhibit(false);
		article.setStatus(true);
		article.setLastModifyTime(System.currentTimeMillis());
		this.getHibernateTemplate().update(article);
		CommentBridge cb=article.getCb();
		cb.setStatus(true);
		this.getHibernateTemplate().update(cb);
		Poll poll=article.getPoll();
		poll.setStatus(true);
		this.getHibernateTemplate().update(poll);
		
		//记入历史
		AlbumArticleHistory history = new AlbumArticleHistory();
		history.setArt(article);
		history.setContent(content);
		history.setDescription("release");
		history.setUser(arbitrator);
		history.setOperateDatetime(System.currentTimeMillis());
		this.getHibernateTemplate().save(history);
		
	}
	
	@Override
	@Transactional
	public void modifyTopOne(long id, boolean state) {
		AlbumArticle art=findByID(id);
		long albID=art.getAlbum().getId();
		
		/*Session s = this.getHibernateTemplate().getSessionFactory().openSession();
		Transaction t = s.beginTransaction();
		Query<?> query=s.createQuery("update AlbumArticle a set a.topOne=false where a.album.id="+albID+" and a.topOne=true");
		query.executeUpdate();
		t.commit();
		s.close();*/
		HibernateUtil.executeHql(this.getHibernateTemplate(), "update AlbumArticle a set a.topOne=false where a.album.id="+albID+" and a.topOne=true");
		if (state){
			art.setTopOne(true);
			this.getHibernateTemplate().update(art);
		}
		
	}

	@Override
	public Rs queryByAid(long aid,int status,int unprohibit,long startT,long endT, int firstResult, int page, int pagesize, boolean asc, int img,int soul,int orderby,WeightValuesOfVisit wvov) {
		String orderCmd,hqlTmp;
		orderCmd=orderBy(orderby,asc,wvov);
		
		String prohibitCmd="";
		if (unprohibit == 1) {
			prohibitCmd = "and a.prohibit is false ";
		}
		
		
		switch (status) {
		case 1:
			hqlTmp = " and a.status is true " + prohibitCmd + " and a.album.status is true and a.album.deled is false ";

			break;
		case -1:
			hqlTmp = " and a.status is false " + prohibitCmd + " and a.album.status is false and a.album.deled is false ";

			break;
		default:
			hqlTmp =" and a.album.deled is false " + prohibitCmd;
			break;
		}
		
		
		if (soul==1) {
			hqlTmp += " and a.soul is true ";
		}
		String imgCmd="";
		if (img==1) {
			imgCmd+=" and ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
		}
		
		if (startT>0L ) {
			hqlTmp += " and a.creationTime >=" + startT;
		}
		
		if (endT>0L ) {
			hqlTmp += " and a.creationTime <=" + endT;
		}
		
		String hql = "from AlbumArticle a where a.album.id="+aid +hqlTmp+imgCmd+ orderCmd;
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstResult, page, pagesize);
		return rs;
	}
	
	
	@Override
	public Rs queryByAidAndCid(long aid, long cid, int status,int unprohibit, long startT, long endT, int firstResult, int page,
			int pagesize, boolean asc, int img, int soul, int orderby, WeightValuesOfVisit wvov) {
		
		
		boolean wherecmd=false;
		
		String hql ;
		if (aid>0L) {
			hql = "from AlbumArticle a where a.album.id="+aid;
			wherecmd=true;
		}else {
			hql = "from AlbumArticle a ";
		}
		
		if (cid>0L) {
			
			if (wherecmd) {
				hql += " and a.classify.id="+cid;
			}else {
				hql += " where a.classify.id="+cid;
				wherecmd=true;
			}
			
		}
		
		
		String orderCmd,hqlTmp;
		orderCmd=orderBy(orderby,asc,wvov);
		String prohibitCmd="";
		if (unprohibit == 1) {
			prohibitCmd = "and a.prohibit is false ";
		}
		
		switch (status) {
		case 1:
			hqlTmp = " a.status is true "+prohibitCmd+" and a.album.status is true and a.album.deled is false ";

			break;
		case -1:
			hqlTmp = " a.status is false "+prohibitCmd+" and a.album.status is false and a.album.deled is false ";

			break;
		default:
			hqlTmp =" a.album.deled is false "+prohibitCmd;
			break;
		}
		
		String andorwhere="";
		if (wherecmd) {
			andorwhere = " and ";
		}else {
			andorwhere = " where ";
		}
		
		hqlTmp = andorwhere + hqlTmp;
		
		if (soul==1) {
			hqlTmp += " and a.soul is true ";
		}
		String imgCmd="";
		if (img==1) {
			imgCmd+=" and ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
		}
		
		if (startT>0L ) {
			hqlTmp += " and a.creationTime >=" + startT;
		}
		
		if (endT>0L ) {
			hqlTmp += " and a.creationTime <=" + endT;
		}
		
		hql += hqlTmp+imgCmd+ orderCmd;
		
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstResult, page, pagesize);
		return rs;
	}
	
	
	@Override
	public Rs queryByGid(long gid,int status,int unprohibit,long startT,long endT, int firstResult, int page, int pagesize, boolean asc, int img,int soul,int orderby,WeightValuesOfVisit wvov) {
		String orderCmd,hqlTmp;
		orderCmd=orderBy(orderby,asc,wvov);
		
		boolean wherecmd=false;
		
		String hql ;
		if (gid>0L) {
			hql = "from AlbumArticle a where a.album.genre.id="+gid;
			wherecmd=true;
		}else {
			hql = "from AlbumArticle a ";
		}
		
		switch (status) {
		case 1:
			if (wherecmd) {
				hqlTmp = " and a.status is true  and a.album.status is true and a.album.deled is false ";
			}else {
				hqlTmp = " where a.status is true  and a.album.status is true and a.album.deled is false  ";
				wherecmd=true;
			}
			

			break;
		case -1:
			if (wherecmd) {
				hqlTmp = " and a.status is false  and a.album.status is false and a.album.deled is false  ";
			}else {
				hqlTmp = " where a.status is false  and a.album.status is false and a.album.deled is false  ";
				wherecmd=true;
			}

			break;
		default:
			if (wherecmd) {
				hqlTmp =" and a.album.deled is false ";
			}else {
				hqlTmp =" where a.album.deled is false ";
				wherecmd=true;
			}
			
			break;
		}
		
		String prohibitCmd="";
		if (unprohibit == 1) {
			prohibitCmd = " a.prohibit is false ";
			if (wherecmd) {
				hqlTmp += " and "+prohibitCmd;
			}else {
				hqlTmp += " where "+prohibitCmd;
				wherecmd=true;
			}
		}
		
		
		if (soul==1) {
			if (wherecmd) {
				hqlTmp += " and a.soul is true ";
			}else {
				hqlTmp += " where a.soul is true ";
				wherecmd=true;
			}
			
		}
		if (img==1) {
			if (wherecmd) {
				hqlTmp+=" and ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
			}else {
				hqlTmp+=" where ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
				wherecmd=true;
			}
			
		}
		
		if (startT>0L ) {
			if (wherecmd) {
				hqlTmp += " and a.creationTime >=" + startT;
			}else {
				hqlTmp += " where a.creationTime >=" + startT;
				wherecmd=true;
			}
			
		}
		
		if (endT>0L  ) {
			if (wherecmd) {
				hqlTmp += " and a.creationTime <=" + endT;
			}else {
				hqlTmp += " where a.creationTime <=" + endT;
				wherecmd=true;
			}
			
		}
		
		hql = hql +hqlTmp+ orderCmd;
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstResult, page, pagesize);
		return rs;
	}
	
	@Override
	public Rs queryByGidAndCid(long gid, long cid, int status,int unprohibit, long startT, long endT, int firstResult, int page,
			int pagesize, boolean asc, int img, int soul, int orderby, WeightValuesOfVisit wvov) {
		String orderCmd,hqlTmp;
		orderCmd=orderBy(orderby,asc,wvov);
		
		boolean wherecmd=false;
		
		String hql ;
		if (gid>0L) {
			hql = "from AlbumArticle a where a.album.genre.id="+gid;
			wherecmd=true;
		}else {
			hql = "from AlbumArticle a ";
		}
		
		if (cid>0L) {
			
			if (wherecmd) {
				hql += " and a.classify.id="+cid;
			}else {
				hql += " where a.classify.id="+cid;
				wherecmd=true;
			}
			
		}
		
		switch (status) {
		case 1:
			if (wherecmd) {
				hqlTmp = " and a.status is true  and a.album.status is true and a.album.deled is false ";
			}else {
				hqlTmp = " where a.status is true  and a.album.status is true and a.album.deled is false  ";
				wherecmd=true;
			}
			

			break;
		case -1:
			if (wherecmd) {
				hqlTmp = " and a.status is false  and a.album.status is false and a.album.deled is false  ";
			}else {
				hqlTmp = " where a.status is false  and a.album.status is false and a.album.deled is false  ";
				wherecmd=true;
			}

			break;
		default:
			if (wherecmd) {
				hqlTmp =" and a.album.deled is false ";
			}else {
				hqlTmp =" where a.album.deled is false ";
				wherecmd=true;
			}
			
			break;
		}
		
		String prohibitCmd="";
		if (unprohibit == 1) {
			prohibitCmd = " a.prohibit is false ";
			if (wherecmd) {
				hqlTmp += " and "+prohibitCmd;
			}else {
				hqlTmp += " where "+prohibitCmd;
				wherecmd=true;
			}
		}
		
		if (soul==1) {
			if (wherecmd) {
				hqlTmp += " and a.soul is true ";
			}else {
				hqlTmp += " where a.soul is true ";
				wherecmd=true;
			}
			
		}
		if (img==1) {
			if (wherecmd) {
				hqlTmp+=" and ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
			}else {
				hqlTmp+=" where ((a.content.thumbnail is not null and trim(a.content.thumbnail)<>'') or (a.content.titleImg is not null and trim(a.content.titleImg)<>'')) ";
				wherecmd=true;
			}
			
		}
		
		if (startT>0L ) {
			if (wherecmd) {
				hqlTmp += " and a.creationTime >=" + startT;
			}else {
				hqlTmp += " where a.creationTime >=" + startT;
				wherecmd=true;
			}
			
		}
		
		if (endT>0L  ) {
			if (wherecmd) {
				hqlTmp += " and a.creationTime <=" + endT;
			}else {
				hqlTmp += " where a.creationTime <=" + endT;
				wherecmd=true;
			}
			
		}
		
		hql = hql +hqlTmp+ orderCmd;
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstResult, page, pagesize);
		return rs;
	}
	
	private String orderBy(int orderby ,boolean asc,WeightValuesOfVisit wvov ) {
		String orderbySQLAdd,orderCmd;
		switch (orderby) {
		case 1:			//按发布时间
			orderbySQLAdd = " a.creationTime ";
			break;
		case 2:			//按修改时间
			orderbySQLAdd = " a.lastModifyTime ";
			break;
		case 3:			//按浏览次数
			orderbySQLAdd = " a.vbook.viewsOwn ";
			break;
		case 4:			//按浏览IP次数
			orderbySQLAdd = " a.vbook.ipOwn ";
			break;
		case 5:			//按评论数
			orderbySQLAdd = " ((a.cb.total+2 )*(a.cb.total*7 + a.poll.agrees/7) + a.vbook.ipTotal/13 ) ";
			break;
		case 6:			//按点赞数
			orderbySQLAdd = " ((a.poll.agrees+2)*(a.cb.total/7 + a.poll.agrees*7) + a.vbook.ipTotal/13 ) ";
			break;
		case 7:			//按平均热度
			orderbySQLAdd = "( (a.cb.total * "+wvov.getMessages()+" + a.poll.agrees * "+wvov.getAgrees()+" + a.vbook.ipTotal * "+wvov.getIps()+" + a.vbook.viewsTotal * "+wvov.getViews()+") *( TO_DAYS(NOW()) - ( TO_DAYS(a.creationTime)-1 ) )   /  ( ( TO_DAYS(NOW()) - ( TO_DAYS(a.creationTime)-1 ) ) /3 ))";
			break;
		case 8:
			orderbySQLAdd = " a.soul ";
			break;
		case 9:
			orderbySQLAdd = " rand() ";
			break;
		default:		//默认排序，按id
			orderbySQLAdd = " a.id ";
		}
		
		String topCmd="";
		if (orderby<3) {
			topCmd=" a.topOne desc, ";
		}
		if (orderby<9) {
			if (asc) {
				orderCmd = " order by "+topCmd +orderbySQLAdd+" asc";
			} else {
				orderCmd = " order by "+topCmd +orderbySQLAdd+" desc";
			}
		}else {
			if (asc) {
				orderCmd = " order by "+topCmd +orderbySQLAdd;
			} else {
				orderCmd = " order by "+topCmd +orderbySQLAdd;
			}
		}
		return orderCmd;
	}

	//查找某专辑内的文章历史操作记录
	@Override
	public Rs findContentByAlbID(long albID, int firstResult, int page, int pagesize, boolean asc) {
		String hql = "from AlbumArticleContent c where c.art.album.deled is false and c.art.album.id="+albID;
		String orderCmd;
		if (asc) {
			orderCmd = " order by c.id asc";
		} else {
			orderCmd = " order by c.id desc";
		}
		hql += orderCmd;
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstResult, page, pagesize);
		return rs;
	}

	@Override
	public long countByAlbumID(long id) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.createAlias("album", "a");
		criteria.add(Restrictions.eq("a.id", id ) );
		criteria.add(Restrictions.eq("a.deled", false ) );
		criteria.setProjection(Projections.rowCount());
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		
		/*String hql = "select count(*) from AlbumArticle a where a.album.id=?0 and a.status is true";
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql,id);*/
		return list.get(0);
	}

	@Override
	public long countProhibitByAlbumID(long id) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.add(Restrictions.eq("prohibit", true ) );
		criteria.createAlias("album", "a");
		criteria.add(Restrictions.eq("a.id", id ) );
		criteria.add(Restrictions.eq("a.deled", false ) );
		criteria.setProjection(Projections.rowCount());
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		
		/*String hql = "select count(*) from AlbumArticle a where a.album.id=?0 and a.status is true and a.prohibit is true";
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql,id);*/
		return list.get(0);
	}
	
	@Override
	public long countByPartnerID(long id) {
		AlbumPartner partner = this.getHibernateTemplate().get(AlbumPartner.class, id);
		
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.add(Restrictions.eq("prohibit", false ) );
		criteria.createAlias("album", "a");
		criteria.add(Restrictions.eq("a.id", partner.getAlbum().getId() ) );
		criteria.add(Restrictions.eq("a.deled", false ) );
		criteria.createAlias("content", "c");
		criteria.createAlias("c.editor", "e");
		criteria.add(Restrictions.eq("e.id", partner.getUser().getId() ) );
		criteria.setProjection(Projections.rowCount());
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
//		System.out.println("e u 都运行了");
		/*String hql = "select count(*) from AlbumArticle a where a.album.id=?0 and a.content.editor.id=?1 and a.status is true and a.prohibit is false";
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql,partner.getAlbum().getId(),partner.getUser().getId());*/
		return list.get(0);
	}

	@Override
	public AlbumArticleContent findCurrContentByID(long id) {
		
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticleContent.class);
		criteria.createAlias("art", "a");
		criteria.add(Restrictions.eq("a.id", id ) );
		criteria.setProjection(Projections.max("id"));
		
		@SuppressWarnings("unchecked")
		List<Long> list= (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		AlbumArticleContent content;
		if (list.get(0) != null) {
			long cid = list.get(0);
			content = this.getHibernateTemplate().get(AlbumArticleContent.class, cid);
		} else {
			content = new AlbumArticleContent();
		}
		
		/*String hql = "select max(c.id) from AlbumArticleContent c where c.art.id="
				+ id;
		AlbumArticleContent content;
		if (this.getHibernateTemplate().find(hql).get(0) != null) {
			long cid = (Long) this.getHibernateTemplate().find(hql).get(0);
			content = this.getHibernateTemplate().get(AlbumArticleContent.class, cid);
		} else {
			return null;
		}*/
		return content;
	}

	@Override
	public AlbumArticleContent findContentByCID(long id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(AlbumArticleContent.class, id);
	}

	@Override
	public long countAfterArticleID(long aid) {
		AlbumArticle art=findByID(aid);
		if (art==null) {
			return 0;
		}
		Album album=art.getAlbum();
		
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.add(Restrictions.eq("prohibit", false ) );
		criteria.createAlias("album", "a");
		criteria.add(Restrictions.eq("a.id", album.getId() ) );
		criteria.add(Restrictions.eq("a.deled", false ) );
		criteria.add(Restrictions.eq("id", aid ) );
		criteria.setProjection(Projections.rowCount());
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		
		/*String hql = "select count(*) from AlbumArticle a where a.album.id=?0 and a.id>?1 and a.status is true and a.prohibit is false";
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql,album.getId(),aid);*/
		return list.get(0);
	}

	@Override
	public long findMaxArtID(long aid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.createAlias("album", "a");
		criteria.add(Restrictions.eq("a.id", aid ) );
		criteria.add(Restrictions.eq("a.deled", false ) );
		criteria.setProjection(Projections.max("id"));
		
		@SuppressWarnings("unchecked")
		List<Long> list= (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		if (list.size()>0) {
			return list.get(0);
		}{
			return 0;
		}
		
		/*String hql = "select max(a.id) from AlbumArticle a where a.album.id=?0";
		
		if (this.getHibernateTemplate().find(hql,aid).get(0) != null) {
			return (long) this.getHibernateTemplate().find(hql,aid).get(0);
		}else {
			return 0;
		}*/
		
	}

	@Override
	public AlbumArticle findNeighbour(long aid, int mod, long albID) {
		Album album;
		String modStr;
		if (mod == 0) {
			modStr = " a.id < " + aid + " order by a.creationTime desc,a.id desc";
		} else {
			modStr = " a.id > " + aid + " order by a.creationTime asc,a.id asc";
		}
		
		if (albID != 0) {
			album = this.getHibernateTemplate().get(Album.class, albID);
		} else {
			album = null;
		}
		
		String hql;

		if (album != null) {
			hql = "from AlbumArticle a where a.status=true and a.prohibit=false and a.album.id="
					+ albID + " and " + modStr;

		} else {
			hql = "from AlbumArticle a where a.status=true and a.prohibit=false and "
					+ modStr;
		}
		
		Rs rs=HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, 0, 1, 1);
		if (rs.getCount()>0 && !rs.getList().isEmpty() && rs.getList().size()>0) {
			return (AlbumArticle) rs.getList().get(0);
		}else {
			return null;
		}
	}

	@Override
	public List<Long> queryAllPassedID(long aid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.add(Restrictions.eq("prohibit", false ) );
		criteria.setProjection(Projections.property("id"));
		
		if (aid>0) {
			criteria.createAlias("album", "a");
			criteria.add(Restrictions.eq("a.id", aid ) );
			criteria.add(Restrictions.eq("a.deled", false ) );
		}
		
		@SuppressWarnings("unchecked")
		List<Long> list= (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		
		return list;
	}

	@Override
	public PortalStatInfo stat(PortalStatInfo psi) {
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.setProjection(Projections.rowCount());
		criteria.add(Restrictions.eq("status", true ) );
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		
		psi.setAlbartsTotal(list.get(0));
		
		return psi;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Rs search(long gid,long aid, String key, boolean fulltext, int firstResult, int page, int pagesize) {

		FullTextSession fts = Search.getFullTextSession(this.getSessionFactory().getCurrentSession());
	    QueryBuilder qb = fts.getSearchFactory().buildQueryBuilder().forEntity(AlbumArticle.class).get();
	    
	    
	    Query luceneQuery;
	    List<AlbumArticle> data;
	    Rs rs=null;
	    try {
	    	
			luceneQuery = qb.keyword().onFields("tmpContent","tmpSubject").matching(key).createQuery();
			if (gid>0L && aid==0L) {
				Albgenre albgenre= this.getHibernateTemplate().get(Albgenre.class, aid);
				luceneQuery = qb
					    .bool()
					    .must(
					    		qb
					            .keyword()
					            .onFields("tmpContent","tmpSubject")
					            .matching(key)
					            .createQuery()
					    )
					    .must(
					    		qb
					            .keyword()
					            .onField("albgenre")
					            .matching(albgenre)
					            .createQuery()
					    )
					    .createQuery();
			}
			if (aid>0L && gid==0L) {
				Album album= this.getHibernateTemplate().get(Album.class, aid);
				luceneQuery = qb
					    .bool()
					    .must(
					    		qb
					            .keyword()
					            .onFields("tmpContent","tmpSubject")
					            .matching(key)
					            .createQuery()
					    )
					    .must(
					    		qb
					            .keyword()
					            .onField("album")
					            .matching(album)
					            .createQuery()
					    )
					    .createQuery();
			}
			
			
			FullTextQuery query = fts.createFullTextQuery(luceneQuery, AlbumArticle.class);
//			System.out.println("query.getQueryString():"+query.getQueryString());
			query.addQueryHint("album.deled=0");
			query.addQueryHint("status is true");
		    query.setFirstResult((page - 1) * pagesize);
		    query.setMaxResults(pagesize);
		    data = query.list();
		    rs=RsUtil.init(page, pagesize, query.getResultSize());
		    List<AlbumArticle> la=AlbumArticleUtil.hightLight(luceneQuery, data, "tmpContent","tmpSubject");
		    rs.setList(la);
		} catch (EmptyQueryException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	    
		if (rs!=null) {
			/*for (Object art:rs.getList()) {
		    	Article a=(Article) art;
		    	System.out.println("a.getSubject():"+a.getSubject());
		    }*/
		}else {
			rs=new Rs();
			rs.setList(new ArrayList<AlbumArticle>());
		}
	    
		
	    
		return rs;
	
	}


	/*@Override
	public int excuteInsert(long nextid) {
		AlbumArticle toBlankArt=findByID(nextid);
		if (toBlankArt==null) {
			return -1;
		}
		AlbumArticle newArt = new AlbumArticle ();
		
		this.getHibernateTemplate().save(newArt);
		
		
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticle.class);
		criteria.add(Restrictions.gt("id", nextid ) ); //大于这个id，最后把这个id的文章清空
		criteria.addOrder( Order.desc("id") );
		@SuppressWarnings("unchecked")
		List<Long> listId=(List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		if (listId.size()==0) {
			return -1;
		}
		for (long id:listId) {
			copy(id,id-1);
		}
		toBlankArt.setCb(new CommentBridge());
		toBlankArt.setContent(new AlbumArticleContent());
		toBlankArt.setCreationTime(toBlankArt.getCreationTime() - 1);
		toBlankArt.setHfs(new HtmlFileStatic());
		toBlankArt.setDeler(null);
		toBlankArt.setPoll(new Poll());
		toBlankArt.setStatus(true);
		toBlankArt.setSubject(null);
		toBlankArt.setSubjectShort(null);
		toBlankArt.setTarget(null);
		toBlankArt.setTmpContent(null);
		toBlankArt.setTmpSubject(null);
		toBlankArt.setTopOne(false);
		toBlankArt.setSoul(false);
		VisitorsBook vbook = new VisitorsBook();
		vbook.setObjType(3);
		toBlankArt.setVbook(vbook);
		toBlankArt.setViews(0);
		this.getHibernateTemplate().save(vbook);
		this.getHibernateTemplate().save(toBlankArt.getCb());
		this.getHibernateTemplate().save(toBlankArt.getPoll());
		this.getHibernateTemplate().save(toBlankArt.getHfs());
		this.getHibernateTemplate().save(toBlankArt);
		
		return 0;
	}*/

	/*@Override
	public boolean copy(long sourceid, long targetid) {
		//将历史记录移动
		AlbumArticle sourceArt=findByID(sourceid);
		AlbumArticle targetArt=findByID(targetid);
		if (sourceArt==null || targetArt==null) {
			return false;
		}
		
		DetachedCriteria criteria=DetachedCriteria.forClass(AlbumArticleHistory.class);
		criteria.createAlias("art", "a");
		criteria.add(Restrictions.eq("a.id", sourceid ) );
		@SuppressWarnings("unchecked")
		List<AlbumArticleHistory> listHistory=(List<AlbumArticleHistory>) this.getHibernateTemplate().findByCriteria(criteria);
		for (AlbumArticleHistory his:listHistory) {
			his.setArt(targetArt);
			his.getContent().setArt(targetArt);
			this.getHibernateTemplate().update(his.getContent());
			this.getHibernateTemplate().update(his);
		}
		//将content移动
		DetachedCriteria criteria2=DetachedCriteria.forClass(AlbumArticleContent.class);
		criteria2.createAlias("art", "a");
		criteria2.add(Restrictions.eq("a.id", sourceid ) );
		@SuppressWarnings("unchecked")
		List<AlbumArticleContent> listContent=(List<AlbumArticleContent>) this.getHibernateTemplate().findByCriteria(criteria2);
		for (AlbumArticleContent con:listContent) {
			con.setArt(targetArt);
			this.getHibernateTemplate().update(con);
		}
		targetArt.setAlbum(sourceArt.getAlbum());
		targetArt.setArbitrator(sourceArt.getArbitrator());
		targetArt.setDeler(sourceArt.getDeler());
		targetArt.setCb(sourceArt.getCb());
		targetArt.setContent(sourceArt.getContent());
		targetArt.setCreationTime(sourceArt.getCreationTime());
		targetArt.setHfs(sourceArt.getHfs());
		targetArt.setHotn(sourceArt.getHotn());
		targetArt.setLastModifyTime(sourceArt.getLastModifyTime());
		targetArt.setLastViewTime(sourceArt.getLastViewTime());
		targetArt.setOwner(sourceArt.getOwner());
		targetArt.setPoll(sourceArt.getPoll());
		targetArt.setProhibit(sourceArt.isProhibit());
		targetArt.setSoul(sourceArt.isSoul());
		targetArt.setStatus(sourceArt.isStatus());
		targetArt.setSubject(sourceArt.getSubject());
		targetArt.setSubjectShort(sourceArt.getSubjectShort());
		targetArt.setTarget(sourceArt.getTarget());
		targetArt.setTmpContent(sourceArt.getTmpContent());
		targetArt.setTmpSubject(sourceArt.getTmpSubject());
		targetArt.setTopOne(sourceArt.isTopOne());
		targetArt.setVbook(sourceArt.getVbook());
		targetArt.setViews(sourceArt.getViews());
		this.getHibernateTemplate().update(targetArt);
		return true;
		
	}
*/

}
