package com.palmnest.dao.estateserve.impl;

import java.util.List;
import java.util.Map;

import com.palmnest.application.core.util.DateHelper;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.estateserve.VisitorInFoDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.estateserve.FaceProjectInfo;
import com.palmnest.model.estateserve.UserImageInfo;
import com.palmnest.model.estateserve.VisitorInfo;
import com.palmnest.model.estateserve.VisitorOrder;
import org.springframework.util.CollectionUtils;

/**
 * 访客模块实现 Dao
 * @author HJY
 *
 */
@Repository("visitorInFoDao")
@SuppressWarnings("unchecked")
public class VisitorInFoDaoImpl extends GenericDaoHibernate<Object, Integer> implements VisitorInFoDao{

	public VisitorInFoDaoImpl() {
		super(Object.class);
	}

	@Override
	public Integer getVisitorCodeMaxCount(String visitorStartTime) {
		String strSQL="SELECT MAX(t1.codeNumber) from tb_VisitorCode t1 where t1.codeCreateTime >='"+visitorStartTime+" 00:00:00' and t1.codeCreateTime <= '"+visitorStartTime+" 23:59:59'";
		Integer count=getJdbcTemplate().queryForInt(strSQL);
		if(count==null){
			return 0;
		}
		return count;
	}

	@Override
	public Map<String, Object> getVisitorCode(String visitorStartTime) {
		String strSQL="SELECT * from tb_VisitorCode t1 where t1.codeCreateTime >='"+visitorStartTime+" 00:00:00' and t1.codeCreateTime <= '"+visitorStartTime+" 23:59:59'";
		List<Map<String,Object>> list=getJdbcTemplate().queryForList(strSQL);
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public Map<String, Object> getVistorInfo(String visitorId) {
		String strSQL="SELECT t1.*,t2.imageFaceUrl from tb_visitorInfo t1"
				+ " LEFT JOIN tb_userImageInfo t2 on t2.userId=t1.visitorId and t2.imageType=2"
				+ " where t1.visitorId="+visitorId;
		List<Map<String,Object>> list=getJdbcTemplate().queryForList(strSQL);
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public Integer getVistorInfoCount(String visitorOrderId) {
		String strSQL="SELECT count(1) from tb_visitorInfo where visitorOrderId="+visitorOrderId;
		Integer count=getJdbcTemplate().queryForInt(strSQL);
		return count;
	}

	
	@Override
	public VisitorInfo getVisitorInfo(String visitorId) {
		String strHQL="from VisitorInfo where visitorId="+visitorId;
		List<VisitorInfo> list=getSession().createQuery(strHQL).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}


	@Override
	public VisitorOrder getVisitorOrder(Integer visitorOrderId) {
		String strHQL="from VisitorOrder where visitorOrderId="+visitorOrderId;
		List<VisitorOrder> list=getSession().createQuery(strHQL).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<VisitorInfo> getVisitorInfoList(Integer visitorOrderId) {
		String strHQL="from VisitorInfo where visitorOrderId="+visitorOrderId;
		List<VisitorInfo> list=getSession().createQuery(strHQL).list();
		if(list!=null && list.size()>0){
			return list;
		}
		return null;
	}

	@Override
	public UserImageInfo getUserImageInfo(Integer userId) {
		String strHQL="from UserImageInfo where imageType=2 and userId="+userId;
		List<UserImageInfo> list=getSession().createQuery(strHQL).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getVisitorTime(String userId,String userType) {
		String strSQL="SELECT DATE_FORMAT(t1.visitorOrderStartTime,'%Y-%m-%d') dateTime from tb_visitorOrder t1 where 1=1 ";

		if ("-1".equals(userType)){
			strSQL += " and t1.fromUserId="+userId;
		}else {
			strSQL += " and t1.visitorUserId="+userId;
		}

		strSQL += " GROUP BY  DATE_FORMAT(t1.visitorOrderStartTime,'%Y-%m-%d')";
		strSQL += " ORDER BY t1.visitorOrderStartTime desc";
		List<Map<String,Object>> list=getJdbcTemplate().queryForList(strSQL);
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> getVisitorList(String dateTime, String userId,String userType) {
		String strSQL="SELECT *,DATE_FORMAT(t1.visitorOrderStartTime,'%Y-%m-%d') visitorTime, "
				+ " DATE_FORMAT(t1.visitorOrderStartTime,'%H:%i') startTime,DATE_FORMAT(t1.visitorOrderEndTime,'%H:%i') endTime from tb_visitorOrder t1 "
				+ " where t1.visitorOrderStartTime >= '"+dateTime+" 00:00:00'"
		        + "   and t1.visitorOrderStartTime <= '"+dateTime+" 23:59:59'";
		if ("-1".equals(userType)){
			strSQL += " and t1.fromUserId="+userId;
		}else {
			strSQL += " and t1.visitorUserId="+userId;
		}
		strSQL += " ORDER BY t1.visitorOrderCreateTime desc";
		List<Map<String,Object>> list=getJdbcTemplate().queryForList(strSQL);
		if(list!=null && list.size()>0){
			return list;
		}
		return null;
	}

	@Override
	public VisitorInfo getVisitorInfo(String visitorOpenId,
			String visitorIdentification) {
		String strHQL="from VisitorInfo where visitorOpenId=? and visitorIdentification=?";
		List<VisitorInfo> list=getSession().createQuery(strHQL).setString(0, visitorOpenId).setString(1, visitorIdentification).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> expVisitorOrderInfoList(
			Map<String, String> params, String orgIdS) {
		String strSQL="SELECT t3.visitorId,IFNULL(t3.visitorName,'') visitorName,t4.`name` organizationName,IFNULL(t3.visitorPhone,'') visitorPhone,IFNULL(t3.visitorCompanyName,'') visitorCompanyName,t1.visitorQrCode,"
				+ "t3.visitorPassword,t3.visitorStartTime,t3.visitorEndTime,t5.imageFaceUrl,"
				+ "t2.userName,t2.userMobile,t1.visitorOrderStatus,t6.name virName,t1.visitorToFloor,t1.visitorReason,t1.visitorOrderType,"
				+ " t1.visitorToOrgId,t3.userHeadUrl,t1.visitorToCompany,DATE_FORMAT(t3.visitorCreateTime,'%Y-%m-%d %H:%i') visitorCreateTime "
				+ " from tb_visitororder t1 "
				+ " LEFT join tb_user t2 on t1.visitorUserId=t2.ID"
				+ " LEFT join tb_visitorinfo t3 on t3.visitorOrderId=t1.visitorOrderId"
				+ " LEFT join tb_organization t4 on t4.ID=t2.organizationId"
				+ " LEFT join tb_virtualarchitecture t6 on t6.id=t2.virtualArchId"
				+ " LEFT JOIN tb_userimageinfo t5 on t5.userId=t3.visitorId"
				+ " where 1=1 ";
		if (StringUtils.isNotBlank(orgIdS)){
			strSQL+=" and (t4.ID IN ("+orgIdS+") OR t1.visitorToOrgId IN ("+orgIdS+"))";
		}
		
		if(null==params){
			strSQL+=" order by t1.visitorOrderCreateTime desc";
			
			List<Map<String, Object>> list = getJdbcTemplate().queryForList(strSQL.toString());
			return list;
	
		}
		
		if(params.containsKey("name")&&StringUtils.isNotEmpty(params.get("name"))){
			strSQL+=" and t3.visitorName like '%"+params.get("name")+"%'  ";
		}
		if(params.containsKey("mobile")&&StringUtils.isNotEmpty(params.get("mobile"))){
			strSQL+=" and t3.visitorPhone like '%"+params.get("mobile")+"%'  ";
		}
		
		if(params.containsKey("visitorInfo")&&StringUtils.isNotEmpty(params.get("visitorInfo"))){
			strSQL+=" and ( t3.visitorName like '%"+params.get("visitorInfo")+"%' or t3.visitorPhone like '%"+params.get("visitorInfo")+"%' or t3.visitorCompanyName like '%"+params.get("visitorInfo")+"%')  ";
		}
		
		if(params.containsKey("respondents")&&StringUtils.isNotEmpty(params.get("respondents"))){
			strSQL+=" and t2.userName like '%"+params.get("respondents")+"%'  ";
		}
		if(params.containsKey("respondentsVirt")&&StringUtils.isNotEmpty(params.get("respondentsVirt"))){
//			strSQL+=" and t1.visitorToCompany like '%"+params.get("respondentsVirt")+"%'  ";
			strSQL+=" and t6.id="+params.get("respondentsVirt")+"  ";
		}
		
		if(params.containsKey("respondentsInfo")&&StringUtils.isNotEmpty(params.get("respondentsInfo"))){
			strSQL+=" and ( t2.userName like '%"+params.get("respondentsInfo")+"%' or t6.name like '%"+params.get("respondentsInfo")+"%'  or t2.userMobile like '%"+params.get("respondentsInfo")+"%')  ";
		}			
		if(params.containsKey("visitorOrderStatus")&&StringUtils.isNotEmpty(params.get("visitorOrderStatus"))){
			strSQL+=" and t1.visitorOrderStatus="+params.get("visitorOrderStatus")+"  ";
		}
		
		
		if(params.containsKey("visitorId")&&StringUtils.isNotEmpty(params.get("visitorId"))){
			strSQL+=" and t3.visitorOrderId="+params.get("visitorId")+"  ";
		}
		
		if(params.containsKey("objective")&&StringUtils.isNotEmpty(params.get("objective"))){
			strSQL+=" and t1.visitorReason like '%"+params.get("objective")+"%'  ";
		}
		if(params.containsKey("beginTime")&&StringUtils.isNotEmpty(params.get("beginTime"))){
			String beginTime=params.get("beginTime");
			if(params.containsKey("endTime")&&StringUtils.isNotEmpty(params.get("endTime"))){
				String endTime=params.get("endTime");
				strSQL+=" and (t3.visitorStartTime >='"+beginTime+" 00:00:00' "
						+ " and t3.visitorStartTime <= '"+endTime+" 23:59:59'  )";
//				sql.append(" and (o.dinnerTime>='"+beginTime+"' and o.dinnerTime<='"+endTime+"' ) ");
			}else{
				strSQL+="and  t3.visitorStartTime >= '"+beginTime+" 00:00:00'  ";
//				sql.append(" and  o.dinnerTime>='"+beginTime+"' ");
			}
		}else if(params.containsKey("endTime")&&StringUtils.isNotEmpty(params.get("endTime"))){
			String endTime=params.get("endTime");
			strSQL+=" and t3.visitorStartTime <= '"+endTime+" 23:59:59'   ";
//			sql.append(" and o.dinnerTime<='"+endTime+"'  ");
		}
		
		
		
		if(params.containsKey("createBeginTime")&&StringUtils.isNotEmpty(params.get("createBeginTime"))){
			String beginTime=params.get("createBeginTime");
			if(params.containsKey("createEndTime")&&StringUtils.isNotEmpty(params.get("createEndTime"))){
				String endTime=params.get("createEndTime");
				strSQL+=" and ( t3.visitorCreateTime >= '"+beginTime+" 00:00:00' "
						+ " and  t3.visitorCreateTime <= '"+endTime+" 23:59:59'   )";
//				sql.append(" and (o.dinnerTime>='"+beginTime+"' and o.dinnerTime<='"+endTime+"' ) ");
			}else{
				strSQL+="and   t3.visitorCreateTime >= '"+beginTime+" 00:00:00'  ";
//				sql.append(" and  o.dinnerTime>='"+beginTime+"' ");
			}
		}else if(params.containsKey("createEndTime")&&StringUtils.isNotEmpty(params.get("createEndTime"))){
			String endTime=params.get("createEndTime");
			strSQL+=" and  t3.visitorCreateTime <= '"+endTime+" 23:59:59'   ";
//			sql.append(" and o.dinnerTime<='"+endTime+"'  ");
		}
		
		
		
//		if(StringUtils.isNotBlank(paramValue)){
//			strSQL+=" and (t3.visitorName like '%"+paramValue+"%' or t3.visitorPhone like '%"+paramValue+"%' "
//					+ " or t3.visitorPassword like '%"+paramValue+"%' or t2.userName like '%"+paramValue+"%')";
//		}
			strSQL+=" order by t1.visitorOrderCreateTime desc";
			List<Map<String, Object>> list = getJdbcTemplate().queryForList(strSQL.toString());
		return list;
	}
	
	@Override
	public Page getVisitorOrderInfoList(Map<String,String> params,String orgIdS,Integer pageNo) {
		String strSQL="SELECT t3.visitorId,IFNULL(t3.visitorName,'') visitorName,t4.`name` organizationName,IFNULL(t3.visitorPhone,'') visitorPhone,IFNULL(t3.visitorCompanyName,'') visitorCompanyName,t1.visitorQrCode,"
				+ "t3.visitorPassword,t3.visitorStartTime,t3.visitorEndTime,t5.imageFaceUrl,"
				+ "t2.userName,t2.userMobile,t1.visitorOrderStatus,t6.name virName,t1.visitorToFloor,t1.visitorReason,t1.visitorOrderType,"
				+ " t1.visitorToOrgId,t3.userHeadUrl,t1.visitorToCompany,DATE_FORMAT(t3.visitorCreateTime,'%Y-%m-%d %H:%i') visitorCreateTime "
				+ " from tb_visitororder t1 "
				+ " LEFT join tb_user t2 on t1.visitorUserId=t2.ID"
				+ " LEFT join tb_visitorinfo t3 on t3.visitorOrderId=t1.visitorOrderId"
				+ " LEFT join tb_organization t4 on t4.ID=t2.organizationId"
				+ " LEFT join tb_virtualarchitecture t6 on t6.id=t2.virtualArchId"
				+ " LEFT JOIN tb_userimageinfo t5 on t5.userId=t3.visitorId"
				+ " where 1=1 ";
		if (StringUtils.isNotBlank(orgIdS)){
			strSQL+=" and (t4.ID IN ("+orgIdS+") OR t1.visitorToOrgId IN ("+orgIdS+"))";
		}
		
		if(null==params){
			strSQL+=" order by t1.visitorOrderCreateTime desc";
			return pagedQueryByJdbcTemplate(strSQL, pageNo, Integer.parseInt(params.get("pageSize")));
		}
		
		if(params.containsKey("name")&&StringUtils.isNotEmpty(params.get("name"))){
			strSQL+=" and t3.visitorName like '%"+params.get("name")+"%'  ";
		}
		if(params.containsKey("mobile")&&StringUtils.isNotEmpty(params.get("mobile"))){
			strSQL+=" and t3.visitorPhone like '%"+params.get("mobile")+"%'  ";
		}
		
		if(params.containsKey("visitorInfo")&&StringUtils.isNotEmpty(params.get("visitorInfo"))){
			strSQL+=" and ( t3.visitorName like '%"+params.get("visitorInfo")+"%' or t3.visitorPhone like '%"+params.get("visitorInfo")+"%' or t3.visitorCompanyName like '%"+params.get("visitorInfo")+"%')  ";
		}
		
		if(params.containsKey("respondents")&&StringUtils.isNotEmpty(params.get("respondents"))){
			strSQL+=" and t2.userName like '%"+params.get("respondents")+"%'  ";
		}
		if(params.containsKey("respondentsVirt")&&StringUtils.isNotEmpty(params.get("respondentsVirt"))){
//			strSQL+=" and t1.visitorToCompany like '%"+params.get("respondentsVirt")+"%'  ";
			strSQL+=" and t6.id="+params.get("respondentsVirt")+"  ";
		}
		
		if(params.containsKey("respondentsInfo")&&StringUtils.isNotEmpty(params.get("respondentsInfo"))){
			strSQL+=" and ( t2.userName like '%"+params.get("respondentsInfo")+"%' or t6.name like '%"+params.get("respondentsInfo")+"%'  or t2.userMobile like '%"+params.get("respondentsInfo")+"%')  ";
		}			
		if(params.containsKey("visitorOrderStatus")&&StringUtils.isNotEmpty(params.get("visitorOrderStatus"))){
			strSQL+=" and t1.visitorOrderStatus="+params.get("visitorOrderStatus")+"  ";
		}
		
		
		if(params.containsKey("visitorId")&&StringUtils.isNotEmpty(params.get("visitorId"))){
			strSQL+=" and t3.visitorOrderId="+params.get("visitorId")+"  ";
		}
		
		if(params.containsKey("objective")&&StringUtils.isNotEmpty(params.get("objective"))){
			strSQL+=" and t1.visitorReason like '%"+params.get("objective")+"%'  ";
		}
		if(params.containsKey("beginTime")&&StringUtils.isNotEmpty(params.get("beginTime"))){
			String beginTime=params.get("beginTime");
			if(params.containsKey("endTime")&&StringUtils.isNotEmpty(params.get("endTime"))){
				String endTime=params.get("endTime");
				strSQL+=" and ( t3.visitorStartTime >= '"+beginTime+" 00:00:00'  "
						+ " and  t3.visitorStartTime <= '"+endTime+" 23:59:59'   )";
//				sql.append(" and (o.dinnerTime>='"+beginTime+"' and o.dinnerTime<='"+endTime+"' ) ");
			}else{
				strSQL+="and  t3.visitorStartTime >= '"+beginTime+" 00:00:00' ";
//				sql.append(" and  o.dinnerTime>='"+beginTime+"' ");
			}
		}else if(params.containsKey("endTime")&&StringUtils.isNotEmpty(params.get("endTime"))){
			String endTime=params.get("endTime");
			strSQL+=" and  t3.visitorStartTime <= '"+endTime+" 23:59:59'   ";
//			sql.append(" and o.dinnerTime<='"+endTime+"'  ");
		}
		
		
		
		if(params.containsKey("createBeginTime")&&StringUtils.isNotEmpty(params.get("createBeginTime"))){
			String beginTime=params.get("createBeginTime");
			if(params.containsKey("createEndTime")&&StringUtils.isNotEmpty(params.get("createEndTime"))){
				String endTime=params.get("createEndTime");
				strSQL+=" and ( t3.visitorCreateTime >= '"+beginTime+" 00:00:00'  "
						+ " and  t3.visitorCreateTime <= '"+endTime+" 23:59:59'   )";
//				sql.append(" and (o.dinnerTime>='"+beginTime+"' and o.dinnerTime<='"+endTime+"' ) ");
			}else{
				strSQL+="and  t3.visitorCreateTime >= '"+beginTime+" 00:00:00'  ";
//				sql.append(" and  o.dinnerTime>='"+beginTime+"' ");
			}
		}else if(params.containsKey("createEndTime")&&StringUtils.isNotEmpty(params.get("createEndTime"))){
			String endTime=params.get("createEndTime");
			strSQL+=" and  t3.visitorCreateTime <= '"+endTime+" 23:59:59'    ";
//			sql.append(" and o.dinnerTime<='"+endTime+"'  ");
		}
		
		
		
//		if(StringUtils.isNotBlank(paramValue)){
//			strSQL+=" and (t3.visitorName like '%"+paramValue+"%' or t3.visitorPhone like '%"+paramValue+"%' "
//					+ " or t3.visitorPassword like '%"+paramValue+"%' or t2.userName like '%"+paramValue+"%')";
//		}
			strSQL+=" order by t1.visitorOrderCreateTime desc";
		return pagedQueryByJdbcTemplate(strSQL, pageNo, Integer.parseInt(params.get("pageSize")));
	}

	@Override
	public List<UserImageInfo> getUserImageInfo(Integer userId, String type) {
		String strHQL="from UserImageInfo where imageType=? and userId=?";
		List<UserImageInfo> list=getSession().createQuery(strHQL).setString(0,type).setInteger(1, userId).list();
		if(list!=null && list.size()>0){
			return list;
		}
		return null;
	}

	@Override
	public UserImageInfo getUserImageInfoById(Integer imageUrlId) {
		String strHQL="from UserImageInfo where imageId=?";
		List<UserImageInfo> list=getSession().createQuery(strHQL).setInteger(0,imageUrlId).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public void deleteUserImageInfoByUserId(Integer userId, String type) {
		String strSQL="delete from tb_userimageinfo where userid="+userId+" and imageType='"+type+"' ";
		getSession().createSQLQuery(strSQL).executeUpdate();
	}

	@Override
	public void updateUserImageInfoByUserId(Integer userId, String type) {
		String strSQL="UPDATE tb_userimageinfo set imageFacePlusId=NULL where userid="+userId+" and imageType='"+type+"' ";
		getSession().createSQLQuery(strSQL).executeUpdate();
	}

	@Override
	public VisitorInfo getVisItorInfo(String visitorOpenId) {
		String strHQL="from VisitorInfo where visitorOpenId=? and  visitorIdentification is null order by visitorStartTime desc";
		Query query=getSession().createQuery(strHQL);
		query.setString(0,visitorOpenId);
		query.setFirstResult(0);
		query.setMaxResults(1);
		List<VisitorInfo> list=query.list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public FaceProjectInfo getFaceProjectInfo(Integer projectId, String type) {
		String strHQL="from FaceProjectInfo where projectId=? and type=? and isEnabled=?";
		List<FaceProjectInfo> list=getSession().createQuery(strHQL).
				setInteger(0, projectId).setString(1,type).setString(2,"1").list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<FaceProjectInfo> getFaceProjectInfoList() {
		String strHQL="from FaceProjectInfo where isEnabled=?";
		List<FaceProjectInfo> list=getSession().createQuery(strHQL)
				.setString(0,"1").list();
		return list;
	}

	@Override
	public VisitorOrder getOrderByQrcodeKey(String qrcodeKey) {

		String strHQL="from VisitorOrder where visitorQrCode=?";
		List<VisitorOrder> list=getSession().createQuery(strHQL)
				.setString(0,qrcodeKey).list();
		if (list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public VisitorInfo getLastVisitorInfoByMobile(String telephone) {
		String sql = "SELECT t1.* FROM tb_visitorinfo t1 LEFT JOIN tb_visitororder t2 ON t1.visitorId = t2.visitorOrderId WHERE t1.visitorPhone = ? AND t2.visitorOrderType = 4 ORDER BY visitorId DESC LIMIT 1";
		return (VisitorInfo) getSession().createSQLQuery(sql).addEntity(VisitorInfo.class).setString(0,telephone).uniqueResult();
	}

	@Override
	public VisitorInfo getVisitorInfoByQrCode(String qrCode) {
		String sql = "SELECT * FROM tb_visitorinfo WHERE visitorOrderId = (SELECT visitorOrderId FROM tb_visitororder WHERE visitorQrCode = ?) LIMIT 1";
		return (VisitorInfo) getSession().createSQLQuery(sql).addEntity(VisitorInfo.class).setString(0,qrCode).uniqueResult();
	}

	@Override
	public VisitorOrder getOrderByLingLingId(String linglingId) {
		String strHQL="from VisitorOrder where linglingId=?";
		List<VisitorOrder> list=getSession().createQuery(strHQL)
				.setString(0,linglingId).list();
		if (list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public void updateVisitorOrder(Integer orderId,String linglingId,String qrcodeKey,Integer codeId) {
		String strSQL="UPDATE tb_visitorOrder set visitorQrCodeId = "+codeId+",visitorQrCode='"+qrcodeKey+"',linglingId = '"+linglingId+"' where visitorOrderId = "+orderId;
		getSession().createSQLQuery(strSQL).executeUpdate();
	}

	
}
