package com.palmnest.service.impl;


import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.bean.RoleFloorTypeInfo;
import com.palmnest.application.core.util.GenPass;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.output.UserDataByTokenDto;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.estateserve.FloorInfoDao;
import com.palmnest.model.*;
import com.palmnest.model.estateserve.VirtualAccount;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.repair.UserRepairType;
import com.palmnest.service.RoleManager;
import com.palmnest.service.UserExistsException;
import com.palmnest.service.UserManager;
import com.palmnest.service.UserService;
import com.palmnest.service.repair.UserRepairTypeManager;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.jws.WebService;
import java.nio.charset.Charset;
import java.util.*;

/**
 * Implementation of UserManager interface.
 *
 * @author <a href="mailto:chasel.java@gmail.com">Chasel Li</a>
 * @modify yubing
 * @since 2014-09-25
 */
@Slf4j
@Service("userManager")
@WebService(serviceName = "UserService", endpointInterface = "com.palmnest.service.UserService")
public class UserManagerImpl extends GenericManagerImpl<User, Long> implements
		UserManager, UserService {

	private PasswordEncoder passwordEncoder;
	private UserDao         userDao;

	@Autowired(required = false)
	private SaltSource            saltSource;
	@Autowired
	private RoleManager           roleManager;
	@Autowired
	private UserRepairTypeManager userRepairTypeManager;
	@Autowired
	private FloorInfoDao          floorInfoDao;
	@Autowired
	private OrganizationDao       organizationDao;

	@Autowired
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.dao = userDao;
		this.userDao = userDao;
	}

	/**
	 * {@inheritDoc}
	 */
	public User getUser(String userId) {
		return userDao.get(new Long(userId));
	}

	/**
	 * {@inheritDoc}
	 */
	public List<User> getUsers() {
		return userDao.getAllDistinct();
	}


	public static String meeting_url = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");

	/**
	 * {@inheritDoc}
	 */
	public User saveUser(User user) throws UserExistsException {
		if (user.getId() != null) {
			// 修改状态情况下，如果前端密码为空，则保持原先密码
			if (StringUtils.isEmpty(user.getPassword())) {
				User loadUser = get(user.getId());
				user.setPassword(loadUser.getPassword());
				user.setShopPassword(loadUser.getShopPassword());
				return userDao.saveUser(user);
			}
		}

		if (user.getVersion() == null) {
			// if new user, lowercase userId
			user.setUsername(user.getUsername().toLowerCase());
		}

		// Get and prepare password management-related artifacts
		boolean passwordChanged = false;
		if (passwordEncoder != null) {
			// Check whether we have to encrypt (or re-encrypt) the password
			if (user.getVersion() == null) {
				// New user, always encrypt
				passwordChanged = true;
			} else {
				// Existing user, check password in DB
				String currentPassword = userDao.getUserPassword(user.getId());
				if (currentPassword == null) {
					passwordChanged = true;
				} else {
					if (!currentPassword.equals(user.getPassword())) {
						passwordChanged = true;
					}
				}
			}

			// If password was changed (or new user), encrypt it
			if (passwordChanged) {
				if (saltSource == null) {
					// backwards compatibility
					user.setShopPassword(GenPass.Encrypt(user.getPassword()));
					user.setPassword(passwordEncoder.encodePassword(
							user.getPassword(), null));
					log.warn("SaltSource not set, encrypting password w/o salt");
				} else {
					user.setShopPassword(GenPass.Encrypt(user.getPassword()));
					user.setPassword(passwordEncoder.encodePassword(
							user.getPassword(), saltSource.getSalt(user)));
				}
			}
		} else {
			log.warn("PasswordEncoder not set, skipping password encryption...");
		}

		try {
			return userDao.saveUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			log.warn(e.getMessage());
			throw new UserExistsException("User '" + user.getUsername()
					+ "' already exists!");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeUser(User user) {
		log.debug("removing user: " + user);
		userDao.remove(user);
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeUser(String userId) {
		log.debug("removing user: " + userId);
		userDao.remove(new Long(userId));
	}

	/**
	 * {@inheritDoc}
	 *
	 * @param username the login name of the human
	 * @return User the populated user object
	 * @throws UsernameNotFoundException thrown when username not found
	 */
	public User getUserByUsername(String username)
			throws UsernameNotFoundException {
		return (User) userDao.loadUserByUsername(username);
	}

	/**
	 * {@inheritDoc}
	 */
	public List<User> search(String searchTerm) {
		return super.search(searchTerm, User.class);
	}

	@Override
	public Pagenation<User> queryUser(int pageNo,
									  List<Criterion> filterList) {
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();
		orderList.add(Order.desc("createdTime"));
		return userDao.queryPage(pageNo, Constants.LIMIT_PAGESIZE, aliasMap, filterList, orderList, User.class);
	}

	public Page queryUser(int pageNo, int pageSize, String username, User user, String orgIds, String roleId) {
		StringBuffer strSbf = new StringBuffer("SELECT t1.ID,t1.USERNAME,t1.FULL_NAME,t1.TELEPHONE,t1.CREATED_TIME,GROUP_CONCAT(DISTINCT t3.`NAME`) AS roleName,t4.itemname as position").append("\n");
		strSbf.append(" FROM tb_app_user t1").append("\n");
		strSbf.append(" LEFT JOIN tr_app_user_role t2 ON t1.id = t2.USER_ID").append("\n");
		strSbf.append(" LEFT JOIN tb_app_role t3 ON t2.ROLE_ID = t3.ID").append("\n");
		strSbf.append(" LEFT JOIN tb_dictionary_item t4 ON t1.position = t4.ID ").append("\n");

		if (StringUtils.isNotBlank(orgIds)) {
			strSbf.append(" left join tr_app_user_orgnization aur on t1.id = aur.user_id \n");
		}
		strSbf.append(" where 1=1 ").append("\n");

		if (StringUtils.isNotBlank(orgIds)) {
			strSbf.append(" AND (aur.org_id in(" + orgIds + ") OR t1.USER_TYPE <= 2 ) \n");
		}

		if (StringUtils.isNotBlank(roleId)) {
			strSbf.append(" AND t3.id=" + roleId + " \n");
		}
		if (StringUtils.isNotBlank(username)) {
			strSbf.append(" AND (t1.USERNAME LIKE '%" + username + "%' OR t1.TELEPHONE LIKE '%" + username + "%' OR t1.FULL_NAME LIKE '%" + username + "%')").append("\n");
		}

		strSbf.append(" and t1.USER_TYPE >= " + user.getUserType() + "").append("\n");

		strSbf.append(" AND t1.ISENABLED='1' GROUP BY t1.ID").append("\n");
		return userDao.queryUserPage(pageNo, pageSize, strSbf.toString());
	}


	@Override
	public User getUserByUsername2(String username) {
		return userDao.getUserByUsername2(username);
	}

	@Override
	public void saveUser2(User user) {
		user.setShopPassword(GenPass.Encrypt(user.getPassword()));
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(), user.getUsername().toLowerCase()));
		userDao.save(user);
	}

	@Override
	public void updateUser(User user) {
		userDao.updateUser(user);
	}

	@Override
	public boolean updateUserPwd(String username, String oldPwd, String newPwd) {
		boolean retFlag = true;
		User    user    = getUser(username, oldPwd);
		if (user == null) {
			retFlag = false;
		} else {
			user.setPassword(newPwd);
			saveUser2(user);
		}
		return retFlag;
	}

	@Override
	public User getUser(String username, String password) {
		password = passwordEncoder.encodePassword(password, username.toLowerCase());
		return userDao.getUser(username, password);
	}

//	@Override
//	public List<AppUserOrgRelation> getAppUserOrgByUserId(int userid) {
//		return userDao.getAppUserOrgByUserId(userid);
//	}

	@Override
	public List<AppUserCompanyRelation> getAppUserCompanyByUserId(int userid) {
		return userDao.getAppUserCompanyByUserId(userid);
	}

	@Override
	public List<AppUserOrgnizationRelation> getUserOrgByUserId(Long userid) {
		return userDao.getUserOrgByUserId(userid);
	}

	@Override
	public List<AppUserFloorRelation> getAppUserFloorByUserId(int userid) {
		return userDao.getAppUserFloorByUserId(userid);
	}

	@Override
	public List<AppUserFloorRelation> getAppUserFloorByUserId(int userid,
															  int roleId) {
		return userDao.getAppUserFloorByUserId(userid, roleId);
	}

//	@Override
//	public void deleteAppUserOrgByUserId(int userid, String orgType) {
//		userDao.deleteAppUserOrgByUserId(userid, orgType);
//	}

	@Override
	public void deleteAppUserOrgByUserId(Long userid) {
		userDao.deleteAppUserOrgByUserId(userid);
	}

	@Override
	public List<AppUserOrgnizationRelation> getAppUserOrgByUserId(int userid) {
		return userDao.getAppUserOrgByUserId(userid);
	}

	@Override
	public void deleteAppUserFloorByUserId(int userid, String orgType) {
		userDao.deleteAppUserFloorByUserId(userid, orgType);
	}

	/*@Override
	public AppUserOrgRelation saveAppUserOrgRelation(User user,
			int organizationId) {
		AppUserOrgRelation re=new AppUserOrgRelation();
		if(Constants.ADMIN_NAME.equals(user.getUsername())){
			re.setOrgId(organizationId);
			re.setOrgType(ElementConstant.USER_ORG_COMPANY);
			re.setUserId(user.getId().intValue());
			re.setCreateTime(new Date());
			re.setCreator(user.getUsername());
			userDao.saveAppUserOrgRelation(re);
		}
		else{
			re.setOrgId(organizationId);
			re.setOrgType(ElementConstant.USER_ORG_COMPANY);
			re.setUserId(user.getId().intValue());
			re.setCreateTime(new Date());
			re.setCreator(user.getUsername());
			userDao.saveAppUserOrgRelation(re);
			
			//保存与超级管理员关联
			User adminUser=getUserByUsername2(Constants.ADMIN_NAME);
			AppUserOrgRelation re2=new AppUserOrgRelation();
			re2.setOrgId(organizationId);
			re2.setOrgType(ElementConstant.USER_ORG_COMPANY);
			re2.setUserId(adminUser.getId().intValue());
			re2.setCreateTime(new Date());
			re2.setCreator(adminUser.getUsername());
			userDao.saveAppUserOrgRelation(re2);
		}
		return re;
	}*/

	/**
	 * 后台保存更新系统更新通知时更新后台用户通知状态
	 */
	@Override
	public void updateAllState() {
		userDao.updateAllState();
	}

	/*@Override
	public String saveOrUpdateUser(User user, List<String> company,
			List<String> dept) {
		String retCode="0";
		try {
			//更新
			if(user.getId()!=null){
//				visitMeetingUrl(user.getUsername());
				retCode="2";
			}
			//新增
			else{
				retCode="1";
			}
			user=saveUser(user);
			//处理用户管辖组织信息
			if(user.getId()!=null){
				int currentUserid=user.getId().intValue();
				//删除当前用户的组织关系
	    		deleteAppUserOrgByUserId(currentUserid, ElementConstant.USER_ORG_COMPANY);
	    		deleteAppUserOrgByUserId(currentUserid, ElementConstant.USER_ORG_DEPT);

	    		if(!CollectionUtils.isEmpty(company)){
	    			for (String companyId : company) {
	    				AppUserOrgRelation re=new AppUserOrgRelation();
	    				re.setOrgId(Integer.parseInt(companyId.substring(2))); //c_28
	    				re.setOrgType(ElementConstant.USER_ORG_COMPANY);
	    				re.setUserId(currentUserid);
	    				re.setCreateTime(new Date());
	    				re.setCreator(user.getLastUpdatedBy());
	    				userDao.saveAppUserOrgRelation(re);
					}
	    		}
	    		if(!CollectionUtils.isEmpty(dept)){
	    			for (String deptId : dept) {
	    				AppUserOrgRelation re=new AppUserOrgRelation();
	    				re.setOrgId(Integer.parseInt(deptId));
	    				re.setOrgType(ElementConstant.USER_ORG_DEPT);
	    				re.setUserId(currentUserid);
	    				re.setCreateTime(new Date());
	    				re.setCreator(user.getLastUpdatedBy());
	    				userDao.saveAppUserOrgRelation(re);
					}
	    		}
			}
		} catch (UserExistsException e) {
			retCode="3";
		}
		return retCode;
	}*/

	/**
	 * 用户管辖项目关系 修改/保存
	 *
	 * @param user
	 * @param orgnization
	 * @return
	 */
	@Override
	public String saveOrUpdateUser(User user, List<String> orgnization) {
		String retCode = "0";
		try {
			//更新
			if (user.getId() != null) {
				retCode = "2";
			}
			//新增
			else {
				retCode = "1";
			}

			//--保存/修改用户操作
			user = saveUser(user);

			//处理用户管辖组织信息
			if (user.getId() != null) {
				Long currentUserid = user.getId();
				//删除当前用户管辖项目关系
				deleteAppUserOrgByUserId(currentUserid);
				deleteAppUserFloorByUserId(Integer.parseInt(String.valueOf(currentUserid)), ElementConstant.USER_ORG_FLOOR);
				if (!CollectionUtils.isEmpty(orgnization)) {
					for (String orgnizationId : orgnization) {
						AppUserOrgnizationRelation re = new AppUserOrgnizationRelation();
						re.setOrgId(Integer.parseInt(orgnizationId));
						re.setUserId(currentUserid);
						re.setCreateTime(new Date());
						re.setCreator(user.getLastUpdatedBy());
						userDao.saveAppUserOrgRelation(re);
					}
				}
			}
		} catch (UserExistsException e) {
			retCode = "3";
		}
		return retCode;
	}
	
	/*@Override
	public String saveOrUpdateUser(User user,List<String> company,List<String> dept,
			List<String> organization,List<String> floor) {
		String retCode="0";
		try {
			//更新
			if(user.getId()!=null){
				retCode="2";
			}
			//新增
			else{
				retCode="1";
			}
			user=saveUser(user);
			//处理用户管辖组织信息
			if(user.getId()!=null){
				int currentUserid=user.getId().intValue();
				deleteAppUserOrgByUserId(currentUserid, ElementConstant.USER_ORG_COMPANY);
				deleteAppUserOrgByUserId(currentUserid, ElementConstant.USER_ORG_DEPT);
				
				/*//*******************楼宇操作******
	 deleteAppUserFloorByUserId(currentUserid,ElementConstant.USER_ORG_BUILD);
	 deleteAppUserFloorByUserId(currentUserid,ElementConstant.USER_ORG_FLOOR);
	 /*/
	/*************************

	 if(!CollectionUtils.isEmpty(company)){
	 for (String companyId : company) {
	 AppUserOrgRelation re=new AppUserOrgRelation();
	 re.setOrgId(Integer.parseInt(companyId.substring(2))); //c_28
	 re.setOrgType(ElementConstant.USER_ORG_COMPANY);
	 re.setUserId(currentUserid);
	 re.setCreateTime(new Date());
	 re.setCreator(user.getLastUpdatedBy());
	 userDao.saveAppUserOrgRelation(re);
	 }
	 }
	 if(!CollectionUtils.isEmpty(dept)){
	 for (String deptId : dept) {
	 AppUserOrgRelation re=new AppUserOrgRelation();
	 re.setOrgId(Integer.parseInt(deptId));
	 re.setOrgType(ElementConstant.USER_ORG_DEPT);
	 re.setUserId(currentUserid);
	 re.setCreateTime(new Date());
	 re.setCreator(user.getLastUpdatedBy());
	 userDao.saveAppUserOrgRelation(re);
	 }
	 }
	 if(!CollectionUtils.isEmpty(organization)){
	 for(String orgId :organization){
	 if(!CollectionUtils.isEmpty(floor)){
	 for(String floorId :floor){
	 AppUserFloorRelation appFloor=new AppUserFloorRelation();
	 appFloor.setCreateTime(new Date());
	 appFloor.setCreator(user.getLastUpdatedBy());
	 appFloor.setFloor_id(Integer.parseInt(floorId));
	 appFloor.setOrg_id(Integer.parseInt(orgId));
	 appFloor.setUser_id(currentUserid);
	 userDao.saveAppUserOrgRelation(appFloor);
	 }
	 }
	 }
	 }




	 }
	 } catch (UserExistsException e) {
	 retCode="3";
	 }
	 return retCode;
	 }*/

	@Override
	public ArrayList<User> getUserByType(int type) {
		return userDao.getUserByType(type);
	}

	;


	@Override
	public List<User> findByFunction(Integer orgId, String systemCode) {
		return userDao.findByFunction(orgId, systemCode);
	}

	@Override
	public User findByTelephone(String telephone) {
		User user = userDao.findByTelephone(telephone);
		return user;
	}

	@Override
	public boolean resetUserPwd(String username, String newPwd) {
		User user = userDao.getUserByUsername2(username);
		if (user == null) {
			return false;
		}
		user.setPassword(newPwd);
		saveUser2(user);
		return true;
	}


	@Override
	public List<User> queryUserBySql(String querySql) {

		return userDao.queryUserBySql(querySql);
	}

	@Override
	public List<User> findByFunction(String systemCode) {
		return userDao.findByFunction(systemCode);
	}


	/**
	 * 保存楼层和维修类型
	 */
	@Transactional
	public String setUserRoleInfo(User userInfo, Map<String, RoleFloorTypeInfo> roleMap, String roles, String user) {
		int      userId = userInfo.getId().intValue();
		String[] str    = roles.split(";");
		//List中存储以角色为key/，角色所对应的值为所选楼栋或者类型等
		for (int j = 0; j < str.length; j++) {
			RoleFloorTypeInfo obj = (RoleFloorTypeInfo) JSONObject.toBean(JSONObject.fromObject(roleMap.get(str[j])), RoleFloorTypeInfo.class);
			if (obj != null) {
				int          type    = obj.getType();
				List<Object> objList = obj.getFloorOrRepairType();
				if (objList != null && objList.size() > 0) {
					if (type == 4) {
						userRepairTypeManager.removeByUser(userInfo.getId(), Long.parseLong(str[j]));
					}
					for (int k = 0; k < objList.size(); k++) {
						if (objList.get(k) != null && StringUtils.isNotEmpty(objList.get(k).toString())) {

							int objId = Integer.parseInt(objList.get(k).toString());
							if (type == 1) {
								if (floorInfoDao.exists(objId)) {
									FloorInfo            floorInfo = floorInfoDao.get(objId);
									AppUserFloorRelation appFloor  = new AppUserFloorRelation();
									appFloor.setCreateTime(new Date());
									appFloor.setCreator(user);
									appFloor.setFloor_id(objId);
									appFloor.setRole_id(Integer.parseInt(str[j]));
									appFloor.setOrg_id(Integer.parseInt(floorInfo.getOrganizationId().toString()));
									appFloor.setUser_id(userId);
									userDao.saveAppUserOrgRelation(appFloor);
								}
							} else if (type == 4) {
								UserRepairType repairType = new UserRepairType(userInfo.getId(), Long.parseLong(String.valueOf(objId)), Long.parseLong(str[j]));
								userRepairTypeManager.saveModel(repairType);
							}

						}

					}
				}
			}

		}
		return null;
	}

//	@Override
//	public List<AppUserOrgRelation> getAppUserOrgByUserId(int userid,
//			String type) {
//		return userDao.getAppUserOrgByUserId(userid, type);
//	}

	@Override
	public User findByFunctionAndUser(String systemCode, Long userId) {
		return userDao.findByFunctionAndUser(systemCode, userId);
	}

	@Override
	public List<User> findByFunctionAndUserList(String systemCode, Long userId) {
		return userDao.findByFunctionAndUserList(systemCode, userId);
	}

	@Override
	public UserDataByTokenDto setUserData(String userName) {
		UserDataByTokenDto dto = new UserDataByTokenDto();
		dto.setTokenType("APP");
		User appUser = userDao.getUserByUsername2(userName);//tb_app_user
		if (appUser != null) {


			//organizationId
			//mettingClient
			List<AppUserOrgnizationRelation> orgList = getUserOrgByUserId(appUser.getId());
			if (orgList != null && orgList.size() > 0) {
				AppUserOrgnizationRelation orgRe = orgList.get(0);
				if (orgRe != null) {
					TbOrganization org = organizationDao.getOrganizationById(orgRe.getOrgId());
					if (org != null) {
						//dto.setOrgId(org.getId().toString());
						//dto.setOrgName(org.getName());
						//dto.setMeetClient(org.getMettingClient());

						//同步改
						if (StringUtils.isNotEmpty(org.getMettingClient())) {
							dto.setOrganizationId(org.getId().toString());
							dto.setOrganizationName(org.getName());
							dto.setMettingclient(org.getMettingClient());//天津党校
						} else {
							dto.setErrorcode("1");
							dto.setErrorMsg("会议室尚未初始化完成");
							return dto;
						}

					}
				}
			}


			//后面动态配置
			/*if("10".equals("10")){
				dto.setMettingclient("C00027");//尚美集团
			}else{
				dto.setMettingclient("C00017");//天津党校
			}*/

			dto.setOpenId("");
			dto.setUserId(appUser.getId().toString());
			userName = appUser.getUsername();
			dto.setUserName(userName);
			dto.setMobile(appUser.getTelephone());//账号唯一值
			//dto.setRole("1");//1-管理员，2-普通用户 会议室后台拿这个是管理员去拿对应楼层
			dto.setRole("SERVER");//1-管理员，2-普通用户 会议室后台拿这个是管理员去拿对应楼层
			//dto.setRole("SYSMANG");//1-管理员，2-普通用户 会议室后台拿这个是管理员去拿对应楼层
			dto.setHeadimgUrl("");
			dto.setVirLoginUrl("");
			Integer isCompanyHead = 0;//否企业负责人 0否 1是
			dto.setCompanyId("");
			dto.setIsCompanyHead(isCompanyHead);
			dto.setIsBingCompany(0);
		}
		return dto;
	}

	@Async
	public void visitMeetingUrl(String userName) {
		HttpClient         httpClient = new DefaultHttpClient();
		String             url        = meeting_url + "/api/BookAppAPI/UpdataOrgID";
		HttpPost           httpPost   = new HttpPost(url);
		UserDataByTokenDto dto        = setUserData(userName);
		String             str        = JSONObject.fromObject(dto).toString();
		httpPost.setEntity(new StringEntity(str, Charset.forName("utf-8")));
		try {
			HttpResponse response   = httpClient.execute(httpPost);
			int          statusCode = response.getStatusLine().getStatusCode();
			System.out.println(statusCode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

	@Override
	public Role findRoleByFunctionAndUser(String systemCode, Long userId) {

		return userDao.findRoleByFunctionAndUser(systemCode, userId);
	}


	@Override
	public List<Map<String, Object>> getPower(String orgId, int sysCode) {
		return userDao.getPower(orgId, sysCode);
	}

	@Override
	public List<Map<String, Object>> getPowerByOrgIds(String orgIds, int sysCode) {
		return userDao.getPowerByOrgIds(orgIds, sysCode);
	}

	@Override
	public List<User> findByFunAndRoleAndFloor(String systemCode, String floorId) {
		return userDao.findByFunAndRoleAndFloor(systemCode, floorId);
	}

	@Override
	public List<User> findByFunctionGeneral(Integer orgId, String systemCode) {
		return userDao.findByFunctionGeneral(orgId, systemCode);
	}

	@Override
	public List<User> findByRoleId(Integer roleId,Integer orgId) {
		return userDao.findByRoleId(roleId,orgId);
	}

	@Override
	public List<Map<String, Object>> findMeetingAuditRoleByOrdId(String OrdId) {

		return userDao.findMeetingAuditRoleByOrdId(OrdId);
	}

	@Override
	public List<Role> findRoleBySystemCodeAndRoleIds(String systemCode,
													 String roleIds) {
		return userDao.findRoleBySystemCodeAndRoleIds(systemCode, roleIds);
	}

	@Override
	public User createVirAccountUser(VirtualAccount virAccount) {

		// 首先查询该企业账号类型用户是否已经存在
		User virUser = getUserByUsername2(virAccount.getVirAccount());
		if (!Objects.isNull(virUser)) {
			return virUser;
		}

		// 不存在创建

		// 创建企业账号用户账号
		virUser = new User();
		virUser.setAccountEnabled(1);
		virUser.setAccountExpired(0);
		virUser.setAccountLocked(0);
		virUser.setCredentialsExpired(1);
		virUser.setCreatedTime(new Date());
		virUser.setIsenabled(ElementConstant.YESORNO_1);// 设置可用
		virUser.setVersion(1);// 不设置,用户名就小写了

		String username = virAccount.getVirAccount();
		String password = virAccount.getPassword();

		virUser.setPassword(passwordEncoder.encodePassword(password, username.toLowerCase()));
		virUser.setUsername(username);
		virUser.setUserType(5);// 企业账号类型用户
		// 保存用户角色
		Set<TbCompany> company = new HashSet<>();
		company.add(organizationDao.getCompanyList("1").get(0));
		virUser.setCompanys(company);//所属运营中心,默认关联第一个

		Set<Role> roleSet = new HashSet<Role>();
		roleSet.add(roleManager.getVirAccountRole());// 查询企业账号角色
		virUser.setRoles(roleSet);//设置用户角色

		// 保存用户并且保存用户项目关系
		virUser = userDao.saveUser(virUser);

		List<String> list = new ArrayList<>();
		list.add(virAccount.getOrgId());

		//处理用户管辖组织信息
		if (virUser.getId() != null) {
			Long currentUserid = virUser.getId();
			//删除当前用户管辖项目关系
			deleteAppUserOrgByUserId(currentUserid);
			deleteAppUserFloorByUserId(Integer.parseInt(String.valueOf(currentUserid)), ElementConstant.USER_ORG_FLOOR);
			if (!CollectionUtils.isEmpty(list)) {
				for (String orgnizationId : list) {
					AppUserOrgnizationRelation re = new AppUserOrgnizationRelation();
					re.setOrgId(Integer.parseInt(orgnizationId));
					re.setUserId(currentUserid);
					re.setCreateTime(new Date());
					re.setCreator(virUser.getLastUpdatedBy());
					userDao.saveAppUserOrgRelation(re);
				}
			}
		}

		return virUser;
	}

	public static void main(String[] args) {
		ShaPasswordEncoder passwordEncoder = new ShaPasswordEncoder();
		String             s               = passwordEncoder.encodePassword("admin123", "admin");
		System.out.println(s);


		MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
		String                       s1      = encoder.encodePassword("admin123", "admin");
		System.out.println(s1);
	}
}
