package com.ifish.daoImpl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.ifish.dao.LiveRoomDao;
import com.ifish.dto.LiveRoomInfoDto;
import com.ifish.entity.LiveRoom;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.RoomStatusEnum;
import com.ifish.hibernate.HibernateBaseDao;
import com.ifish.hibernate.Pagination;

/** 
 * @ClassName: LiveRoomImpl
 * @Description: TODO 
 * @author ggw 
 *  
 */

@Repository
public class LiveRoomImpl extends HibernateBaseDao<LiveRoom, Integer> implements LiveRoomDao {

	@Override
	protected Class<LiveRoom> getEntityClass() {
		return LiveRoom.class;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LiveRoomInfoDto> findByDistance(Double longitude,Double latitude) {
		if(longitude!=null && latitude!=null){
			String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays,round(6378.138*2*asin(sqrt(pow(sin((?*pi()/180-u.latitude*pi()/180)/2),2)+cos(?*pi()/180)*cos(u.latitude*pi()/180)* pow(sin((?*pi()/180-u.longitude*pi()/180)/2),2)))*1000) AS distance from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l on c.user_id=l.user_id WHERE c.is_live=? AND l.room_status=? HAVING distance IS NOT NULL ORDER BY distance ASC LIMIT 5";
			return this.getSession().createSQLQuery(sql)
					.setParameter(0, latitude)
					.setParameter(1, latitude)
					.setParameter(2, longitude)
					.setParameter(3, BooleanEnum.YES.getKey())
					.setParameter(4, RoomStatusEnum.status1.getKey())
					.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class))
					.list();
		}
		else{
			return new ArrayList<LiveRoomInfoDto>();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LiveRoomInfoDto> findByBrowse(Integer userId) {
		if(userId!=null){
			String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays from tbl_browse_room b LEFT JOIN tbl_live_room l ON b.room_id=l.room_id LEFT JOIN tbl_camera_user c ON c.user_id=l.user_id LEFT JOIN tbl_user u ON c.user_id=u.user_id where b.user_id=? AND c.is_live=? AND l.room_status=? ORDER BY b.update_time DESC LIMIT 5";
			return this.getSession().createSQLQuery(sql)
					.setParameter(0, userId)
					.setParameter(1, BooleanEnum.YES.getKey())
					.setParameter(2, RoomStatusEnum.status1.getKey())
					.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class))
					.list();
		}
		else{
			return new ArrayList<LiveRoomInfoDto>();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LiveRoomInfoDto> findByPopularityValue() {
		String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE c.is_live=? AND l.room_status=? ORDER BY l.popularity_value DESC LIMIT 5";
		return this.getSession().createSQLQuery(sql)
				.setParameter(0, BooleanEnum.YES.getKey())
				.setParameter(1, RoomStatusEnum.status1.getKey())
				.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class))
				.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<LiveRoomInfoDto> findByTime(Integer firstResult,Integer pageSize,String orders) {
		//综合数据
		Integer length = 0;
		String[] strOrder = null;
		if(orders!=null && orders.length()>0){
			strOrder = orders.split(",");
			length = strOrder.length;
		}
		//总条数
		String countSql = "select count(*) from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE ### c.is_live=? AND l.room_status=? ORDER BY l.create_time DESC";
		//分页数据
		String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,l.create_time AS createTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE ### c.is_live=? AND l.room_status=? ORDER BY l.create_time DESC LIMIT ?,?";
		//查询条件去除综合数据
		Object[] intOrder = new Integer[length];
		StringBuilder pingjie = new StringBuilder("");
		if(length>0){
			pingjie.append("l.room_id NOT IN (");
			for (int i = 0; i < length; i++) {
				if(i==0){
					pingjie.append("?");
				}
				else{
					pingjie.append(",?");
				}
				intOrder[i] = Integer.valueOf(strOrder[i]);
			}
			pingjie.append(") AND");
		}
		countSql = countSql.replaceAll("###", pingjie.toString());
		sql = sql.replaceAll("###", pingjie.toString());
		//查询total
		SQLQuery countQuery = this.getSession().createSQLQuery(countSql);
		if(length>0){
			for (int i = 0; i < length; i++) {
				countQuery.setParameter(i, intOrder[i]);
			}
			countQuery.setParameter(length, BooleanEnum.YES.getKey());
			countQuery.setParameter((length+1), RoomStatusEnum.status1.getKey());
		}
		else{
			countQuery.setParameter(0, BooleanEnum.YES.getKey());
			countQuery.setParameter(1, RoomStatusEnum.status1.getKey());
		}
		int totalCount = ((BigInteger)countQuery.uniqueResult()).intValue();
		//分页数据
		SQLQuery query = this.getSession().createSQLQuery(sql);
		if(length>0){
			for (int i = 0; i < length; i++) {
				query.setParameter(i, intOrder[i]);
			}
			query.setParameter(length, BooleanEnum.YES.getKey());
			query.setParameter((length+1), RoomStatusEnum.status1.getKey());
			query.setParameter((length+2), firstResult);
			query.setParameter((length+3), pageSize);
		}
		else{
			query.setParameter(0, BooleanEnum.YES.getKey());
			query.setParameter(1, RoomStatusEnum.status1.getKey());
			query.setParameter(2, firstResult);
			query.setParameter(3, pageSize);
		}
		List<LiveRoomInfoDto> list = query.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class)).list();
		//分页封装
		Pagination<LiveRoomInfoDto> page = new Pagination<LiveRoomInfoDto>();
		page.setTotalCount(totalCount);
		page.setList(list);
		return page;

	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<LiveRoomInfoDto> findByPopularityValue(Integer firstResult,Integer pageSize) {
		//总条数
		String countSql = "select count(*) from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE c.is_live=? AND l.room_status=? ORDER BY l.popularity_value DESC";
		int totalCount = ((BigInteger) this.getSession().createSQLQuery(countSql)
				.setParameter(0, BooleanEnum.YES.getKey())
				.setParameter(1, RoomStatusEnum.status1.getKey())
				.uniqueResult()).intValue();
		String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE c.is_live=? AND l.room_status=? ORDER BY l.popularity_value DESC LIMIT ?,?";
		//分页数据
		List<LiveRoomInfoDto> list =  this.getSession().createSQLQuery(sql)
				.setParameter(0, BooleanEnum.YES.getKey())
				.setParameter(1, RoomStatusEnum.status1.getKey())
				.setParameter(2, firstResult)
				.setParameter(3, pageSize)
				.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class))
				.list();
		//分页封装
		Pagination<LiveRoomInfoDto> page = new Pagination<LiveRoomInfoDto>();
		page.setTotalCount(totalCount);
		page.setList(list);
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<LiveRoomInfoDto> getLiveRoomsByTuijian(Integer firstResult, Integer pageSize) {
		//总条数
		String countSql = "select count(*) from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE c.is_live=? AND l.room_status=? ORDER BY l.popularity_value DESC";
		int totalCount = ((BigInteger) this.getSession().createSQLQuery(countSql)
				.setParameter(0, BooleanEnum.YES.getKey())
				.setParameter(1, RoomStatusEnum.status1.getKey())
				.uniqueResult()).intValue();
		String sql = "select l.room_id AS roomId,u.user_id AS userId,u.user_type AS userType,u.nick_name AS nickName,u.user_img AS userImg,u.login_time AS loginTime,c.camera_id AS cameraId,l.room_name AS roomName,l.room_desc AS roomDesc,l.popularity_value AS popularityValue,(TO_DAYS(NOW())-TO_DAYS(l.create_time)) AS numberDays from tbl_user u LEFT JOIN tbl_camera_user c ON u.user_id=c.user_id LEFT JOIN tbl_live_room l ON u.user_id=l.user_id WHERE l.is_tuijian='1' AND c.is_live=? AND l.room_status=? ORDER BY l.tuijian_num ASC LIMIT ?,?";
		//分页数据
		List<LiveRoomInfoDto> list =  this.getSession().createSQLQuery(sql)
				.setParameter(0, BooleanEnum.YES.getKey())
				.setParameter(1, RoomStatusEnum.status1.getKey())
				.setParameter(2, firstResult)
				.setParameter(3, pageSize)
				.setResultTransformer(Transformers.aliasToBean(LiveRoomInfoDto.class))
				.list();
		//分页封装
		Pagination<LiveRoomInfoDto> page = new Pagination<LiveRoomInfoDto>();
		page.setTotalCount(totalCount);
		page.setList(list);
		return page;
	}

}
