package com.hnshituo.core.auth.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.pb.SpeOptBaseService;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.basic.util.DataEncoder;
import com.hnshituo.core.auth.mapper.RoleMapper;
import com.hnshituo.core.auth.mapper.UserInfoMapper;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.mapper.UserRoleMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.service.UserService;
import com.hnshituo.core.auth.vo.Role;
import com.hnshituo.core.auth.vo.User;
import com.hnshituo.core.auth.vo.UserInfo;
import com.hnshituo.core.auth.vo.UserRole;

@RemoteService(path="core/auth/user")
public class UserServiceImpl extends BaseServiceImpl<User, String> implements UserService {

	private static Logger logger = Logger.getLogger(UserServiceImpl.class);

	/**
	 * 密码加密
	 * */
	public String encrypted(String inStr) throws Exception {
		return DataEncoder.shaEncode(inStr);
	}

	/**
	 * 获取当前登录人信息
	 * */
	@Override
	@RemoteService(path="loginUser")
	public User getLoginUser() throws Exception {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		User user = super.findById(userId);
		return user;
	}

	/**
	 * 更新当前登陆用户的信息
	 * */
	@Override
	@RemoteService(path="updateCurrent")
	public User updateLoginUser(User user) throws Exception {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		user.setId(userId);
		this.update(user);
		return this.findById(userId);
	}

	/**
	 * 分页获取人员信息
	 * */
	public PageModel<User> findUserInfo(User user, int pageNumber, int pageSize) {
		PageModel<User> pm = new PageModel<User>(pageNumber, pageSize);
		user = (user == null) ? new User() : user;
		StringBuilder sb = new StringBuilder(" 1=1 ");
		if (StringUtils.isNotEmpty(user.getDept_id())) {
			sb.append("AND DEPT_ID ='" + user.getDept_id() + "' ");
		}

		pm.setRows(this.getMapper(UserMapper.class).findWithCondition(null, sb.toString(), " CREATE_TIME DESC , UPDATE_TIME DESC ", (pageNumber - 1) * pageSize, pageSize));
		pm.setTotal(this.getMapper(UserMapper.class).countWithCondition(null, sb.toString()));
		return pm;
	}

	/**
	 * 验证id是否重复
	 * */
	@Override
	public boolean validateId(String id) {
		return !this.getMapper(UserMapper.class).isIdExist(id);
	}

	/**
	 * 验证登录名是否重复
	 * */
	@Override
	public boolean validateLoginName(String loginName) {
		return !this.getMapper(UserMapper.class).isLoginNameExist(loginName);
	}

	//	/**
	//	 * 用户注册
	//	 * */
	//	@Override
	//	@Transactional(value="tm", rollbackFor=Exception.class)
	//	public void insert(User t) throws Exception {
	//		try{
	//			if (t==null) return;
	//			t.setCreate_time(new Date());
	//			t.setCreate_man((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
	//			t.setLogo(this.getBean(SpeOptBaseService.class).doAdd(t.getLogo()));
	//			//-----------------------
	//			super.insert(t);
	//			this.getMapper(UserMapper.class).resetPassword(t.getId(), encrypted("123456"));
	//			this.getMapper(RoleMapper.class).delRelationByUserId(t.getId());
	//		}catch(Exception e){
	//			return;
	//		}
	//		
	//
	//		if (t.getRoles() != null && t.getRoles().size() > 0)
	//			this.getMapper(RoleMapper.class).insertUserRole2(t.getId(), t.getRoles());
	//
	//		//为用户设置token（RongCloud）
	//		/*if(t.getId()!=null&&t.getUsername()!=null)
	//			setToken(t.getId(),t.getUsername(),"");*/
	//	}


	/**
	 * web用户注册
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel registerWeb(User t) throws Exception {
		ResultModel rm = new ResultModel();
		try{
			if (t==null) {
				rm.setState("500");
				return rm;
			}

			t.setCreate_time(new Date());
			t.setCreate_man((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
			if(t.getLogo()!=null&&!"".equals(t.getLogo()))
				t.setLogo(this.getBean(SpeOptBaseService.class).doAdd(t.getLogo()));
			//-----------------------
			t.setPassword("123456");
			t.setValid_flag("1");
			super.insert(t);
			this.getMapper(UserMapper.class).resetPassword(t.getId(), encrypted("123456"));
			this.getMapper(RoleMapper.class).delRelationByUserId(t.getId());

			rm.setData(t);
			rm.setState("200");
			if (t.getRoles() != null ){
				for(Role roles:t.getRoles()){
					UserRole ur=new UserRole();
					ur.setRoleId(roles.getId());
					ur.setUserId(t.getId());
					int count=this.getMapper(UserRoleMapper.class).findMaxId();
					ur.setId(count+1);
					this.getMapper(UserRoleMapper.class).insert(ur);
				}
			}
//				this.getMapper(RoleMapper.class).insertUserRole2(t.getId(), t.getRoles());
		}catch(Exception e){
			rm.setState("500");
						if(e.getMessage().contains("LOGIN_NAME")||e.getMessage().contains("ID")){
							rm.setMsgInfo("该用户名已存在");
							return rm;
						}
			throw e;
		}
		//为用户设置token（RongCloud）
		/*ResultModel result =  new ResultModel();
		if(t.getId()!=null&&t.getUsername()!=null)
			result = setToken(t.getId(),t.getUsername(),"");
		if(result.getMsgInfo() != null){
			rm.setMsgInfo(result.getMsgInfo());
		}*/
		return rm;
	}

	/**
	 * 修改用户信息
	 */
	@Override
	@Transactional(value="tm", rollbackFor=Exception.class)
	public void update(User t) throws Exception {
		try{
			if (t==null || t.getId() == null) return;
			t.setUpdate_time(new Date());
			t.setUpdate_man((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
			super.update(t);
			this.getMapper(RoleMapper.class).delRelationByUserId(t.getId());
		}catch(Exception e){
			return;
		}

		if (t.getRoles() != null && t.getRoles().size() > 0){
			for(Role role:t.getRoles()){
				int count=this.getMapper(UserRoleMapper.class).findMaxId()+1;
				UserRole ur=new UserRole();
				ur.setId(count);
				ur.setUserId(t.getId());
				ur.setRoleId(role.getId());
				this.getMapper(UserRoleMapper.class).insert(ur);
			}
		}
	}

	/**
	 * 前端界面查看用户个人信息操作
	 * */
	public List<User> userPersonInforApp(User t){
		//if (t==null || t.getId() == null) return null;
		List<User> userList = this.getMapper(UserMapper.class).findWithCondition(t,null, null, 0, 0);
		return userList;
	}

	/**
	 * 前端界面查看用户DEPT_ID
	 * */
	public List<User> findByUserDeptIdApp(User t) throws Exception{
		return this.getMapper(UserMapper.class).findByUserIdApp(t.getId());
	}

	/**
	 * 前端界面修改用户信息操作，仅修改用户的基本信息不含密码，权限，部门等数据
	 * */
	//	public void updateApp(User t) throws Exception {
	//		if (t==null || t.getId() == null) return;
	//		t.setUpdateTime(new Date());
	//		t.setUpdateMan((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
	//		if(t.getAge()==null)
	//			t.setAge(0);
	//		List<String> ls=new ArrayList<String>();
	//		ls.add(t.getLogo());
	//		List<String> arr=speOptService.confirmUpload(ls);
	//		if(arr.size()>0){
	//			t.setLogo(arr.get(0));
	//		}
	//		super.update(t);
	//	}
	//	
	/**
	 * 前端界面修改用户信息操作，仅修改用户的基本信息不含密码，权限，部门等数据
	 * */
	public ResultModel updateApp(User t) throws Exception {
		ResultModel rm = new ResultModel();
		if (t==null || t.getId() == null) {
			rm.setState("500");
			rm.setMsgInfo("修改失败：Id不能为空");
			return rm ;
		}else{
			t.setUpdate_time(new Date());
			t.setUpdate_man((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
			if(t.getAge()==null)
				t.setAge(0);
			String true_path=this.getBean(SpeOptBaseService.class).doAdd(t.getLogo());
			t.setLogo(true_path);
			super.update(t);
			rm.setState("200");
			return rm;
		}
	}

	/**
	 * 前端界面获取所有用户信息（包括用户名，登录名，该用户所在组织ID，组织部门名称）
	 * */
	public List<User> allUserInfoApp(){
		return this.getMapper(UserMapper.class).findWithCondition(null, null, null, 0, 0);
	}

	/**
	 * 前端界面获取所有用户信息,不去查部门, 只带用户基本信息
	 * */
	public List<UserInfo> userInfoApp(){
		List<UserInfo> list=this.getMapper(UserInfoMapper.class).findWithCondition(null, null, null, 0, 0);
		for(UserInfo user:list){
			UserRole userRole=new UserRole();
			userRole.setUserId(user.getId());
			List<UserRole> roleList=this.getBean(UserRoleServiceImpl.class).doQuery(userRole);
			String position="";
			for(UserRole roles:roleList){
				Role role=this.getBean(RoleServiceImpl.class).doQueryById(roles.getRoleId());
				if(role!=null)
					position+=role.getName()+",";
			}
			if(!"".equals(position)){
				position=position.substring(0, position.length()-1);
				user.setPositions(position);
			}
		}
		return list;
	}


	/**
	 * 根据部门编号得到该部门及其子部门下的所有人员信息
	 * */
	public List<User> findByDeptId(String deptId) throws Exception {
		if (StringUtils.isEmpty(deptId)) return null;
		return this.getMapper(UserMapper.class).findWithCondition(null, " (DEPT_ID LIKE '" + deptId + "%' or DEPT_ID='"+deptId+"')", "convert(username using gbk) asc", 0, 0);
	}

	/**
	 * 根据部门编号得到该部门下的所有人员信息
	 * */
	public List<User> findByDeptIds(String deptId) throws Exception {
		if (StringUtils.isEmpty(deptId)) return null;
		return this.getMapper(UserMapper.class).findWithCondition(null, "DEPT_ID='" + deptId + "'", 
				null, 0, 0);
	}


	public PageModel<User> findPageModel(User user, int pageNumber, int pageSize) {
		PageModel<User> pm = new PageModel<User>(pageNumber, pageSize);
		user = (user == null) ? new User() : user;
		StringBuilder sb = new StringBuilder(" 1=1 ");
		if (StringUtils.isNotEmpty(user.getLogin_name())) {
			sb.append("AND LOGIN_NAME LIKE '%" + user.getLogin_name() + "%' ");
			user.setLogin_name(null);
		}
		if (StringUtils.isNotEmpty(user.getUsername())) {
			sb.append(" AND USERNAME LIKE '%" + user.getUsername() + "%' ");
			user.setUsername(null);
		}
		if(StringUtils.isNotEmpty(user.getDept_name())) {
			sb.append("ANd DEPT_NAME like  '%" + user.getDept_name() + "%' ");
			user.setDept_name(null);
		}
		if (StringUtils.isNotEmpty(user.getId())) {
			sb.append(" AND ID LIKE '%" + user.getId() + "%' ");
			user.setId(null);
		}
		if(user.getLogin_time()!=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			String str=sdf.format(user.getLogin_time());  

			sb.append(" AND (login_time < '" + str + "' or login_time is null)");
			user.setLogin_time(null);
		}
		pm.setRows(this.getMapper(UserMapper.class).findWithCondition(user, sb.toString(), " valid_flag desc,id ", (pageNumber - 1) * pageSize, pageSize));
		pm.setTotal(this.getMapper(UserMapper.class).countWithCondition(user, sb.toString()));
		return pm;
	}

	//根据session中的用户名去查询用户信息
	public User findUserById(String userId){
		return this.getMapper(UserMapper.class).findById(userId);
	}
	/**
	 * 重置为默认密码为123456
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public void defaultPassword(String id,String password) throws Exception {
		if((!id.isEmpty() && id != null) && (!password.isEmpty() && password != null)){
			this.getMapper(UserMapper.class).resetPassword(id, encrypted(password));
		}
	}

	/**
	 * 重置设备锁默认为空
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public void defaultDevice(String id) throws Exception {
		this.getMapper(UserMapper.class).resetDevice(id, null);
	}

	/**
	 * 后台管理修改密码
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel resetPassword(String id,String OldPwd, String NewPwd) throws Exception {
		ResultModel rm = new ResultModel();
		if (StringUtils.isEmpty(id) || StringUtils.isEmpty(NewPwd)) {
			rm.setState("500");
			rm.setMsgInfo("用户ID或密码不能为空");
			return rm;
		}
		User u=new User();
		u.setId(id);
		//验证当前登陆人密码是否与之前的一致
		User user = this.getMapper(UserMapper.class).login(u, DataEncoder.shaEncode(OldPwd));
		if(user!=null){
			this.getMapper(UserMapper.class).resetPassword(id, encrypted(NewPwd));
			rm.setState("200");			
		}else{
			rm.setState("500");
			rm.setMsgInfo("原密码错误");
		}
		return rm;
	}

	/*************↓***************WEB*******************↓*****************/

	/**
	 * 前端界面获取所有用户信息（包括用户名，登录名，该用户所在组织ID，组织部门名称）
	 * 含分页，模糊查询DEPT_NAME，username
	 * */
	public ResultModel allUserInfoWeb(CommonPage<User> sum){
		int PageIndex=sum.getPageIndex();
		int PageSize=sum.getPageSize();
		User user=sum.getObject();
		ResultModel rm=new ResultModel();
		PageModel<User> pm=new PageModel<User>(PageIndex, PageSize);
		String sWh="";
		if(user.getId()!=null && !"".equals(user.getId()))
			sWh+=" id like '%"+user.getId()+"%' or ";
		if(user.getDept_name()!=null && !"".equals(user.getDept_name()))
			sWh+=" DEPT_NAME like '%"+user.getDept_name()+"%' or ";
		if(user.getUsername()!=null && !"".equals(user.getUsername()))
			sWh+=" USERNAME like '%"+user.getUsername()+"%' or ";

		if(!sWh.equals("")){
			sWh=sWh.substring(0, sWh.length()-3);
		}

		List<User> list=this.getMapper(UserMapper.class).findWithCondition(null, sWh, "USERNAME", (PageIndex-1)*PageSize,PageSize);
		int count=this.getMapper(UserMapper.class).countWithCondition(null, sWh);
		pm.setRows(list);
		pm.setTotal(count);
		rm.setData(pm);
		rm.setState("200");
		return rm;
	}

	/**
	 * Web端修改密码
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel resetPasswordWeb(CommonPage<User> sum) throws Exception{
		String id=sum.getMemo1();
		String OldPwd=sum.getMemo2();
		String NewPwd=sum.getMemo3();
		ResultModel rm=new ResultModel();
		rm.setState("200");
		if (StringUtils.isEmpty(id) || StringUtils.isEmpty(NewPwd)) {
			rm.setState("500");
			rm.setMsgInfo("用户ID或密码不能为空");
			return rm;
		}
		User u=new User();
		u.setId(id);
		//验证当前登陆人密码是否与之前的一致
		User user = this.getMapper(UserMapper.class).login(u, DataEncoder.shaEncode(OldPwd));
		if(user!=null){
			//可修改密码
			this.getMapper(UserMapper.class).resetPassword(id, encrypted(NewPwd));
		}else{
			rm.setState("500");
			rm.setMsgInfo("当前密码错误!");
		}
		return rm;
	}

	/**
	 * WEB前端界面修改用户信息操作，仅修改用户的基本信息不含密码，权限，部门等数据
	 * */
	public ResultModel updateWeb(User t) throws Exception {
		ResultModel rm = new ResultModel();
		t.setUpdate_time(new Date());
		t.setUpdate_man((String)getSession().getAttribute(HomeService.SESSION_USER_NAME));
		if(t.getAge()==null)
			t.setAge(0);
		if(t.getLogo()!=null&!"".equals(t.getLogo()))
			t.setLogo(this.getBean(SpeOptBaseService.class).doAdd(t.getLogo()));
		super.update(t);
		rm.setState("200");
		return rm;
	}
	/**
	 * 前端界面查看用户个人信息操作
	 * */
	public ResultModel userPersonInfoWeb(){
		ResultModel rm=new ResultModel();
		String id=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		User user= this.getMapper(UserMapper.class).findById(id);
		rm.setState("200");
		rm.setData(user);
		return rm;
	}

	/**
	 * WEB端根据用户ID数组查询用户们的信息
	 * */
	public ResultModel doQueryPartWeb(User user){
		ResultModel rm = new ResultModel();
		List<User> userList=user.getUsers();
		List<User> list=new ArrayList<User>();
		for(User users:userList){
			User u=this.getMapper(UserMapper.class).findById(users.getId());
			list.add(u);
		}
		rm.setState("200");
		rm.setData(list);
		return rm;
	}

	/**
	 * 根据部门编号查询该部门下的人员信息
	 * */
	public ResultModel findByDeptIdWeb(CommonPage<User> sum) throws Exception {
		ResultModel rm=new ResultModel();
		String deptId=sum.getMemo1();
		if (StringUtils.isEmpty(deptId)) return rm;
		List<User> list=this.getMapper(UserMapper.class).findWithCondition(null, "DEPT_ID='" + deptId + "'", null, 0, 0);
		rm.setState("200");
		rm.setData(list);
		return rm;
	}

	/**
	 * 根据角色编号得到该角色下的所有人员信息
	 * */
	public ResultModel findByRoleIdWeb(CommonPage<UserRole> sum) throws Exception {
		ResultModel rm=new ResultModel();
		try{
			UserRole userRole=sum.getObject();
			String userName=sum.getMemo1();
			String dept=sum.getMemo2();
			List<User> urList=this.getBean(UserMapper.class).doQueryByRoleNo(userRole.getRoleId(),userName,dept);

			rm.setData(urList);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除用户 参数id
	 * */
	public ResultModel doDeleteWeb(User user){
		ResultModel rm=new ResultModel();
		try{
			user.setValid_flag("0");		//离职
			this.getMapper(UserMapper.class).update(user);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("删除失败"+e.getMessage());
		}
		return rm;
	}
	/*****************************WEB*************************************/

}
