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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

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

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.core.auth.mapper.UserLoginMapper;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.service.UserLoginService;
import com.hnshituo.core.auth.vo.User;
import com.hnshituo.core.auth.vo.UserLogin;

@RemoteService(path = "UserLoginService")
public class UserLoginServiceImpl extends BaseServiceImpl<UserLogin, Object>	implements UserLoginService {

	/**
	 * 查询
	 * */
	public ResultModel doQueryWeb(CommonPage<UserLogin> sum){
		ResultModel rm=new ResultModel();
		UserLogin login=sum.getObject();
		if(login==null) login=new UserLogin();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<UserLogin> pm=new PageModel<UserLogin>(pageIndex, pageSize);
		try{
			List<UserLogin> loginList=this.getMapper(UserLoginMapper.class).doQuery(login,startTime,endTime,(pageIndex-1)*pageSize,pageSize*pageIndex);
			int count=this.getMapper(UserLoginMapper.class).doQueryCount(login,startTime,endTime);
			pm.setRows(loginList);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 报表
	 * */
	public ResultModel doQueryCensusWeb(CommonPage<UserLogin> sum){
		ResultModel rm=new ResultModel();
		UserLogin login=sum.getObject();
		if(login==null) login=new UserLogin();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String flag=sum.getMemo1();		
		PageModel<UserLogin> pm=new PageModel<UserLogin>(pageIndex, pageSize);
		try{
			int pre_pageSize=0;
			//			if("1".equals(flag)){
			pre_pageSize=pageSize;
			pageSize=0;
			//			}
			if(endTime!=null)
				endTime+=" 23:59:59";
			List<UserLogin> loginList=this.getMapper(UserLoginMapper.class).doQueryCensus(login,startTime,endTime);
			List<UserLogin> personList=this.getMapper(UserLoginMapper.class).doQueryPerson(login,startTime,endTime,(pageIndex-1)*pageSize,pageIndex*pageSize);
			int total=this.getMapper(UserLoginMapper.class).doQueryPersonCount(login,startTime,endTime);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			long twoTime = 2*24*60*60*1000; //获取2天的毫秒数
			GregorianCalendar gc = new GregorianCalendar(); 
			for(UserLogin persons:personList){		//人员列表
				int count=0;		//异常次数2天
				String firstLogin="";
				boolean in=true;
				Date sTime=null;
				Date eTime=null;
				int eva=0;
				int seven=0;
				for(UserLogin ur:loginList){
					if(ur.getLogin_name().equals(persons.getLogin_name())){
						seven++;
						long time= sdf.parse(ur.getCheck_time()).getTime();
						long times = time - twoTime;
						Date date=new Date(times); 	//将毫秒数转日期
						gc.setTime(date); 
						String startDate=sdf.format(gc.getTime()); //两天前的日期
						String endDate=ur.getCheck_time();
						List<UserLogin> checkList=this.getMapper(UserLoginMapper.class).doQueryCensus(persons, startDate, endDate);
						if(checkList.size()==0)		//2天异常次数
							count++;
						firstLogin=endDate;
						//最长未登录
						if(in){
							sTime=sdf.parse(ur.getCheck_time());
							in=false;
						}else{
							eTime=sdf.parse(ur.getCheck_time());		//计算两个时间差
							int cha = (int) ((sTime.getTime() - eTime.getTime()) / (1000*3600*24));
							if(cha>eva)
								eva=cha;		
							sTime=eTime;
						}
					}
				}
				List<UserLogin> checkList=this.getMapper(UserLoginMapper.class).doQueryCensus(persons, null, firstLogin);
				if(checkList.size()==0)			//如果是第一次登录该系统，则减一次异常
					count--;
				//判断选择的时间段内
				long time= sdf.parse(endTime).getTime();
				long times = time - twoTime;
				Date date=new Date(times); 	//将毫秒数转日期
				gc.setTime(date); 
				String startDate=sdf.format(gc.getTime()); //两天前的日期
				List<UserLogin> checkList2=this.getMapper(UserLoginMapper.class).doQueryCensus(persons, startDate, endTime);
				if(checkList2.size()==0)			//未登录过
					count++;
				persons.setCount(count);
				if(eTime==null&&startTime!=null){
					eTime=sdf.parse(startTime);
					int cha = (int) ((sTime.getTime() - eTime.getTime()) / (1000*3600*24));
					if(cha>eva)
						eva=cha;		
					sTime=eTime;
				}
				if(eTime!=null&&startTime!=null){
					sTime=sdf.parse(startTime);
					eTime=sdf.parse(endTime);
					int cnm = (int) ((eTime.getTime() - sTime.getTime()) / (1000*3600*24));
					int cao=cnm-seven;
					cao++;
					if(cao<0) cao=0;
					persons.setSeven_count(cao);
				}
				persons.setLong_count(eva);
			}
			if("1".equals(flag)){
				personList=doOrder(personList, flag);
			}
			if("".equals(login.getDept_id())&&"".equals(login.getLogin_name())&&"".equals(login.getUsername()))
				personList=doAddUser(personList,startTime,endTime);
			List<UserLogin> list = new ArrayList<UserLogin>();
			int startSize=(pageIndex-1)*pre_pageSize;
			int endSize=pageIndex*pre_pageSize;
			if(pre_pageSize>personList.size()||endSize>personList.size())
				endSize=personList.size();
			for(int a=startSize;a<endSize;a++){
				list.add(personList.get(a));
			}
			total=personList.size();
			personList=list;

			pm.setRows(personList);
			pm.setTotal(total);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){                                                                 
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 个人详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<UserLogin> sum){
		ResultModel rm=new ResultModel();
		UserLogin login=sum.getObject();
		if(login==null) login=new UserLogin();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			endTime+=" 23:59:59";
			List<UserLogin> list=new ArrayList<UserLogin>();
			List<UserLogin> loginList=this.getMapper(UserLoginMapper.class).doQueryCensus(login,startTime,endTime);
			if(startTime!=null&&endTime!=null&&loginList.size()>0){
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				Date sTime=sdf.parse(startTime);
				Date eTime=sdf.parse(endTime);
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(sTime);
				Calendar cal2 = Calendar.getInstance();
				cal2.setTime(eTime);
				int sday= cal1.get(Calendar.DAY_OF_YEAR);
				int eday= cal2.get(Calendar.DAY_OF_YEAR);
				int eva=eday-sday;		//计算两个时间差
				for(int v=0;v<=eva;v++){
					boolean flag=true;
					for(int a=loginList.size()-1;a>=0;a--){
						cal2.set(Calendar.DATE,cal1.get(Calendar.DATE)+v);
						if(sdf.format(cal2.getTime()).equals(loginList.get(a).getCheck_time())){		//如果有登录记录，插入list
							list.add(loginList.get(a));
							flag=false;
						}
					}
					if(flag){		//如果没有登录记录，新建对象插入list
						UserLogin ul=new UserLogin();
						ul.setCheck_time(sdf.format(cal2.getTime()));
						ul.setCount(0);
						ul.setLogin_name(loginList.get(0).getLogin_name());
						ul.setDept_id(loginList.get(0).getDept_id());
						ul.setDept_name(loginList.get(0).getDept_name());
						list.add(ul);
					}
				}
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){                                                                 
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	public ResultModel doAdd(UserLogin login){
		ResultModel rm=new ResultModel();
		try{
			login.setSeq(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
			login.setLogin_time(new Date());
			this.getMapper(UserLoginMapper.class).insert(login);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
		}
		return rm;
	}

	//使用迟到次数进行排序
	private List<UserLogin> doOrder(List<UserLogin> list,String order){
		for(UserLogin ur:list){		// 1迟到多 2迟到少 3考勤多 4考勤少
			switch(Integer.parseInt(order)){
			case 1:
				Collections.sort(list, new Comparator<UserLogin>(){
					@Override  
					public int compare(UserLogin o1, UserLogin o2){
						int i = o2.getCount() - o1.getCount() ;  
						if(i == 0){  
							return o2.getCount() - o1.getCount();  
						}  
						return i;  
					}
				});  
				break;
			default:break;
			}
		}
		return list;
	}

	public List<UserLogin> doAddUser(List<UserLogin> personList, String startTime, String endTime) throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<User> userList=this.getMapper(UserMapper.class).findWithCondition(null, " valid_flag='1'", null,0,0);
		Date sTime=null;
		Date eTime=null;
		int cha =0;
		if(startTime!=null&&endTime!=null){
			sTime=sdf.parse(startTime);
			eTime=sdf.parse(endTime);
			cha = (int) ((eTime.getTime() - sTime.getTime()) / (1000*3600*24));
		}
		for(User user:userList){
			int in=0;
			for(UserLogin urs:personList){
				if(urs.getLogin_name().equals(user.getId()))
					in++;
			}
			if(in==0){
				UserLogin ur=new UserLogin();
				ur.setLogin_name(user.getId());
				ur.setUsername(user.getUsername());
				ur.setDept_id(user.getDept_id());
				ur.setDept_name(user.getDept_name());
				ur.setLogin_in(false);
				ur.setLong_count(cha);
				ur.setSeven_count(cha);
				ur.setCount(1);
				personList.add(ur);
			}
		}
		return personList;
	}
}
