package com.uas.account.dao;

import com.alibaba.druid.util.StringUtils;
import com.uas.account.core.Page;
import com.uas.account.entity.*;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Repository
public class UserDaoImpl extends BaseDao implements UserDao {

	@Override
	public User save(User user) {
		if (user.getId() == null && !StringUtils.isEmpty(user.getUid())) {
			Long id = null;
			if (null == user.getSpaceId()) {
				id = jdbcTemplate.queryForObject("select min(id) from ac$users where appId=? and uid_=?", Long.class,
						user.getAppId(), user.getUid());
			} else {
				id = jdbcTemplate.queryForObject("select min(id) from ac$users where appId=? and uid_=? and spaceId=?",
						Long.class, user.getAppId(), user.getUid(), user.getSpaceId());
			}
			user.setId(id);
		}
		if (user.getId() == null) {
			user.setId(generateId("ac$user_seq"));
			jdbcTemplate.update(
					"insert into ac$users(id,appId,spaceId,spaceUID,spaceDialectUID,uid_,secondUID,dialectUID,name,password,salt,hr) values (?,?,?,?,?,?,?,?,?,?,?,?)",
					user.getId(), user.getAppId(), user.getSpaceId(), user.getSpaceUID(), user.getSpaceDialectUID(),
					user.getUid(), user.getSecondUID(), user.getDialectUID(), user.getName(), user.getPassword(),
					user.getSalt(), user.getHr());
		} else {
			jdbcTemplate.update(
					"update ac$users set appId=?,spaceId=?,spaceUID=?,spaceDialectUID=?,uid_=?,secondUID=?,dialectUID=?,name=?,password=?,salt=?,hr=? where id=?",
					user.getAppId(), user.getSpaceId(), user.getSpaceUID(), user.getSpaceDialectUID(), user.getUid(),
					user.getSecondUID(), user.getDialectUID(), user.getName(), user.getPassword(), user.getSalt(),
					user.getHr(), user.getId());
		}
		return user;
	}

	@Override
	public User findOne(String appId, Long spaceId, String uid) {
		try {
			List<User> users = null;
			if (null == spaceId) {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where appId=? and spaceId is null and uid_=?",
						new BeanPropertyRowMapper<User>(User.class), appId, uid);
			} else {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where appId=? and spaceId=? and uid_=?",
						new BeanPropertyRowMapper<User>(User.class), appId, spaceId, uid);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public User findDialectOne(String appId, Long spaceId, String dialectUID) {
		try {
			List<User> users = null;
			if (null == spaceId) {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt from ac$users where appId=? and spaceId is null and dialectUID=?",
						new BeanPropertyRowMapper<User>(User.class), appId, dialectUID);
			} else {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt from ac$users where appId=? and spaceId=? and dialectUID=?",
						new BeanPropertyRowMapper<User>(User.class), appId, spaceId, dialectUID);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public UserView findOneView(String appId, Long spaceId, String uid) {
		try {
			List<UserView> users = null;
			if (null == spaceId) {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr from ac$users where  ac$users.appId=? and ac$users.spaceId is null and ac$users.uid_=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, uid);
			} else {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$userspaces.name spaceName,ac$users.hr from ac$users,ac$userspaces where ac$users.spaceId=ac$userspaces.id and ac$users.appId=? and ac$users.spaceId=? and ac$users.uid_=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, spaceId, uid);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public UserView findOneViewBySecondUID(String appId, Long spaceId, String secondUID) {
		try {
			List<UserView> users = null;
			if (null == spaceId) {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$userspaces.name spaceName from ac$users,ac$userspaces where ac$users.spaceId=ac$userspaces.id and ac$users.appId=? and ac$users.spaceId is null and ac$users.secondUID=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, secondUID);
			} else {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$userspaces.name spaceName from ac$users,ac$userspaces where ac$users.spaceId=ac$userspaces.id and ac$users.appId=? and ac$users.spaceId=? and ac$users.secondUID=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, spaceId, secondUID);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public UserView findOneViewByDialectUID(String appId, Long spaceId, String dialectUID) {
		try {
			List<UserView> users = null;
			if (null == spaceId) {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$userspaces.name spaceName,ac$users.hr from ac$users,ac$userspaces where ac$users.spaceId=ac$userspaces.id and ac$users.appId=? and ac$users.spaceId is null and ac$users.dialectUID=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, dialectUID);
			} else {
				users = jdbcTemplate.query(
						"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$userspaces.name spaceName,ac$users.hr from ac$users,ac$userspaces where ac$users.spaceId=ac$userspaces.id and ac$users.appId=? and ac$users.spaceId=? and ac$users.dialectUID=?",
						new BeanPropertyRowMapper<UserView>(UserView.class), appId, spaceId, dialectUID);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public User findOne(String appId, String spaceUID, String uid) {
		try {
			List<User> users = null;
			if (null == spaceUID) {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where appId=? and spaceUID is null and uid_=?",
						new BeanPropertyRowMapper<User>(User.class), appId, uid);
			} else {
				users = jdbcTemplate.query(
						"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where appId=? and spaceUID=? and uid_=?",
						new BeanPropertyRowMapper<User>(User.class), appId, spaceUID, uid);
			}
			return CollectionUtils.isEmpty(users) ? null : users.get(0);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<User> findByUID(String uid) {
		try {
			return jdbcTemplate.query(
					"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where uid_=? order by appId,spaceId",
					new BeanPropertyRowMapper<User>(User.class), uid);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<UserView> findViewByUID(String uid) {
		try {
			return jdbcTemplate.query(
					"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr,ac$userspaces.name spaceName from ac$users left join ac$userspaces on ac$users.spaceId=ac$userspaces.id where ac$users.uid_=? order by ac$users.spaceId,ac$users.appId",
					new BeanPropertyRowMapper<UserView>(UserView.class), uid);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<UserView> findViewBySecondUID(String secondUID) {
		try {
			return jdbcTemplate.query(
					"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr,ac$userspaces.name spaceName from ac$users left join ac$userspaces on ac$users.spaceId=ac$userspaces.id where ac$users.secondUID=? order by ac$users.spaceId,ac$users.appId",
					new BeanPropertyRowMapper<UserView>(UserView.class), secondUID);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public void updateUserSpace(long spaceId, String newAppId, String newSpaceUID) {
		jdbcTemplate.update("update ac$users set appId=?,spaceUID=? where spaceId=?", newAppId, newSpaceUID, spaceId);
	}

	@Override
	public User findOne(long id) {
		try {
			return jdbcTemplate.queryForObject(
					"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where id=?",
					new BeanPropertyRowMapper<User>(User.class), id);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public Page<User> findAll(String appId, String spaceId, int pageNumber, int pageSize) {
		StringBuffer countSql = new StringBuffer("select count(1) from ac$users where 1=1");
		StringBuffer querySql = new StringBuffer(
				"select * from (select t.*,rownum r from (select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where 1=1");
		Object[] args = new Object[] {};
		if (!StringUtils.isEmpty(appId)) {
			countSql.append(" and appId=?");
			querySql.append(" and appId=?");
			args = Arrays.copyOf(args, args.length + 1);
			args[args.length - 1] = appId;
		}
		if (!StringUtils.isEmpty(spaceId)) {
			countSql.append(" and spaceId=?");
			querySql.append(" and spaceId=?");
			args = Arrays.copyOf(args, args.length + 1);
			args[args.length - 1] = spaceId;
		}
		int total = count(countSql.toString(), args);

		querySql.append(" order by appId,spaceId,uid_) t where rownum <= ?) where r >= ?");
		args = Arrays.copyOf(args, args.length + 2);
		args[args.length - 2] = pageNumber * pageSize;
		args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
		List<User> content = null;
		try {
			content = jdbcTemplate.query(querySql.toString(), new BeanPropertyRowMapper<User>(User.class), args);
		} catch (EmptyResultDataAccessException e) {

		}
		return new Page<User>(pageNumber, pageSize, content, total);
	}

	@Override
	public List<UserView> findByAppAndUID(String appId, String uid) {
		try {
			return jdbcTemplate.query(
					"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr,ac$userspaces.name spaceName from ac$users left join ac$userspaces on ac$users.spaceId=ac$userspaces.id where ac$users.appId=? and ac$users.uid_=? order by ac$users.spaceId",
					new BeanPropertyRowMapper<UserView>(UserView.class), appId, uid);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<UserView> findByAppAndSecondUID(String appId, String secondUID) {
		try {
			return jdbcTemplate.query(
					"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr,ac$userspaces.name spaceName from ac$users left join ac$userspaces on ac$users.spaceId=ac$userspaces.id where ac$users.appId=? and ac$users.secondUID=? order by ac$users.spaceId",
					new BeanPropertyRowMapper<UserView>(UserView.class), appId, secondUID);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<UserView> findByAppAndDialectUID(String appId, String dialectUID) {
		try {
			return jdbcTemplate.query(
					"select ac$users.id,ac$users.appId,ac$users.spaceId,ac$users.spaceUID,ac$users.spaceDialectUID,ac$users.uid_ as \"UID\",ac$users.secondUID,ac$users.dialectUID,ac$users.name,ac$users.password,ac$users.salt,ac$users.hr,ac$userspaces.name spaceName from ac$users left join ac$userspaces on ac$users.spaceId=ac$userspaces.id where ac$users.appId=? and ac$users.dialectUID=? order by ac$users.spaceId",
					new BeanPropertyRowMapper<UserView>(UserView.class), appId, dialectUID);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public void saveFailed(UserFailed failed) {
		failed.setId(generateId("ac$user$fail_seq"));
		jdbcTemplate.update(
				"insert into ac$user$fail(id,callTime,errMsg,fromId,fromSpaceId,fromAppId,toSpaceId,toAppId) values (?,?,?,?,?,?,?,?)",
				failed.getId(), failed.getCallTime(), failed.getErrMsg(), failed.getFromId(), failed.getFromSpaceId(),
				failed.getFromAppId(), failed.getToSpaceId(), failed.getToAppId());
	}

	@Override
	public List<User> findByDialectUID(String dialectUID) {
		try {
			return jdbcTemplate.query(
					"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where dialectUID=? order by appId,spaceId",
					new BeanPropertyRowMapper<User>(User.class), dialectUID);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<User> findBySecondUID(String secondUID) {
		try {
			return jdbcTemplate.query(
					"select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where secondUID=? order by appId,spaceId",
					new BeanPropertyRowMapper<User>(User.class), secondUID);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public UserDetail save(UserDetail userDetail) {
		int count = count("from ac$user$detail where mobile=?", userDetail.getMobile());
		if (count == 0) {
			jdbcTemplate
					.update("insert into ac$user$detail(mobile,email,name,sex,idCode,avatar,birthday,valid,department,job,lastLoginTime) values (?,?,?,?,?,?,?,?,?,?,?)",
							userDetail.getMobile(), userDetail.getEmail(), userDetail.getName(), userDetail.getSex(),
							userDetail.getIdCode(), userDetail.getAvatar(),
							(userDetail.getBirthday() == null ? null : new Date(userDetail.getBirthday())), userDetail.getValid(),
							userDetail.getDepartment(), userDetail.getJob(), (userDetail.getLastLoginTime()==null?null:new Date(userDetail.getLastLoginTime())));

		} else {
			jdbcTemplate
					.update("update ac$user$detail set email=?,name=?,sex=?,idCode=?,avatar=?,birthday=?,valid=?,department=?,job=?,lastlogintime=? where mobile=?",
							userDetail.getEmail(), userDetail.getName(), userDetail.getSex(), userDetail.getIdCode(),
							userDetail.getAvatar(), (userDetail.getBirthday() == null ? null : new Date(userDetail.getBirthday())),
							userDetail.getValid(), userDetail.getDepartment(), userDetail.getJob(), (userDetail.getLastLoginTime()==null?null:new Date(userDetail.getLastLoginTime())), userDetail.getMobile());
		}
		return userDetail;
	}

    @Override
    public UserDetail save(UserDetail userDetail, String oldMobile) {
        int count;
        if (oldMobile == null) {
            count = 0;
        } else {
            count = count("from ac$user$detail where mobile=?", oldMobile);
        }
        if (count == 0) {
            jdbcTemplate
                    .update("insert into ac$user$detail(mobile,email,name,sex,idCode,avatar,birthday,valid,department,job,lastLoginTime) values (?,?,?,?,?,?,?,?,?,?,?)",
                            userDetail.getMobile(), userDetail.getEmail(), userDetail.getName(), userDetail.getSex(),
                            userDetail.getIdCode(), userDetail.getAvatar(),
                            (userDetail.getBirthday() == null ? null : new Date(userDetail.getBirthday())), userDetail.getValid(),
                            userDetail.getDepartment(), userDetail.getJob(), (userDetail.getLastLoginTime()==null?null:new Date(userDetail.getLastLoginTime())));

        } else {
            jdbcTemplate
                    .update("update ac$user$detail set mobile=?, email=?,name=?,sex=?,idCode=?,avatar=?,birthday=?,valid=?,department=?,job=?,lastlogintime=? where mobile=?",
                            userDetail.getMobile(), userDetail.getEmail(), userDetail.getName(), userDetail.getSex(), userDetail.getIdCode(),
                            userDetail.getAvatar(), (userDetail.getBirthday() == null ? null : new Date(userDetail.getBirthday())),
                            userDetail.getValid(), userDetail.getDepartment(), userDetail.getJob(), (userDetail.getLastLoginTime()==null?null:new Date(userDetail.getLastLoginTime())), oldMobile);
        }
        return null;
    }

    private RowMapper<UserDetail> getRowMapper() {
		return new RowMapper<UserDetail>() {

			@Override
			public UserDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
				UserDetail detail = new UserDetail();
				detail.setAvatar(rs.getString("avatar"));
				Date birthday = rs.getDate("birthday");
				if (birthday != null)
					detail.setBirthday(birthday.getTime());
				detail.setEmail(rs.getString("email"));
				detail.setIdCode(rs.getString("idCode"));
				detail.setMobile(rs.getString("mobile"));
				detail.setName(rs.getString("name"));
				detail.setSex(rs.getString("sex"));
				detail.setValid(rs.getInt("valid"));
				detail.setDepartment(rs.getString("department"));
				detail.setJob(rs.getString("job"));
				Date lastLoginTime = rs.getTimestamp("lastlogintime");
				if (lastLoginTime != null) {
					detail.setLastLoginTime(lastLoginTime.getTime());
				}
				return detail;
			}

		};
	}

	@Override
	public UserDetail findOne(String mobile) {
		try {
			return jdbcTemplate.queryForObject("select * from ac$user$detail where mobile=?", getRowMapper(), mobile);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public List<UserDetail> findByEmail(String email) {
		try {
			return jdbcTemplate.query("select * from ac$user$detail where email=?", getRowMapper(), email);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	@Override
	public void changePasswordByAppAndUser(String appId, User user, String password) {
		if (!StringUtils.isEmpty(user.getUid()))
			jdbcTemplate.update("update ac$users set password=? where appid=? and uid_=?", password, appId,
					user.getUid());
		else
			jdbcTemplate.update("update ac$users set password=? where appid=? and dialectUID=?", password, appId,
					user.getDialectUID());
	}

	@Override
	public void delete(User user) {
		jdbcTemplate.update("delete from ac$users where id=?", user.getId());
	}

	@Override
	public void changeSecondUIDByUser(User user, String secondUID) {
		if (!StringUtils.isEmpty(user.getUid()))
			jdbcTemplate.update("update ac$users set secondUID=? where uid_=?", secondUID, user.getUid());
		else
			jdbcTemplate.update("update ac$users set secondUID=? where appId=? and dialectUID=?", secondUID,
					user.getAppId(), user.getDialectUID());
	}

	@Override
	public Page<UserDetail> findAllDetail(String name, String mobile, int pageNumber, int pageSize) {
		StringBuffer countSql = new StringBuffer("select count(1) from ac$user$detail where 1=1");
		StringBuffer querySql = new StringBuffer(
				"select * from (select t.*,rownum r from (select * from ac$user$detail where 1=1");
		Object[] args = new Object[] {};
		if (!StringUtils.isEmpty(name)) {
			countSql.append(" and name like '%").append(name).append("%'");
			querySql.append(" and name like '%").append(name).append("%'");
		}
		if (!StringUtils.isEmpty(mobile)) {
			countSql.append(" and mobile=?");
			querySql.append(" and mobile=?");
			args = Arrays.copyOf(args, args.length + 1);
			args[args.length - 1] = mobile;
		}
		int total = count(countSql.toString(), args);

		querySql.append(" order by mobile) t where rownum <= ?) where r >= ?");
		args = Arrays.copyOf(args, args.length + 2);
		args[args.length - 2] = pageNumber * pageSize;
		args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
		List<UserDetail> content = null;
		try {
			content = jdbcTemplate.query(querySql.toString(), getRowMapper(), args);
		} catch (EmptyResultDataAccessException e) {

		}
		return new Page<UserDetail>(pageNumber, pageSize, content, total);
	}

	@Override
	public int getUserDetailCount() {
		return count("from ac$user$detail");
	}

	@Override
	public ModelMap getUserAppCount() {
		return jdbcTemplate.query(
				"select t2.description,count(1) c from (select distinct appId,uid_,secondUID from ac$users) t1,ac$apps t2 where t1.appId=t2.uid_ group by t2.description order by count(1) desc",
				new ResultSetExtractor<ModelMap>() {

					@Override
					public ModelMap extractData(ResultSet rs) throws SQLException, DataAccessException {
						ModelMap map = new ModelMap();
						while (rs.next()) {
							map.put(rs.getString(1), rs.getInt(2));
						}
						return map;
					}

				});
	}

	@Override
	public void deleteByAppAndSpace(String appId, long spaceId) {
		jdbcTemplate.update("delete from ac$users where appId=? and spaceId=?", appId, spaceId);
	}

	@Override
	public List<UserSpaceDetailInfo> findByEnNameAndPageNumber(String name, Integer pageNumber) {
		String sql = "select dialectuid imid,uid_ as \"usertel\",name username from ac$users where 1=1 and appid = 'im' and uid_ in (select a.uid_ from ac$users a left join ac$userspaces u on a.spaceid = u.id where u.appid = 'b2b' and upper(u.name) = upper('"
				+ name + "'))";
		List<UserSpaceDetailInfo> content = null;
		try {
			content = jdbcTemplate.query(sql,
					new BeanPropertyRowMapper<UserSpaceDetailInfo>(UserSpaceDetailInfo.class));
		} catch (EmptyResultDataAccessException e) {

		}
		return content;
	}

	@Override
	public List<User> findByBusinessCode(String businessCode) {
		String sql = "select seconduid,uid_ as \"uid\",name,dialectuid from ac$users  where upper(spaceuid) = upper('"
				+ businessCode + "') and appid = 'b2b'";
		List<User> content = null;
		try {
			content = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
		} catch (EmptyResultDataAccessException e) {

		}
		return content;
	}

	@Override
	public Integer getEnterpriseCount() {
		try {
			return jdbcTemplate.queryForObject("select count(*) SUM from ac$us$detail where 1=1", Integer.class);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Integer getPersonalUserCount() {
		try {
			return jdbcTemplate.queryForObject("select count(*) SUM from ac$user$detail where 1=1", Integer.class);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Integer getUuUserCount() {
		try {
			return jdbcTemplate.queryForObject("select count(*) SUM FROM ac$users where appid='im'", Integer.class);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void lockEmail(String email) {
		int count = count("from ac$lock where username=? and type='email'", email);
		if (count == 0) {
			jdbcTemplate.update("insert into ac$lock(username, type) values (?, 'email')", email);
		}
	}

	@Override
	public void lockTel(String tel) {
		int count = count("from ac$lock where username=? and type='tel'", tel);
		if (count == 0) {
			jdbcTemplate.update("insert into ac$lock(username, type) values (?, 'tel')", tel);
		}
	}

	@Override
	public void lockUU(String uu) {
		int count = count("from ac$lock where username=? and type='uu'", uu);
		if (count == 0) {
			jdbcTemplate.update("insert into ac$lock(username, type) values (?, 'uu')", uu);
		}
	}

	@Override
	public boolean isLockEmail(String email) {
		int count = count("from ac$lock where username=? and type='email'", email);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isLockTel(String tel) {
		int count = count("from ac$lock where username=? and type='tel'", tel);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isLockUU(String uu) {
		int count = count("from ac$lock where username=? and type='uu'", uu);
		if (count > 0) {
			return true;
		}
		return false;
	}


    @Override
    public User findHrInfo(String businessCode) {
	    List<User> content = null;
        if(null != businessCode) {
            content = jdbcTemplate.query("select id,appId,spaceId,spaceUID,spaceDialectUID,uid_ as \"UID\",secondUID,dialectUID,name,password,salt,hr from ac$users where appId = 'b2b' and spaceuid = '" + businessCode + "' and nvl(hr, 0) = 1",
                    new BeanPropertyRowMapper<User>(User.class));
            return content.size() > 0 ? content.get(0) : null;
        }
        return null;
    }

	/**
	 * 根据imid返回userUU
	 */
	@Override
	public String getUserUUByImId(Long imId) {
		try {
			List<User> users = jdbcTemplate.query("select b2b.dialectuid  from ac$users b2b where b2b.uid_ = (select im.uid_ from ac$users im where im.dialectuid =" + imId + " and im.appid = 'im' and rownum = 1) and b2b.appid = 'b2b' and rownum = 1", new BeanPropertyRowMapper<User>(User.class));
			if (!CollectionUtils.isEmpty(users)) {
				return users.get(0).getDialectUID();
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

}
