package com.lerx.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.lerx.dao.iface.IAlbumDao;
import com.lerx.entities.Album;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.Poll;
import com.lerx.entities.Team;
import com.lerx.entities.VisitorsBook;
import com.lerx.hql.entities.Rs;
import com.lerx.hql.util.HibernateCallbackUtil;
import com.lerx.portal.obj.PortalStatInfo;

public class AlbumDaoImpl extends HibernateDaoSupport implements IAlbumDao {

	@Override
	public Album add(Album album) {
		VisitorsBook vbook = album.getVbook();
		Poll poll=album.getPoll();
		CommentBridge cb=album.getCb();
		Team team=cb.getObjTeam();
		this.getHibernateTemplate().save(team);
		cb.setObjTeam(team);
		this.getHibernateTemplate().save(vbook);
		this.getHibernateTemplate().save(poll);
		this.getHibernateTemplate().save(cb);
		
		this.getHibernateTemplate().save(album);
		return album;
	}
	
	@Override
	public void modify(Album album) {
		CommentBridge cb=album.getCb();
		if (cb==null) {
			cb = new CommentBridge();
			cb.setUser(album.getLeader());
			cb.setStatus(true);
			cb.setObjType(3);
			cb.setObjTitle(album.getName());
			Team team=new Team();
			this.getHibernateTemplate().save(team);
			cb.setObjTeam(team);
			this.getHibernateTemplate().save(cb);
			album.setCb(cb);
		}else {
			if (cb.getObjTeam()==null) {
				Team team=new Team();
				this.getHibernateTemplate().save(team);
				cb.setObjTeam(team);
			}
			this.getHibernateTemplate().update(cb);
		}
		this.getHibernateTemplate().update(album.getPoll());
		this.getHibernateTemplate().update(album);

	}
	
	@Override
	public void update(Album album) {
		this.getHibernateTemplate().update(album);
		
	}

	@Override
	public Album findByID(long id) {
		return this.getHibernateTemplate().get(Album.class, id);
	}

	@Override
	public Album findByName(String name) {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		criteria.add(Restrictions.eq("name", name ) );
		criteria.add(Restrictions.eq("deled", false ) );
		List<?> lu=this.getHibernateTemplate().findByCriteria(criteria);
		
		/*String hql = "from Album a where a.name=?0";
		@SuppressWarnings("unchecked")
		List<Album> lu = (List<Album>) this.getHibernateTemplate().find(hql, name);*/
		if (lu.size() > 0) { // 如果有子对象，则拒绝删除
			return (Album) lu.get(0);
		} else {
			return null;
		}
	}
	
	@Override
	public Album findByUuid(String uuid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		criteria.add(Restrictions.eq("uuid", uuid ) );
		criteria.add(Restrictions.eq("deled", false ) );
		@SuppressWarnings("unchecked")
		List<Album> lu = (List<Album>) this.getHibernateTemplate().findByCriteria(criteria);
		if (lu.size() > 0) { 
			return lu.get(0);
		}else{
			return null;
		}
	}

	@Override
	public boolean delByID(long id) {
		Album album=findByID(id);
		album.setDeled(true);
		this.getHibernateTemplate().update(album);
		return true;
		/*
		 * this.getHibernateTemplate().delete(findByID(id));
		 * 
		 * if (findByID(id) == null) { return true; } else { return false; }
		 */
	}

	@Override
	public Rs query(long gid,int page, int pagesize, int status, int open, int orderBy, int orderDirection) {
		String sqladd = "", statusSql, openSql;
		switch (status) {
		case -1:
			statusSql = " a.status is false ";
			break;
		case 0:
			statusSql = "";
			break;
		default:
			statusSql = " a.status is true ";
		}
		sqladd += statusSql;

		switch (open) {
		case -1:
			openSql = " a.open is false ";
			break;
		case 0:
			openSql = "";
			break;
		default:
			openSql = " a.open is true ";
		}

		if (!sqladd.trim().equals("") && !openSql.trim().equals("")) {
			sqladd += " and ";
		}

		sqladd += openSql;

		if (!sqladd.trim().equals("")) {
			sqladd = " and " + sqladd;
		}
		
		String orderSqlAdd;

		switch (orderBy) {
		
		case 1:
			orderSqlAdd=" order by a.createTime ";
			break;
		
		case 2:
			orderSqlAdd=" order by a.lastEditTime ";
			break;
			
		case 3:
			orderSqlAdd=" order by a.vbook.viewsTotal ";
			break;
			
		case 4:
			orderSqlAdd=" order by a.vbook.ipTotal ";
			break;
		case 5:
			orderSqlAdd=" order by (a.cb.total + a.poll.total/3 + a.vbook.ipTotal/13) ";
			break;
		case 6:
			orderSqlAdd=" order by (a.cb.total/3 + a.poll.total + a.vbook.ipTotal/13) ";
			break;
		case 7:
			orderSqlAdd = "order by ((a.cb.total * 2 + a.poll.total*3 + a.vbook.ipTotal*3) *( TO_DAYS(NOW()) - ( TO_DAYS(a.createTime)-1 ) )   /  ( ( TO_DAYS(NOW()) - ( TO_DAYS(a.createTime)-1 ) ) /3 ))";
//			orderSqlAdd=" order by ((a.vbook.ipTotal*3 + a.vbook.viewsTotal + a.cb.total*13 + a.poll.total*7)/( TO_DAYS(NOW()) - (TO_DAYS(a.createTime)-1) )) ";
			break;
		case 8:
			orderSqlAdd=" order by (a.totalArtSoul * 37 + a.totalArt) ";
			break;
		case 9:
			orderSqlAdd=" order by rand() ";
			break;
		default:
			orderSqlAdd=" order by a.id ";
		}
		
		if (orderDirection==0) {
			orderSqlAdd += "desc";
		}else {
			orderSqlAdd += "asc";
		}
		String gidStr="";
		if (gid>0) {
			gidStr = " and a.genre.id="+gid+" ";
		}

		String hql = "from Album a where a.deled is false " +gidStr+ sqladd + orderSqlAdd;
		int firstPlace = 0;
		return HibernateCallbackUtil.getRs(this.getHibernateTemplate(), hql, firstPlace, page, pagesize);
	}

	@Override
	public List<Album> findByLeaderID(long uid,long gid, int status) {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		
		switch (status) {
		case -1:
			criteria.add(Restrictions.eq("status", false ) );
			break;
		case 1:
			criteria.add(Restrictions.eq("status", true ) );
			break;
		}
		
		if (gid>0) {
			criteria.add(Restrictions.eq("genre.id", gid ) );
		}
		criteria.add(Restrictions.eq("leader.id", uid ) );
		criteria.add(Restrictions.eq("deled", false ) );
		criteria.addOrder( Order.desc("id") );
		
		@SuppressWarnings("unchecked")
		List<Album> list=(List<Album>) this.getHibernateTemplate().findByCriteria(criteria);
		
		
		return list;
	}

	@Override
	public List<Long> queryAllPassedID() {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		criteria.add(Restrictions.eq("status", true ) );
		criteria.add(Restrictions.eq("open", true ) );
		criteria.add(Restrictions.eq("deled", false ) );
		criteria.add(Restrictions.isNotNull("leader") );
		criteria.createAlias("leader", "a"); 
		criteria.add(Restrictions.eq("a.state", true ) );
		criteria.createAlias("a.role", "b");
		criteria.add(Restrictions.eq("b.status", true ) );
		criteria.addOrder( Order.asc("id") );
		criteria.setProjection(Projections.property("id"));
		
		
		@SuppressWarnings("unchecked")
		List<Long> list=(List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		/*System.out.println("在运行"+list.size());
		System.out.println("criteria.toString():"+criteria.toString());
		
		for (Long lid:list) {
			Album a=findByID(lid);
			System.out.println("--"+lid+":专辑："+a.getName());
		}*/
		/*String hql="select a.id from Album a where a.status is true and a.open is true and a.leader.state is true and (a.leader.role<>null and a.leader.role.status is true) ";

		hql += " order by a.id asc" ;
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql);*/
		return list;
	}

	@Override
	public List<Album> findAllByUid(long uid, long gid, int status) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long countByUidAndGid(long uid, long gid) {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		criteria.add(Restrictions.eq("deled", false ) );
		criteria.setProjection(Projections.rowCount());
		if (uid>0L) {
			criteria.createAlias("leader", "a"); 
			criteria.add(Restrictions.eq("a.id", uid ) );
		}
		if (gid>0L) {
			criteria.createAlias("genre", "g"); 
			criteria.add(Restrictions.eq("g.id", gid ) );
		}
		
		@SuppressWarnings("unchecked")
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(criteria);
		return list.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Album> rand(long gid,int pagesize) {
		DetachedCriteria criteria=DetachedCriteria.forClass(Album.class);
		criteria.createAlias("genre", "g"); 
		criteria.add(Restrictions.eq("g.id", gid ) );
		criteria.add(Restrictions.eq("deled", false ) );
		Criteria cri =  criteria.getExecutableCriteria(this.getSessionFactory().getCurrentSession()); 
		//cri.setFirstResult(0);//从第一条记录开始
        cri.setMaxResults(pagesize);
        criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
        
		return (List<Album>) this.getHibernateTemplate().findByCriteria(criteria);
		
	}

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

	

}
