package com.palmnest.dao.lingling.impl;

import cn.superdesk.libs.common.json.JsonUtils;

import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.LingLingUserGroupDto;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.lingling.LingLingDao;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.VisitorOrder;
import com.palmnest.model.lingling.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author HIAPAD
 * @Description TODO
 * @Date 2018/12/7 12:14
 **/
@Slf4j
@Repository(value = "lingLingDao")
public class LingLingDaoImpl extends GenericDaoHibernate<Object, Long> implements LingLingDao {


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


	@Override
	public LingLingDevice getByDeviceId(Integer deviceId,Integer orgId) {
		String               hql  = "from LingLingDevice where deviceId=? and orgId=?";
		List<LingLingDevice> list = getSession().createQuery(hql).setInteger(0, deviceId).setInteger(1, orgId).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Page getDeviceList(Map<String, String> paramMap) {

		String sql = "select * from tb_lingling_device where 1=1 and isEnable=1";

		if (StringUtils.isNotBlank(paramMap.get("deviceType"))) {
			sql += " and deviceType=" + paramMap.get("deviceType");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceStatus"))) {
			sql += " and deviceStatus=" + paramMap.get("deviceStatus");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceId"))) {
			sql += " and deviceId=" + paramMap.get("deviceId");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceCode"))) {
			//sql += " and deviceCode='" + paramMap.get("deviceCode") + "'";
			  sql += " and deviceCode  like '%" + paramMap.get("deviceCode") + "%'";
		}
		if (StringUtils.isNotBlank(paramMap.get("createTime"))) {
			sql += " and createTime=" + paramMap.get("createTime");
		}
		if (StringUtils.isNotBlank(paramMap.get("orgId"))) {
			sql += " and orgId in (" + paramMap.get("orgId") + ")";
		}
		sql += " order by createTime";

		return pagedQueryByJdbcTemplate(sql.toString(), Integer.parseInt(paramMap.get("pageNo")), Integer.parseInt(paramMap.get("pageSize")));
	}

	@Override
	public void deleteByGroupId(Long groupId) {
		String sql = "delete from tr_perm_group_device where device_perm_group_id=" + groupId;
		int    i   = getSession().createSQLQuery(sql).executeUpdate();
	}

	@Override
	public Page getDeviceGroupList(Map<String, String> paramMap) {

		String sql = "select t1.* from tb_device_perm_group t1 LEFT JOIN tr_perm_group_device t2 ON t1.ID=t2.device_perm_group_id LEFT JOIN tb_lingling_device t3 ON t3.id=t2.device_id where 1=1";

		if (StringUtils.isNotBlank(paramMap.get("groupName"))) {
			sql += " and t1.group_name like '%" + paramMap.get("groupName") + "%'";
		}
		if (StringUtils.isNotBlank(paramMap.get("groupType"))) {
			sql += " and t1.group_type=" + paramMap.get("groupType");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceId"))) {
			sql += " and t3.deviceId=" + paramMap.get("deviceId");
		}
		if (StringUtils.isNotBlank(paramMap.get("orgId"))) {
			sql += " and t1.orgId in (" + paramMap.get("orgId") + ")";
		}
		sql += " GROUP BY t1.ID order by create_time";
		return pagedQueryByJdbcTemplate(sql.toString(), Integer.parseInt(paramMap.get("pageNo")), Integer.parseInt(paramMap.get("pageSize")));
	}

	@Override
	public List<LingLingDevice> getDeviceList(Integer isEnable, Integer orgId) {

		String sql = "from LingLingDevice where isEnable=? and orgId=?";

		List<LingLingDevice> deviceList = getSession().createQuery(sql).setInteger(0, isEnable).setInteger(1, orgId).list();
		return deviceList;
	}

	@Override
	public LingLingDevice getById(Long id) {
		String               hql  = "from LingLingDevice where id=?";
		List<LingLingDevice> list = getSession().createQuery(hql).setLong(0, id).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public DevicePermGroup getDeviceGroupById(Long id) {
		String                hql  = "from DevicePermGroup where id=?";
		List<DevicePermGroup> list = getSession().createQuery(hql).setLong(0, id).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void deleteUserGroupByGroupId(Long groupId) {
		String sql = "delete from tr_perm_group_user where device_perm_group_id=" + groupId;
		int    i   = getSession().createSQLQuery(sql).executeUpdate();
	}

	@Override
	public List<DevicePermGroup> getDevicePermGroupByOrgId(Integer orgId, Integer groupType) {

		String sql = "from DevicePermGroup where groupType=? and orgId=?";
		return getSession().createQuery(sql).setInteger(0, groupType).setInteger(1, orgId).list();
	}

	@Override
	public int deleteUserGroupByUserIds(String userIds) {
		String sql = "delete from tr_perm_group_user where user_id in (" + userIds + ")";
		return getSession().createSQLQuery(sql).executeUpdate();
	}

	@Override
	public LingLingCard getCardByCardId(String cardUid) {
		String             sql  = "from LingLingCard where cardCode=?";
		List<LingLingCard> list = getSession().createQuery(sql).setString(0, cardUid).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Page getPassHistory(Map<String, String> paramMap) {
		
		String sql = "SELECT DISTINCT t1.passType,t1.id,IFNULL(t2.deviceType,'考拉设备') deviceType,t2.deviceId,CONCAT(IFNULL(t2.deviceName,''),IFNULL(t1.deviceName,'')) deviceName,t1.mobile,t1.userName,t1.type,t1.cardUid,t1.openTime,t1.qrcodeKey,CONCAT(IFNULL(org2.`name`,''),IFNULL(org.`name`,'')) orgName  " +
				" FROM tb_lingling_log t1 " +
				"		LEFT JOIN tb_lingling_device t2 ON t1.deviceCode = t2.deviceCode " +
				"		LEFT JOIN tb_organization org  on org.id = t2.orgId  " +
				"		LEFT JOIN tb_organization org2 ON org2.id = t1.orgId  " +
				" WHERE 1=1 and t1.type <> 4 AND t2.isEnable = 1  ";

		
		if (StringUtils.isNotBlank(paramMap.get("passType")) && !"0".equals(String.valueOf(paramMap.get("passType")))) {
			sql += " and t1.passType=" + paramMap.get("passType");
		}
		
		if (StringUtils.isNotBlank(paramMap.get("deviceType"))) {
			sql += " and t2.deviceType=" + paramMap.get("deviceType");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceId"))) {
			sql += " and t1.deviceId=" + paramMap.get("deviceId");
		}
		if (StringUtils.isNotBlank(paramMap.get("mobile"))) {
			sql += " and t1.mobile=" + paramMap.get("mobile");
		}

		
		
		if (StringUtils.isNotBlank(paramMap.get("passPersonInfo"))) {//通行人信息 姓名、手机号、企业
			sql += " and ( t1.mobile like '%" + paramMap.get("passPersonInfo") + "%'   or t1.userName like '%" + paramMap.get("passPersonInfo") + "%' )";
		}
		
		if (StringUtils.isNotBlank(paramMap.get("passEqInfo"))) {//通行设备信息 设备类型、ID、名称 
			sql += " and ( t1.deviceId like '%" + paramMap.get("passPersonInfo") + "%'   or t1.deviceName like '%" + paramMap.get("passPersonInfo") + "%' )";
		}		
		
		
		if (StringUtils.isNotBlank(paramMap.get("userType"))) {
			if ("1".equals(paramMap.get("userType"))) {
				// 员工类型 对应日志表中的员工二维码(1)和NFC卡类型(3)
				sql += " and t1.type in (1,3)";
			} else if ("2".equals(paramMap.get("userType"))) {
				// 访客类型 对应日志表中的访客二维码(2)
				sql += " and t1.type=2";
			}
		}

		if (StringUtils.isNotBlank(paramMap.get("cardCode"))) {
			sql += " and t1.cardUid='" + paramMap.get("cardCode") + "'";
		}
		if (StringUtils.isNotBlank(paramMap.get("orgId"))) {
			sql += " and (t2.orgId in (" + paramMap.get("orgId") + ") or  t1.orgId in (" + paramMap.get("orgId") + ") )";
		}

		if (StringUtils.isNotBlank(paramMap.get("startTime"))) {
			sql += " and t1.openTime >= str_to_date('" + paramMap.get("startTime") + " 00:00:00','%Y-%m-%d %H:%i:%s') ";
		}
		if (StringUtils.isNotBlank(paramMap.get("endTime"))) {
			sql += " and t1.openTime <= str_to_date('" + paramMap.get("endTime") + " 23:59:59','%Y-%m-%d %H:%i:%s') ";
		}

		sql += " order by t1.openTime desc";
		return pagedQueryByJdbcTemplate(sql.toString(), Integer.parseInt(paramMap.get("pageNo")), Integer.parseInt(paramMap.get("pageSize")));
	}

	@Override
	public List<LingLingDevice> getDevicesByGroup(Long groupId, Integer isEnable) {

		String sql = "SELECT td.* " +
				"	FROM tb_lingling_device td " +
				"		LEFT JOIN tr_perm_group_device tgd ON td.id = tgd.device_id " +
				"		LEFT JOIN tb_device_perm_group tg ON tg.ID = tgd.device_perm_group_id " +
				"	WHERE tg.ID=" + groupId;

		if (isEnable != null) {
			sql += " AND td.isEnable =" + isEnable;
		}

		sql += " GROUP BY td.id";

		return getSession().createSQLQuery(sql).addEntity(LingLingDevice.class).list();
	}

	@Override
	public VisitorMachine getVisitorMachine(Long machineId) {
		String hql = " from VisitorMachine where id=?";
		return (VisitorMachine) getSession().createQuery(hql).setLong(0, machineId).uniqueResult();
	}

	@Override
	public VisitorMachine getVisitorMachineByOrgId(Integer orgId) {
		String hql = " from VisitorMachine where orgId=?";
		return (VisitorMachine) getSession().createQuery(hql).setLong(0, orgId).uniqueResult();
	}
	
	@Override
	public VisitorMachine getVisitorMachineByDeviceCode(String deviceCode) {
		String hql = " from VisitorMachine where deviceCode=?";
		return (VisitorMachine) getSession().createQuery(hql).setString(0, deviceCode).uniqueResult();
	}

	@Override
	public LingLingVisitorInfo getVisitorInfoByTelephone(String telephone) {
		String hql = " from LingLingVisitorInfo where telephone=?";
		return (LingLingVisitorInfo) getSession().createQuery(hql).setString(0, telephone).uniqueResult();
	}

	@Override
	public LingLingVisitorInfo getVisitorInfoByIdenNumber(String idenNumber) {
		String hql = " from LingLingVisitorInfo where idenNumber=?";
		return (LingLingVisitorInfo) getSession().createQuery(hql).setString(0, idenNumber).uniqueResult();
	}

	@Override
	public VisitorOrder getMachineVisitorInfo(String codeId) {
		String hql = " from VisitorOrder where visitorQrCodeId=?";
		return (VisitorOrder) getSession().createQuery(hql).setString(0, codeId).uniqueResult();
	}
	
	@Override
	public VisitorOrder getMachineVisitorByQr(String qrcodeKey) {
		String hql = " from VisitorOrder where visitorQrCode=?";
		return (VisitorOrder) getSession().createQuery(hql).setString(0, qrcodeKey).uniqueResult();
	}

	@Override
	public List<Integer> getUserIdsByGroupId(Long groupId) {
		String sql = " SELECT user_id FROM tr_perm_group_user WHERE device_perm_group_id=?";
		return getSession().createSQLQuery(sql).setLong(0, groupId).list();
	}

	@Override
	public void deleteUserGroup(Integer userId, Long groupId) {
		String sql = "delete from tr_perm_group_user where user_id=? AND device_perm_group_id=?";
		getSession().createSQLQuery(sql).setInteger(0, userId).setLong(1, groupId).executeUpdate();
	}

	@Override
	public void saveUserGroup(Integer id, String groupId) {
		String sql = "INSERT INTO tr_perm_group_user(device_perm_group_id, user_id, lastUpdateTime) VALUES (?,?,?)";
		System.out.println(sql);
		Query query =getSession().createSQLQuery(sql).setInteger(0, Integer.parseInt(groupId)).setInteger(1, id).setTimestamp(2, new Date());
		System.out.println("saveUserGroup-query:"+query.getQueryString());
		int result=query.executeUpdate();
		System.out.println("saveUserGroup-result:"+result);
//		String sql = "INSERT INTO tr_perm_group_user(device_perm_group_id, user_id, lastUpdateTime)  VALUES (?,?,?)";
//		getSession().createSQLQuery(sql).setString(0, groupId).setInteger(1, id).setTimestamp(2, new Date()).executeUpdate();
	}

	@Override
	public DevicePermGroup getByUserInfo(Integer orgId) {
		StringBuilder sql = new StringBuilder();
		sql.append(" from DevicePermGroup ");
		sql.append(" where groupType=2 and orgId=?  ");
		List<DevicePermGroup> list = getSession().createQuery(sql.toString()).setInteger(0, orgId).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}


	@Override
	public LingLingDevice getByDeviceCode(String deviceCode) {
		String               hql  = "from LingLingDevice where isEnable=1 and deviceCode=? ";
		List<LingLingDevice> list = getSession().createQuery(hql).setString(0, deviceCode).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	
	@Override
	public String getDeviceIdsByMethedType(int methedType,Integer userId) {
		StringBuilder sb=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT l.deviceId) deviceIds FROM tr_perm_group_user u ");
		sb.append(" INNER JOIN tr_perm_group_device d ON d.device_perm_group_id = u.device_perm_group_id ");
		sb.append(" INNER JOIN tb_lingling_device l ON l.id = d.device_id ");
		sb.append(" WHERE u.user_id ="+userId);
		sb.append(" AND l.methedType ="+methedType);
		sb.append(" GROUP BY u.user_id ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			return list.get(0).get("deviceIds") == null ? "" : list.get(0).get("deviceIds").toString();
		}
		return "";
	}


	@Override
	public List<Integer> getGroupIds(String userIds) {
		List<Integer> resList=new ArrayList<Integer>();
		StringBuilder sb=new StringBuilder("");
		sb.append(" SELECT GROUP_CONCAT(device_perm_group_id) device_perm_group_id FROM tr_perm_group_user WHERE user_id IN ("+userIds+") GROUP BY user_id LIMIT 1");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("device_perm_group_id")||StringUtils.isBlank(map.get("device_perm_group_id").toString())){
				return null;
			}
			String groupIds=map.get("device_perm_group_id").toString();
			if(StringUtils.isBlank(groupIds)){
				return null;
			}
			String [] ids=groupIds.split(",");
			for(String id:ids){
				Integer groupId=Integer.parseInt(id);
				if(null==groupId){
					continue;
				}
				resList.add(groupId);
			}
			return resList;
		}
		return resList;
	}


	@Override
	public int getGroupIdsByGroupAndUser(Integer userId,
			Integer groupId) {
		StringBuilder sb=new StringBuilder("");
		sb.append(" select device_perm_group_id from tr_perm_group_user where user_id="+userId+" and device_perm_group_id="+groupId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if(!CollectionUtils.isEmpty(list)){
			return list.size();
		}
		return 0;
	}


	@Override
	public LingLingDeveloper findByOrgId(Integer orgId) {
		StringBuilder sb=new StringBuilder("from LingLingDeveloper where 1=1 ");
		if(null==orgId){
			sb.append(" and isDefault=1 ");
		}else{
			sb.append(" and orgId="+orgId );
		}
		List<LingLingDeveloper> list = getSession().createQuery(sb.toString()).list();
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}


	@Override
	public List<Integer> findOrgIds() {
		List<Integer> resList=new ArrayList<Integer>();
		StringBuilder sb=new StringBuilder(" SELECT GROUP_CONCAT(orgId) orgIds FROM tb_lingling_developer WHERE 1 = 1 AND orgId IS NOT NULL ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("orgIds")||StringUtils.isBlank(map.get("orgIds").toString())){
				return null;
			}
			String orgIds=map.get("orgIds").toString();
			if(StringUtils.isBlank(orgIds)){
				return null;
			}
			String [] ids=orgIds.split(",");
			for(String id:ids){
				Integer orgId=Integer.parseInt(id);
				if(null==orgId){
					continue;
				}
				resList.add(orgId);
			}
			return resList;
		}
		return null;
	}
	
//	@Override
//	public LingLingDevice getByDeviceId(Integer deviceId,Integer orgId) {
//		String               hql  = "from LingLingDevice where deviceId=? and orgId=? ";
//		List<LingLingDevice> list = getSession().createQuery(hql).setInteger(0, deviceId).setInteger(1, orgId).list();
//		if (null != list && list.size() > 0) {
//			return list.get(0);
//		}
//		return null;
//	}


	@Override
	public String getDeviceIdsByGroupId(Integer groupId) {
		StringBuilder sql=new StringBuilder("SELECT GROUP_CONCAT(DISTINCT d.deviceId) deviceIds FROM tr_perm_group_device g,tb_lingling_device d WHERE g.device_id=d.id and device_perm_group_id ="+groupId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("deviceIds")||StringUtils.isBlank(map.get("deviceIds").toString())){
				return "";
			}
			return map.get("deviceIds").toString();
		}
		return "";
	}


	@Override
	public String getSdkkeyByGroupId(Long groupId) {
		StringBuilder sb=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT b.sdkkey) sdkkey FROM tr_perm_group_device a LEFT JOIN tb_lingling_device b ON a.device_id = b.id WHERE b.sdkkey is not null and  a.device_perm_group_id ="+groupId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("sdkkey")||StringUtils.isBlank(map.get("sdkkey").toString())){
				return "";
			}
			return map.get("sdkkey").toString();
		}
		return null;
	}


	@Override
	public String getLinglingIdsByGroupId(Long groupId) {
		StringBuilder sb=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT u.lingLingId) lingLingId FROM tr_perm_group_user g, tb_user u WHERE u.id = g.user_id AND u.lingLingId IS NOT NULL AND g.device_perm_group_id ="+groupId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("lingLingId")||StringUtils.isBlank(map.get("lingLingId").toString())){
				return "";
			}
			return map.get("lingLingId").toString();
		}
		return null;
	}


	@Override
	public Map<String, Object> getUserGroupInfo(Integer userId) {
		String sql=" SELECT gu.device_perm_group_id groupId, gu.user_id userId, dg.group_type groupType FROM tr_perm_group_user gu, tb_device_perm_group dg WHERE gu.device_perm_group_id = dg.id AND gu.user_id ="+userId;
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql);
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			return map;
		}
		return null;
	}


	@Override
	public String getDeviceNamesByGroupId(String groupId) {
		StringBuilder sb=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT d.deviceName) deviceName FROM tr_perm_group_device g, tb_lingling_device d WHERE g.device_id = d.id AND d.isEnable=1 AND g.device_perm_group_id ="+groupId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sb.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("deviceName")||StringUtils.isBlank(map.get("deviceName").toString())){
				return "";
			}
			return map.get("deviceName").toString();
		}
		return null;
	}


	@Override
	public String getDeviceIdsByUserId(Integer userId) {
		StringBuilder sql=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT l.deviceId) deviceIds FROM tr_perm_group_user u, tr_perm_group_device d, tb_lingling_device l WHERE u.device_perm_group_id = d.device_perm_group_id AND d.device_id = l.id AND u.user_id ="+userId);
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			if(null==map||null==map.get("deviceIds")||StringUtils.isBlank(map.get("deviceIds").toString())){
				return "";
			}
			return map.get("deviceIds").toString();
		}
		return "";
	}


	@Override
	public void saveCardAndUser(Integer userId, Long cardId) {
		String sql = "INSERT INTO tr_user_lingling_card (`card_id`, `user_id`) VALUES (?,?)";
		getSession().createSQLQuery(sql).setLong(0, cardId).setInteger(1, userId).executeUpdate();
	}

	@Override
	public void savePermGroupDevice(Long devicePermGroupId, Long deviceId) {
		String sql = "INSERT INTO tr_perm_group_device (`device_perm_group_id`, `device_id`) VALUES (?,?)";
		getSession().createSQLQuery(sql).setLong(0, devicePermGroupId).setLong(1, deviceId).executeUpdate();
	}


//	@Override
//	public String getUserIdsByGroupId(String groupId) {
//		StringBuilder sql=new StringBuilder(" SELECT GROUP_CONCAT(DISTINCT u.user_id) userIds FROM tr_perm_group_user u WHERE u.device_perm_group_id ="+groupId);
//		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
//		if (list != null && list.size() > 0) {
//			Map<String, Object> map=list.get(0);
//			if(null==map||null==map.get("userIds")||StringUtils.isBlank(map.get("userIds").toString())){
//				return "";
//			}
//			return map.get("userIds").toString();
//		}
//		return "";
//	}


	@Override
	public List<Map<String, Object>> getGroupUser(String groupId) {
		StringBuilder sql=new StringBuilder(" SELECT u.id userId, u.userName mobile, u.userMobile userName FROM tb_user u, tr_perm_group_user g WHERE g.user_id = u.id AND g.device_perm_group_id ="+groupId);
		
		sql.append(" order by u.id  ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}


	@Override
	public Map<String, Object> getUserCardInfo(Long cardId) {
		String sql=" SELECT c.user_id userId, u.userName userName, u.userMobile userMobile FROM tr_user_lingling_card c, tb_user u WHERE c.user_id = u.id AND c.card_id = "+cardId;
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql);
		if (list != null && list.size() > 0) {
			Map<String, Object> map=list.get(0);
			return map;
		}
		return null;
	}


	@Override
	public DevicePermGroup getGroupByUserId(Integer userId) {
		String sql = "SELECT g.* FROM tr_perm_group_user gu, tb_device_perm_group g WHERE g.id = gu.device_perm_group_id AND gu.user_id =" + userId;
		List<DevicePermGroup> list=getSession().createSQLQuery(sql).addEntity(DevicePermGroup.class).list();
		if(!CollectionUtils.isEmpty(list)){
			return list.get(0);
		}
		return null;
	}


	@Override
	public LingLingCard getCardByUserId(Integer userId) {
		String sql = " SELECT c.id, c.card_code cardCode, c.create_time createTime FROM tr_user_lingling_card l, tb_lingling_card c WHERE c.id = l.card_id AND l.user_id = " + userId;
		List<LingLingCard> list=getSession().createSQLQuery(sql).addEntity(LingLingCard.class).list();
		if(!CollectionUtils.isEmpty(list)){
			return list.get(0);
		}
		return null;
	}


	@Override
	public void delCardAndUser(Long cardId) {
		String sql = "delete from tr_user_lingling_card where card_id=? ";
		getSession().createSQLQuery(sql).setLong(0, cardId).executeUpdate();
		
	}


	@Override
	public int updatePermGroupUser(Long groupId,String userIds,int type) {
		StringBuilder sql = new StringBuilder( "update tr_perm_group_user set lastUpdateTime=SYSDATE() where device_perm_group_id=? ");
		if(1 == type){
			sql.append(" and user_id="+userIds);
		}else if(2 == type){
			sql.append(" and user_id in ("+userIds+") ");
		}else if(3 == type){
			//userIds为linglingId
			sql.append(" and user_id in (select id from tb_user where lingLingId in ("+userIds+") ) ");
		}
		return getSession().createSQLQuery(sql.toString()).setLong(0, groupId).executeUpdate();
	}


//	@Override
//	public void saveUserGroupList(String lingLingIds, String groupId) {
//		String sql = "INSERT INTO tr_perm_group_user (device_perm_group_id, user_id, lastUpdateTime) SELECT "+groupId+", id, SYSDATE() FROM tb_user WHERE lingLingId IN ("+lingLingIds+")";
//		System.out.println("saveUserGroupList-sql:"+sql);
//		SQLQuery query=getSession().createSQLQuery(sql);
//		int result=query.executeUpdate();
//		System.out.println("saveUserGroupList-result:"+result);
//	}


	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> getUserIdByLingLingIds(String linglingIds) {
//		String sql="select ID as id from tb_user where lingLingId in ("+linglingIds+")";
//		System.out.println("getUserIdByLingLingIds-sql:"+sql);
//		List<Integer> list = this.getJdbcTemplate().queryForList(sql,Integer.class);
//		System.out.println("getUserIdByLingLingIds-list1:"+JsonUtils.toJson(list));
//		if(CollectionUtils.isEmpty(list)){
			List<Integer> list = new ArrayList<Integer>();
			String hql="from AppUser where lingLingId in ("+linglingIds+")";
			System.out.println("getUserIdByLingLingIds-hql:"+hql);
			Query query=this.getSession().createQuery(hql);
			System.out.println("getUserIdByLingLingIds-query:"+query.getQueryString());
			List<AppUser> userList=query.list();
			System.out.println("getUserIdByLingLingIds-userList:"+JsonUtils.toJson(userList));
			if(CollectionUtils.isEmpty(userList)){
				return list;
			}
			for(AppUser user:userList){
				if(null == user || null == user.getId()){
					continue;
				}
				list.add(user.getId());
			}
//		}
//		System.out.println("getUserIdByLingLingIds-list2:"+JsonUtils.toJson(list));
		return list;
	}


	@Override
	public List<Map<String, Object>> getExPassHistory(Map<String, String> paramMap) {
		String sql = "SELECT DISTINCT t1.passType,t1.id,IFNULL(t2.deviceType,'考拉设备') deviceType,t2.deviceId,CONCAT(IFNULL(t2.deviceName,''),IFNULL(t1.deviceName,'')) deviceName,t1.mobile,t1.userName,CONCAT(t1.userName, ' ', t1.mobile) userInfo,t1.type,t1.cardUid,t1.openTime,t1.qrcodeKey,CONCAT(IFNULL(org2.`name`,''),IFNULL(org.`name`,'')) orgName  " +
				" FROM tb_lingling_log t1 " +
				"		LEFT JOIN tb_lingling_device t2 ON t1.deviceCode = t2.deviceCode " +
				"		LEFT JOIN tb_organization org  on org.id = t2.orgId  " +
				"		LEFT JOIN tb_organization org2 ON org2.id = t1.orgId  " +
				" WHERE 1=1 and t1.type <> 4 AND t2.isEnable = 1  ";
		if (StringUtils.isNotBlank(paramMap.get("passType")) && !"0".equals(String.valueOf(paramMap.get("passType")))) {
			sql += " and t1.passType=" + paramMap.get("passType");
		}
		
		if (StringUtils.isNotBlank(paramMap.get("deviceType"))) {
			sql += " and t2.deviceType=" + paramMap.get("deviceType");
		}
		if (StringUtils.isNotBlank(paramMap.get("deviceId"))) {
			sql += " and t1.deviceId=" + paramMap.get("deviceId");
		}
		if (StringUtils.isNotBlank(paramMap.get("mobile"))) {
			sql += " and t1.mobile=" + paramMap.get("mobile");
		}

		
		
		if (StringUtils.isNotBlank(paramMap.get("passPersonInfo"))) {//通行人信息 姓名、手机号、企业
			sql += " and ( t1.mobile like '%" + paramMap.get("passPersonInfo") + "%'   or t1.userName like '%" + paramMap.get("passPersonInfo") + "%' )";
		}
		
		if (StringUtils.isNotBlank(paramMap.get("passEqInfo"))) {//通行设备信息 设备类型、ID、名称 
			sql += " and ( t1.deviceId like '%" + paramMap.get("passPersonInfo") + "%'   or t1.deviceName like '%" + paramMap.get("passPersonInfo") + "%' )";
		}		
		
		
		if (StringUtils.isNotBlank(paramMap.get("userType"))) {
			if ("1".equals(paramMap.get("userType"))) {
				// 员工类型 对应日志表中的员工二维码(1)和NFC卡类型(3)
				sql += " and t1.type in (1,3)";
			} else if ("2".equals(paramMap.get("userType"))) {
				// 访客类型 对应日志表中的访客二维码(2)
				sql += " and t1.type=2";
			}
		}

		if (StringUtils.isNotBlank(paramMap.get("cardCode"))) {
			sql += " and t1.cardUid='" + paramMap.get("cardCode") + "'";
		}
		if (StringUtils.isNotBlank(paramMap.get("orgId"))) {
			sql += " and (t2.orgId in (" + paramMap.get("orgId") + ") or  t1.orgId in (" + paramMap.get("orgId") + ") )";
		}

		if (StringUtils.isNotBlank(paramMap.get("startTime"))) {
			sql += " and t1.openTime >= str_to_date('" + paramMap.get("startTime") + " 00:00:00','%Y-%m-%d %H:%i:%s') ";
		}
		if (StringUtils.isNotBlank(paramMap.get("endTime"))) {
			sql += " and t1.openTime <= str_to_date('" + paramMap.get("endTime") + " 23:59:59','%Y-%m-%d %H:%i:%s') ";
		}

		sql += " order by t1.openTime desc";
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}


	@Override
	public List<Map<String, Object>> getPassDate(Map<String, Object> params) {
		StringBuilder sql=new StringBuilder("");
		sql.append(" SELECT ");
		sql.append(" (  ");
		sql.append(" CASE  ");
		sql.append(" WHEN t.M = 0 AND t.`HOUR` < 10 THEN ");
		sql.append(" CONCAT('0',t.`HOUR`,':00-','0',t.`HOUR`,':30') ");
		sql.append(" WHEN t.M = 0 AND t.`HOUR` > 9 THEN ");
		sql.append(" CONCAT(t.`HOUR`,':00-',t.`HOUR`,':30') ");
		sql.append(" WHEN t.M = 1 AND t.`HOUR` < 9 THEN ");
		sql.append(" CONCAT('0',t.`HOUR`,':30-','0',(t.`HOUR` + 1),':00') ");
		sql.append(" WHEN t.M = 1 AND t.`HOUR` = 9 THEN ");
		sql.append(" CONCAT('0',t.`HOUR`,':30-',(t.`HOUR` + 1),':00') ");
		sql.append(" WHEN t.M = 1 AND t.`HOUR` > 9 THEN ");
		sql.append(" CONCAT(t.`HOUR`,':30-',(t.`HOUR` + 1),':00') ");
		sql.append(" ELSE ''  ");
		sql.append(" END ");
		sql.append(" ) time, ");
		sql.append(" t.Count count ");
		sql.append(" FROM ");
		sql.append(" ( ");
		sql.append(" SELECT HOUR (e.openTime) AS HOUR, FLOOR(MINUTE(e.openTime) / 30) AS M, COUNT(e.id) AS Count ");
		sql.append(" FROM tb_lingling_log e, ");
		sql.append(" ( SELECT d.id, d.deviceId FROM tb_lingling_device d WHERE d.orgId = "+params.get("orgId")+" ) ld ");
		sql.append(" WHERE 1 = 1 AND e.deviceId = ld.deviceId AND DATE_FORMAT(e.openTime, '%Y-%m-%d') = '"+params.get("date")+"' ");
		sql.append(" AND e.passType = 2  ");
		if(params.containsKey("type") && null != params.get("type") && StringUtils.isNotBlank(params.get("type").toString()) && 0 != Integer.parseInt(params.get("type").toString())){
			sql.append(" AND e.type = "+params.get("type"));
		}
		sql.append(" GROUP BY FLOOR(MINUTE(e.openTime) / 30), HOUR (e.openTime) ");
		sql.append(" ORDER BY e.openTime, HOUR (e.openTime) ");
		sql.append(" ) t ");
		return getJdbcTemplate().queryForList(sql.toString());
	}


	@Override
	public List<Map<String, Object>> getPassMonth(Map<String, Object> params) {
		StringBuilder sql=new StringBuilder("");
		sql.append(" SELECT DATE_FORMAT(e.openTime, '%Y-%m-%d') time, count(e.id) count ");
		sql.append(" FROM tb_lingling_log e, ");
		sql.append(" 	( SELECT d.id, d.deviceId FROM tb_lingling_device d WHERE d.orgId = "+params.get("orgId")+" ) ld ");
		sql.append(" WHERE e.deviceId = ld.deviceId ");
		sql.append(" AND DATE_FORMAT(e.openTime, '%Y-%m') = '"+params.get("date")+"' ");
		if(params.containsKey("type") && null != params.get("type") && StringUtils.isNotBlank(params.get("type").toString()) && 0 != Integer.parseInt(params.get("type").toString())){
			sql.append(" AND e.type = "+params.get("type"));
		}
		sql.append(" GROUP BY DATE_FORMAT(e.openTime, '%Y-%m-%d') ");
		sql.append(" ORDER BY DATE_FORMAT(e.openTime, '%Y-%m-%d') ");
		return getJdbcTemplate().queryForList(sql.toString());
	}


	@Override
	public List<Map<String, Object>> getCardByUserIds(String userIds) {
		String sql="SELECT DISTINCT ud.user_id, ud.card_id, d.card_code FROM tr_user_lingling_card ud, tb_lingling_card d WHERE ud.card_id = d.id AND ud.user_id in ("+userIds+")";
		return getJdbcTemplate().queryForList(sql);
	}
}
