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

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.basic.util.DataEncoder;
import com.hnshituo.core.auth.mapper.FunctionMapper;
import com.hnshituo.core.auth.mapper.RoleMapper;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.service.FunctionService;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.service.UserService;
import com.hnshituo.core.auth.vo.Function;
import com.hnshituo.core.auth.vo.User;
import com.hnshituo.core.auth.vo.UserLogin;

@RemoteService(path="core/home")
public class HomeServiceImpl extends BaseServiceImpl implements HomeService {
	
	//获取日志记录器Logger，名字为本类类名
    private static Logger log = Logger.getLogger(HomeServiceImpl.class);
	/**
	 * 用户登录WEB(用对象传参)
	 */ 
	public ResultModel login4Web(CommonPage<User> sum) throws Exception {
		User in_user=sum.getObject();
		ResultModel rm=new ResultModel();
		rm.setState("200");
		String secret=DataEncoder.shaEncode(in_user.getPassword());
		User user = this.getMapper(UserMapper.class).login(in_user,secret);
		if (user == null) {
			rm.setState("500");
			rm.setMsgInfo("用户名或密码错误");
			return rm;
		}
		if("0".equals(user.getValid_flag())){
			rm.setState("500");
			rm.setMsgInfo("该账号已停用");
			return rm;
		}
		
		this.getSession().setAttribute(SESSION_USER_ID, user.getId());
		this.getSession().setAttribute(SESSION_USER_NAME, user.getUsername());
		this.getSession().setAttribute(SESSION_DEPT_ID, user.getDept_id());
		this.getSession().setAttribute(SESSION_DEPT_NAME, user.getDept_name());
		this.getSession().setAttribute(SESSION_WORK_ORD, in_user.getWrk_ord());
		this.getSession().setAttribute(SESSION_WORK_GRP, in_user.getWrk_grp());
		this.getSession().setAttribute(SESSION_WORK_TIME, in_user.getWrk_date());
		

		user.setImage(null);
		user.setPassword(in_user.getPassword());
		this.getSession().setAttribute(SESSION_USER, user);

		Boolean isAdmin=this.getMapper(RoleMapper.class).isAdmin(in_user.getId())==0?false:true;
		this.getSession().setAttribute(SESSION_ISADMIN, isAdmin);

		List<Function> funcs = findFuncByPrv();
		if (funcs != null) {
			Map<String, Function> funcsMap = new HashMap<String, Function>();
			for (Function function : funcs) {
				funcsMap.put(function.getUrl(), function);
			}
			this.getSession().setAttribute(SESSION_FUNC_PRV, funcsMap);
		}
		user.setPassword(null);
		rm.setData(user);
		
		User u=new User();
		u.setId(in_user.getId());
		u.setLogin_time(new Date());
//		u.setWrk_grp(in_user.getWrk_grp());
//		u.setWrk_ord(in_user.getWrk_ord());
		this.getMapper(UserMapper.class).update(u);
		
		//记录登录时间
		UserLogin login=new UserLogin();
		login.setLogin_name(user.getId());
		login.setUsername(user.getUsername());
		login.setDept_id(user.getDept_id());
		login.setDept_name(user.getDept_name());
		this.getBean(UserLoginServiceImpl.class).doAdd(login);
		
		return rm;
	}
	
	/**
	 *获取SSO系统的登录信息
	 */ 
	public ResultModel getUserInfoBySso(User user) throws Exception {
		ResultModel rm=new ResultModel();
		//User in_user=sum.getObject();
//		ResultModel rm=new ResultModel();
//		rm.setState("200");
//		String secret=DataEncoder.shaEncode(in_user.getPassword());
//		User user = this.getMapper(UserMapper.class).login(in_user,secret);
		if (user == null) {
			rm.setState("500");
			rm.setErrorInfo("用户名或密码错误");
			return rm;
		}
//		if("0".equals(user.getValid_flag())){
//			rm.setState("500");
//			rm.setMsgInfo("该账号已停用");
//			return rm;
//		}
		log.debug("User对象:"+user);
		this.getSession().setAttribute(SESSION_USER_ID, user.getId());
		this.getSession().setAttribute(SESSION_USER_NAME, user.getUsername());
		this.getSession().setAttribute(SESSION_DEPT_ID, user.getDept_id());
		this.getSession().setAttribute(SESSION_DEPT_NAME, user.getDept_name());
		this.getSession().setAttribute(SESSION_WORK_ORD, user.getWrk_ord());
		this.getSession().setAttribute(SESSION_WORK_GRP, user.getWrk_grp());
		this.getSession().setAttribute(SESSION_WORK_TIME, user.getWrk_date());
		
		String wrk_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String user_name = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String wrk_grp = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		String wrk_date = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_TIME);
		log.debug("wrk_ord:"+wrk_ord);
		log.debug("user_name:"+user_name);
		log.debug("wrk_grp:"+wrk_grp);
		log.debug("wrk_date:"+wrk_date);
		log.debug(">>>>>>>>>>>>>>>>>>>>");

		user.setImage(null);
		user.setPassword(user.getPassword());
		this.getSession().setAttribute(SESSION_USER, user);

		Boolean isAdmin=this.getMapper(RoleMapper.class).isAdmin(user.getId())==0?false:true;
		this.getSession().setAttribute(SESSION_ISADMIN, isAdmin);

		List<Function> funcs = findFuncByPrv();
		if (funcs != null) {
			Map<String, Function> funcsMap = new HashMap<String, Function>();
			for (Function function : funcs) {
				funcsMap.put(function.getUrl(), function);
			}
			this.getSession().setAttribute(SESSION_FUNC_PRV, funcsMap);
		}
		user.setPassword(null);
		rm.setData(user);
		
		User u=new User();
		u.setId(user.getId());
		u.setLogin_time(new Date());
//		u.setWrk_grp(in_user.getWrk_grp());
//		u.setWrk_ord(in_user.getWrk_ord());
		this.getMapper(UserMapper.class).update(u);
		
		//记录登录时间
		UserLogin login=new UserLogin();
		login.setLogin_name(user.getId());
		login.setUsername(user.getUsername());
		login.setDept_id(user.getDept_id());
		login.setDept_name(user.getDept_name());
		this.getBean(UserLoginServiceImpl.class).doAdd(login);
		
		rm.setState("200");
		return rm;
	}
	
	
	
	
	/**
	 * 获取用户权限
	 * */
	@RemoteService(path="button")
	public List<Function> findFuncByPrv() throws Exception {
		String userId = this.getSession().getAttribute(HomeService.SESSION_USER_ID).toString();
		List<Function> funcs = null;
		if (userId.equals("admin")) {
			funcs = this.getMapper(FunctionMapper.class).findWithCondition(null, "VISIBLE = 0 AND TYPE = 1", "SEQ", 0, 0);
		} else {
			User user = this.getBean(UserService.class).findById(userId);
			if (user == null || user.getRoles() == null || user.getRoles().size() < 1) return null;
			if(user.getRoles().size()>0&&user.getRoles().get(0).getId()==null) return null;
			funcs = this.getMapper(FunctionMapper.class).findFuncByRoles(user.getRoles());
		}
		return funcs;
	}

	
	/**
	 * 用户退出登录
	 */ 
	@RemoteService(path="exit")
	public ResultModel Exit() throws Exception {
		ResultModel rm=new ResultModel();
		Enumeration em = this.getSession().getAttributeNames();
		while(em.hasMoreElements()){
			this.getRequest().getSession().removeAttribute(em.nextElement().toString());
		}
		rm.setState("200");
		return rm;		
	}

	/**
	 * 显示内网地址
	 * */
	public String ipAddress() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String ip = request.getHeader("X-Forwarded-For");
		if (null == ip || 0 == ip.length() || "UNKNOWN".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (null == ip || 0 == ip.length() || "UNKNOWN".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (null == ip || 0 == ip.length() || "UNKNOWN".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (null == ip || 0 == ip.length() || "UNKNOWN".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if(ip != null) {
			return ip.split(",")[0];
		}else{
			return ip;
		}
	}

	public boolean hasPermission(String url) throws Exception {
		//如果该功能不受权限权限控制，返回true
		//TODO 该功能需优化。每次请求都会检查数据库，是否存在受管制的URL，较为费时，有性能优化空间
		boolean isExist = false;
		isExist = this.getBean(FunctionService.class).hasFunction(url);
		if (!isExist) return true; 

		Map<String, Function> funcs = (Map<String, Function>) this.getSession().getAttribute(HomeService.SESSION_FUNC_PRV);
		if (funcs!=null && funcs.size()>0) {
			if (funcs.containsKey(url)) {
				return true;
			}
		}
		return false;
	}
}
