package com.jeeplus.modules.API.oa;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.LocationUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.oa.entity.OaAttendance;
import com.jeeplus.modules.oa.entity.OaAttendancePlace;
import com.jeeplus.modules.oa.entity.OaAttendanceRule;
import com.jeeplus.modules.oa.service.OaAttendancePlaceService;
import com.jeeplus.modules.oa.service.OaAttendanceRuleService;
import com.jeeplus.modules.oa.service.OaAttendanceService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



/**
 * 考勤Controller
 * @author mengxy
 * @version 2017-5-10
 */
@Controller
@RequestMapping(value = "${frontPath}/oa/oaAttendance")
public class AttendanceController extends BaseController {
	
	@Autowired
	private OaAttendanceService oaAttendanceService;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private OaAttendanceRuleService oaAttendanceRuleService;

	@Autowired
	private OaAttendancePlaceService oaAttendancePlaceService;
	
	/**
	 * 考勤信息列表页面
	 */
	@ResponseBody
	@RequestMapping(value = "getAttendanceList" , method=RequestMethod.GET)
	public AjaxJson getAttendanceList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendance oaAttendance = new OaAttendance();
		String userId=request.getParameter("userId");
		String pageNo=request.getParameter("pageNo");
		oaAttendance.setUser(new User(userId));
		Page<OaAttendance> page = oaAttendanceService.findPage(new Page<OaAttendance>(request, response), oaAttendance); 

		if(page==null ){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2004);
			j.setMsg("获取考勤信息失败");
			j.put("data",page);
		}else if(pageNo !=null &&Integer.parseInt(pageNo)>page.getTotalPage()){
			j.put("data",new Page<OaAttendance>());
		    j.setMsg("获取考勤信息成功");
		    j.setErrorCode(ErrorCode.code_1004);
		}else{
			j.setErrorCode(ErrorCode.code_1004);
		    j.put("data", page);
		    j.setMsg("获取考勤信息成功");
		}
		return j;
	}
	
	/**
	 * 获取当月考勤
	 */
	@ResponseBody
	@RequestMapping(value = "getAttendanceListByMonth",method=RequestMethod.GET)
	public AjaxJson getAttendanceListByMonth(HttpServletRequest request,HttpServletResponse response){
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = request.getParameter("date");
		String str[] = date.split("-");
		if(str.length==2){
			String year = str[0];
			String month = str[1];
			if(month.length()==2){
				OaAttendance oaAttendance = new OaAttendance();
				User user = UserUtils.getUser();
				oaAttendance.setUser(user);
				List<OaAttendance> list = oaAttendanceService.findList(oaAttendance);
				List<Map<String,Object>> mapList = Lists.newArrayList();
				int count=DateUtils.getMaxDay(Integer.parseInt(year),Integer.parseInt(month));
				for (int i = 1; i <= count; i++) {
					List<OaAttendance> list1 = Lists.newArrayList();
					for(OaAttendance o : list){
						String date1 = sdf.format(o.getSignDate());
						String dates[] = date1.split("-");
						int a = Integer.parseInt(dates[2]);
						if(dates[0].equals(year) && dates[1].equals(month) && a==i){
							list1.add(o);
						}	
					}
					String day = "";
					if(i<10){
						day="0"+i;
					}else{
						day=i+"";
					}
					Map<String,Object> map = Maps.newHashMap();
					if(list1.size()>0){
						map.put("day", year+"-"+month+"-"+day);
						map.put("type","1");
					}else{
						map.put("day", year+"-"+month+"-"+day);
						map.put("type","0");
					}
					mapList.add(map);
				}
				j.put("data",mapList);
				j.setMsg("获取考勤记录成功");
				j.setErrorCode(ErrorCode.code_1004);
			}else{
				j.setMsg("日期格式错误，获取打考勤录失败");
				j.put("data", Lists.newArrayList());
				j.setErrorCode(ErrorCode.code_2002);
				j.setSuccess(false);
			}
		}else{
			j.setMsg("日期格式错误，获取考勤记录失败");
			j.put("data", Lists.newArrayList());
			j.setErrorCode(ErrorCode.code_2002);
			j.setSuccess(false);
		}
		
		return j;
		
	}
	
	/**
	 * 考勤信息列表页面
	 */
	@ResponseBody
	@RequestMapping(value = "getAttendanceListByDate" , method=RequestMethod.GET)
	public AjaxJson getAttendanceListByDate(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
		String date = request.getParameter("date");
        String userId = request.getParameter("userId");
		User user = UserUtils.getUser();
        if(user == null || user.getId() ==null){
            user = UserUtils.get(userId);
        }else{
            userId = user.getId();
        }
		OaAttendance oaAttendance = new OaAttendance();
		Date signDate = null ;

		try {
			signDate = sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        java.util.Date nowDate=null;
        try {
            nowDate= sdf.parse(sdf.format(new Date()));

        } catch (ParseException e) {

            e.printStackTrace();
        }
		oaAttendance.setUser(user);
		oaAttendance.setSignDate(signDate);
		oaAttendance.setCompany(UserUtils.getSelectCompany());
		List<OaAttendance> list = oaAttendanceService.findList(oaAttendance);
		List<Map<String,Object>> mapList = Lists.newArrayList();
		for(OaAttendance o : list){
			OaAttendanceRule r = oaAttendanceRuleService.get(o.getRule());
			Date startRule = null;
			Date endRule = null;
			String start = null;
			String end = null;
            Date startDate=o.getStartTime();
            Date endDate = o.getEndTime();
			Date startTime=null;
			Date endTime = null;
			try {
				startRule =sdf1.parse(r.getStartTime());
				endRule =sdf1.parse(r.getEndTime());

				if(o.getStartTime()!=null && !o.getStartTime().equals("")){
					start=sdf1.format(o.getStartTime());
					startTime=sdf1.parse(start);
				}
				if(o.getEndTime()!=null && !o.getEndTime().equals("")){
					end=sdf1.format(o.getEndTime());
					endTime=sdf1.parse(end);
				}	
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            Calendar c1 =  new GregorianCalendar();//次日规定上班时间
            Calendar c2 =  new GregorianCalendar();//上班时间
            Calendar c3 =  new GregorianCalendar();//下班时间
            Calendar c4 =  new GregorianCalendar();//规定上班时间
            Calendar c5 =  new GregorianCalendar();//规定上班时间

            c1.setTime(startRule);
            if(startDate !=null) {
                c2.setTime(startDate);
            }
            if(endDate !=null) {
                c3.setTime(endDate);
            }
            c4.setTime(startRule);
            c5.setTime(endRule);
            c1.set(Calendar.YEAR, c2.get(Calendar.YEAR));
            c1.set(Calendar.MONTH, c2.get(Calendar.MONTH));
            c1.set(Calendar.DAY_OF_MONTH, c2.get(Calendar.DAY_OF_MONTH));
            c1.add(Calendar.DATE,+1);

            //1 正常打卡 、 2迟到、  3早退 、 4未打卡 、 5待打卡
			User u = userDao.get(user);
			Map<String,Object> map = Maps.newHashMap();
            if(startTime!=null && endTime!=null){
				map.put("hint", "今日打卡2次");
                if(startTime.getTime()<=startRule.getTime()){
                    map.put("morning", "1");
                    map.put("startTime", sdf2.format(startTime));
                }else{
                    map.put("morning", "2");
                    map.put("startTime", sdf2.format(startTime));
                }
                if(endTime.getTime()>=endRule.getTime() && c3.compareTo(c1)<0){
                    map.put("afternoon", "1");
                    map.put("endTime", sdf2.format(endTime));
                }else if(endTime.getTime()<endRule.getTime()){
                    map.put("afternoon", "3");
                    map.put("endTime", sdf2.format(endTime));
                }else{
                    map.put("afternoon", "3");
                    map.put("endTime", sdf2.format(endTime));
                }
			}else if(startTime==null && endTime!=null){
				map.put("hint", "今日打卡1次");
				if(endTime.getTime()>=endRule.getTime()){
					map.put("afternoon", "1");
					map.put("endTime", sdf2.format(endTime));
					map.put("morning", "4");
					map.put("startTime", "");
				}else if(c3.compareTo(c1)<0){
                    map.put("afternoon", "1");
                    map.put("endTime", sdf2.format(endTime));
                    map.put("morning", "4");
                    map.put("startTime", "");
                }else{
					map.put("afternoon", "3");
					map.put("endTime", sdf2.format(endTime));
					map.put("morning", "4");
					map.put("startTime", "");
				}
			}else if(startTime!=null && endTime==null){
				map.put("hint", "今日打卡1次");
                if(signDate.compareTo(nowDate)>=0) {
                    if (startTime.getTime() <= startRule.getTime()) {
                        map.put("morning", "1");
                        map.put("startTime", sdf2.format(startTime));
                        map.put("afternoon", "5");
                        map.put("endTime", "");
                    } else {
                        map.put("morning", "2");
                        map.put("startTime", sdf2.format(startTime));
                        map.put("afternoon", "5");
                        map.put("endTime", "");
                    }
                }else{
                    if (startTime.getTime() <= startRule.getTime()) {
                        map.put("morning", "1");
                        map.put("startTime", sdf2.format(startTime));
                        map.put("afternoon", "4");
                        map.put("endTime", "");
                    } else {
                        map.put("morning", "2");
                        map.put("startTime", sdf2.format(startTime));
                        map.put("afternoon", "4");
                        map.put("endTime", "");
                    }
                }
			}
			map.put("userId", u.getId());
			mapList.add(map);
		}
		if(mapList ==null || mapList.size()==0){
            Map<String,Object> map = Maps.newHashMap();
            if(signDate.compareTo(nowDate)>=0){
                map.put("userId", userId);
                map.put("hint", "今日打卡0次");
                map.put("morning", "5");
                map.put("startTime", "");
                map.put("afternoon", "5");
                map.put("endTime", "");
                mapList.add(map);
                j.setMsg("获取当日考勤成功");
				j.setErrorCode(ErrorCode.code_1004);
                j.put("date", mapList);
            }else {
                map.put("userId", userId);
                map.put("hint", "今日打卡0次");
                map.put("morning", "4");
                map.put("startTime", "");
                map.put("afternoon", "4");
                map.put("endTime", "");
                mapList.add(map);
                j.setMsg("获取当日考勤成功");
				j.setErrorCode(ErrorCode.code_1004);
                j.put("date", mapList);
            }
		}else{
			j.put("date",mapList);
			j.setSuccess(true);
			j.setErrorCode(ErrorCode.code_1004);
			j.setMsg("获取当日考勤成功");
		}
		
		return j;	
	}

	/**
	 * 获取当前时间的接口，格式为*年*月*日 周*
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTodayTime" , method=RequestMethod.GET)
	public AjaxJson getTodayTime(HttpServletRequest request, HttpServletResponse response){
		AjaxJson j=new AjaxJson();
		Map<String,String> map = Maps.newHashMap();
		Calendar now = Calendar.getInstance();
		String time =  now.get(Calendar.YEAR)+"年"+ (now.get(Calendar.MONTH) + 1) + "月"+now.get(Calendar.DAY_OF_MONTH)+"日";
		map.put("time",time);
		//String week =new SimpleDateFormat("EEEE").format(new Date()).replace("星期","周")+"";
		String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		String week = weekDays[w];
		map.put("week",week);
		j.put("data",map);
		return j;
	}

	/**
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTodayAttendance" , method=RequestMethod.GET)
	public AjaxJson getTodayAttendance(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendance oaAttendance = new OaAttendance();
		String userId=request.getParameter("userId");
		String date =(new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
		//String date=request.getParameter("date");
		if(userId!=null &&!userId.equals("")) {
			oaAttendance.setUser(new User(userId));
		}else{
			oaAttendance.setUser(UserUtils.getUser());
		}
		oaAttendance.setCompany(UserUtils.getSelectCompany());
		List<Map<String,Object>> mapList = Lists.newArrayList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
		Date signDate = null;
		try {
			signDate = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		oaAttendance.setSignDate(signDate);
		List<OaAttendance> oaAttList = oaAttendanceService.findList(oaAttendance);

		if(oaAttList==null ){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2005);
			j.setMsg("获取考勤信息失败");
			j.put("data",oaAttList);
		}else if(oaAttList.size()>0){
			OaAttendance o = oaAttList.get(0);
			OaAttendanceRule r = oaAttendanceRuleService.get(o.getRule());
			Date startRule = null;
			Date endRule = null;
			String start = null;
			String end = null;
			Date startDate=o.getStartTime();
			Date endDate = o.getEndTime();
			Date startTime=null;
			Date endTime = null;
			try {
				startRule =sdf1.parse(r.getStartTime());
				endRule =sdf1.parse(r.getEndTime());

				if(o.getStartTime()!=null && !o.getStartTime().equals("")){
					start=sdf2.format(o.getStartTime());
					startTime=sdf2.parse(start);
				}
				if(o.getEndTime()!=null && !o.getEndTime().equals("")){
					end=sdf2.format(o.getEndTime());
					endTime=sdf2.parse(end);
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_2004);
				j.setMsg("获取考勤信息失败");
				return  j;
				//e.printStackTrace();
			}
			Calendar c1 =  new GregorianCalendar();//次日规定上班时间
			Calendar c2 =  new GregorianCalendar();//上班时间
			Calendar c3 =  new GregorianCalendar();//下班时间
			Calendar c4 =  new GregorianCalendar();//规定上班时间
			Calendar c5 =  new GregorianCalendar();//规定上班时间

			c1.setTime(startRule);
			if(startDate !=null) {
				c2.setTime(startDate);
			}
			if(endDate !=null) {
				c3.setTime(endDate);
			}
			c4.setTime(startRule);
			c5.setTime(endRule);
			c1.set(Calendar.YEAR, c2.get(Calendar.YEAR));
			c1.set(Calendar.MONTH, c2.get(Calendar.MONTH));
			c1.set(Calendar.DAY_OF_MONTH, c2.get(Calendar.DAY_OF_MONTH));
			c1.add(Calendar.DATE,+1);

			//1 正常打卡 、 2迟到、  3早退 、 5待打卡

			Map<String,Object> map = Maps.newHashMap();
			if(startTime!=null && endTime!=null){
				if(startTime.getTime()<=startRule.getTime()){
					map.put("morning", "1");
					map.put("startTime", sdf2.format(startTime));
				}else{
					map.put("morning", "2");
					map.put("startTime", sdf2.format(startTime));
				}
				if(endTime.getTime()>=endRule.getTime() && c3.compareTo(c1)<0){
					map.put("afternoon", "1");
					map.put("endTime", sdf2.format(endTime));
				}else if(endTime.getTime()<endRule.getTime()){
					map.put("afternoon", "3");
					map.put("endTime", sdf2.format(endTime));
				}else{
					map.put("afternoon", "3");
					map.put("endTime", sdf2.format(endTime));
				}
			}else if(startTime==null && endTime!=null){
				if(endTime.getTime()>=endRule.getTime() && c3.compareTo(c1)<0){
					map.put("afternoon", "1");
					map.put("endTime", sdf2.format(endTime));
					map.put("morning", "5");
					map.put("startTime", "");
				}else if(endTime.getTime()<endRule.getTime()){
					map.put("afternoon", "3");
					map.put("endTime", sdf2.format(endTime));
					map.put("morning", "5");
					map.put("startTime", "");
				}else{
					map.put("afternoon", "3");
					map.put("endTime", sdf2.format(endTime));
					map.put("morning", "5");
					map.put("startTime", "");
				}
			}else if(startTime!=null && endTime==null){
				if(startTime.getTime()<=startRule.getTime()){
					map.put("morning", "1");
					map.put("startTime", sdf2.format(startTime));
					map.put("afternoon", "5");
					map.put("endTime", "");
				}else{
					map.put("morning", "2");
					map.put("startTime", sdf2.format(startTime));
					map.put("afternoon", "5");
					map.put("endTime", "");
				}
			}
			mapList.add(map);

		}else {
			Map<String,Object> map = Maps.newHashMap();
			map.put("userId", userId);
			map.put("hint", "今日打卡0次");
			map.put("morning", "5");
			map.put("startTime", "");
			map.put("afternoon", "5");
			map.put("endTime", "");
			mapList.add(map);
			j.setMsg("获取当日考勤成功");
			j.setErrorCode(ErrorCode.code_1004);
		}
		j.put("data",mapList);
		return j;
	}
	
	/**
	 * 打卡接口
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "addPunchCard" , method=RequestMethod.GET)
	public AjaxJson addPunchCard(HttpServletRequest request, HttpServletResponse response) throws ParseException {
		AjaxJson j=new AjaxJson();
		OaAttendance oaAttendance = new OaAttendance();
		String userId = request.getParameter("userId");
		String companyId = request.getParameter("companyId");
		if(Strings.isNullOrEmpty(companyId)){
			companyId = UserUtils.getSelectCompany().getId();
		}
		String ruleId = request.getParameter("ruleId");
		String lnt = request.getParameter("lnt");
		String lat = request.getParameter("lat");
		String wifi=request.getParameter("wifi");
		String cardType = request.getParameter("cardType");
		logger.info("http://localhost:8888/jeeplus/f/oa/oaAttendance/addPunchCard?userId="+userId+"&companyId="+companyId+"&ruleId="+ruleId+"&lnt="+lnt+"&lat="+lat+"&wifi="+wifi+"&cardType="+cardType);
		//依据公司和规则编号查询规则
		OaAttendanceRule oaRule = oaAttendanceRuleService.queryRuleByCompanyIdAndRuleId(ruleId, companyId);
		if(oaRule == null){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2005);
			j.setMsg("当前公司没有考勤规则");
			return j;
		}
		String placeId = oaRule.getPlaceId();
		String wi = oaRule.getWifi();
		if(Strings.isNullOrEmpty(placeId) && Strings.isNullOrEmpty(wi)){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2005);
			j.setMsg("没有考勤规则，无法打卡");
			return j;
		}
		String[] split = placeId.split(",");
		List arr = new ArrayList();
		for (int i = 0; i < split.length; i++) {
			if(!"-1".equals(split[i])){
				OaAttendancePlace oap = oaAttendancePlaceService.get(split[i]);
				double placeScope = 0d;
				double longitude = 0d;
				if(!Strings.isNullOrEmpty(oap.getPlaceScope())){
					placeScope = Double.parseDouble(oap.getPlaceScope());
				}else {
					placeScope = Double.parseDouble(200+"");
				}
				if(!Strings.isNullOrEmpty(oap.getLongitude())){
					longitude = Double.parseDouble(oap.getLongitude());
				}
				double latitude = 0d;
				if(!Strings.isNullOrEmpty(oap.getLatitude())){
					latitude = Double.parseDouble(oap.getLatitude());
				}
				double lntd = 0d;
				double latd = 0d;
				if(!Strings.isNullOrEmpty(lnt)){
					lntd = Double.parseDouble(lnt);
				}
				if(!Strings.isNullOrEmpty(lat)){
					latd = Double.parseDouble(lat);
				}
				double distance = LocationUtils.getDistance(longitude, latitude, lntd, latd);
				Double d = new Double(distance);
				Double dp = new Double(placeScope);
				int i1 = d.compareTo(dp);
				if(i1 <= 0){
					//在范围内
					arr.add(i1);
				}

			}
		}
		boolean wifiBool = false;
		String[] wifis = wi.split(",");
		if (StringUtils.isNotBlank(wifi) ){
			for (String w : wifis) {
				if (!wifi.equals("-1") && wifi.equals(w)) {
					wifiBool = true;
					break;
				}
			}
		}
		if(arr.size() == 0 && !wifiBool ){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			j.setMsg("不在打卡范围内");
			return j;
		}

        companyId = UserUtils.getSelectCompany().getId();
        logger.info("addPunchCard / companyId="+companyId);
		String flag="";
		OaAttendanceRule oaAttendanceRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId);
		if(oaAttendanceRule.getCompany().getId().equals(companyId)){
			if(oaAttendanceRule != null){
//			if(oaAttendanceRule.getWifi().equals(wifi)){
				oaAttendance.setUser(new User(userId));
				oaAttendance.setCompany(new Office(companyId));
				oaAttendance.setRule(new OaAttendanceRule(ruleId));
				oaAttendance.setIsNewRecord(false);
				if(cardType.equals("1")){
					flag = oaAttendanceService.save(oaAttendance,"1");
				}
				if(cardType.equals("2")){
					flag = oaAttendanceService.save(oaAttendance,"2");
				}

//			}
			}
		}else {
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			j.setMsg("打卡失败，公司信息不一致 请重新登录");
		}
		if(oaAttendanceRule != null){
//			if(oaAttendanceRule.getWifi().equals(wifi)){
				oaAttendance.setUser(new User(userId));
				oaAttendance.setCompany(new Office(companyId));
				oaAttendance.setRule(new OaAttendanceRule(ruleId));
				oaAttendance.setIsNewRecord(false);
				if(cardType.equals("1")){
					flag = oaAttendanceService.save(oaAttendance,"1");
				}
				if(cardType.equals("2")){
					flag = oaAttendanceService.save(oaAttendance,"2");
				}

//			}
		}
		if(StringUtils.isNotBlank(flag)){
			if(flag.equals("ok")){
				j.put("data", "success");
				j.setMsg("打卡成功");
				j.setErrorCode(ErrorCode.code_1004);
			}else{
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_1004);
				j.setMsg(flag);
			}
		}else {
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2004);
			j.setMsg("数据异常！");
			j.setMsg(flag);
		}
		return j;
	}
	
	
	/**
	 * 获取考勤规则接口
	 */
	@ResponseBody
	@RequestMapping(value = "getCompanyRule" , method=RequestMethod.GET)
	public AjaxJson getCompanyRule(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendance oaAttendance = new OaAttendance();
		String ruleId=request.getParameter("ruleId");
		String userId=request.getParameter("userId");
		String companyId=request.getParameter("companyId");
        companyId = UserUtils.getSelectCompany().getId();
        OaAttendanceRule oaAttendanceRule = new OaAttendanceRule();
        if (!companyId.equals("1")){
            if(ruleId != null && !ruleId.equals("")){
                oaAttendanceRule =oaAttendanceRuleService.get(ruleId);
            }else{
                oaAttendanceRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId);
                oaAttendance.setUser(new User(userId));
            }
        }
		if(oaAttendanceRule==null || oaAttendanceRule.getId()==null){
			j.put("data", new HashedMap());
		    j.setMsg("获取考勤规则成功");
		    j.setErrorCode(ErrorCode.code_1004);
		}else{
            String wifi = oaAttendanceRule.getWifi();
            String wifiName = oaAttendanceRule.getWifiName();
            String placeId = oaAttendanceRule.getPlaceId();
            Map<String,Object> map1 = new HashMap<String,Object>();
            Map<String,Object> map2 = new HashMap<String,Object>();
            Map<String,Object> map3 = new HashMap<String,Object>();
            Map<String,Object> map4 = new HashMap<String,Object>();
            Map<String,Object> map5 = new HashMap<String,Object>();
            int status1 = 0;
            int status2 = 0;
            int status3 = 0;
            int status4 = 0;
            int status5 = 0;
            if (StringUtils.isNotBlank(wifi)){
                String[] wifis = wifi.split(",");
                map1.put("wifi",wifis[0].equals("-1")?"":wifis[0]);
                map2.put("wifi",wifis[1].equals("-1")?"":wifis[1]);
                map3.put("wifi",wifis[2].equals("-1")?"":wifis[2]);
                map4.put("wifi",wifis[3].equals("-1")?"":wifis[3]);
                map5.put("wifi", wifis[4].equals("-1")?"":wifis[4]);
                if (wifis[0].equals("-1")){
                    status1++;
                }
                if (wifis[1].equals("-1")){
                    status2++;
                }
                if (wifis[2].equals("-1")){
                    status3++;
                }
                if (wifis[3].equals("-1")){
                    status4++;
                }
                if (wifis[4].equals("-1")){
                    status5++;
                }
            }
            if (StringUtils.isNotBlank(wifiName)){
                String[] wifiNames = wifiName.split(",");
                map1.put("wifiName",wifiNames[0].equals("-1")?"":wifiNames[0]);
                map2.put("wifiName",wifiNames[1].equals("-1")?"":wifiNames[1]);
                map3.put("wifiName",wifiNames[2].equals("-1")?"":wifiNames[2]);
                map4.put("wifiName",wifiNames[3].equals("-1")?"":wifiNames[3]);
                map5.put("wifiName", wifiNames[4].equals("-1")?"":wifiNames[4]);
            }
            if (StringUtils.isNotBlank(placeId)){
                String[] placeIds = placeId.split(",");
                map1.put("placeId",placeIds[0].equals("-1")?"":placeIds[0]);
                map2.put("placeId",placeIds[1].equals("-1")?"":placeIds[1]);
                map3.put("placeId",placeIds[2].equals("-1")?"":placeIds[2]);
                map4.put("placeId",placeIds[3].equals("-1")?"":placeIds[3]);
                map5.put("placeId", placeIds[4].equals("-1")?"":placeIds[4]);
                if (placeIds[0].equals("-1")){
                    map1.put("placeName","");
                    map1.put("placeScope","");
                    map1.put("latitude","");
                    map1.put("longitude","");
                    status1++;
                }else {
                    OaAttendancePlace oaAttendancePlace = oaAttendanceRuleService.getOaAttendancePlace(placeIds[0]);
                    String placeName = oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceName())?"":oaAttendancePlace.getPlaceName();
                    String placeScope =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceScope())?"":oaAttendancePlace.getPlaceScope();
                    String latitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLatitude())?"":oaAttendancePlace.getLatitude();
                    String longitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLongitude())?"":oaAttendancePlace.getLongitude();
                    map1.put("placeName",placeName);
                    map1.put("placeScope",placeScope);
                    map1.put("latitude",latitude);
                    map1.put("longitude",longitude);
                }
                if (placeIds[1].equals("-1")){
                    map2.put("placeName","");
                    map2.put("placeScope","");
                    map2.put("latitude","");
                    map2.put("longitude","");
                    status2++;
                }else {
                    OaAttendancePlace oaAttendancePlace = oaAttendanceRuleService.getOaAttendancePlace(placeIds[1]);
                    String placeName = oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceName())?"":oaAttendancePlace.getPlaceName();
                    String placeScope =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceScope())?"":oaAttendancePlace.getPlaceScope();
                    String latitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLatitude())?"":oaAttendancePlace.getLatitude();
                    String longitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLongitude())?"":oaAttendancePlace.getLongitude();
                    map2.put("placeName",placeName);
                    map2.put("placeScope",placeScope);
                    map2.put("latitude",latitude);
                    map2.put("longitude",longitude);
                }
                if (placeIds[2].equals("-1")){
                    map3.put("placeName","");
                    map3.put("placeScope","");
                    map3.put("latitude","");
                    map3.put("longitude","");
                    status3++;
                }else {
                    OaAttendancePlace oaAttendancePlace = oaAttendanceRuleService.getOaAttendancePlace(placeIds[2]);
                    String placeName = oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceName())?"":oaAttendancePlace.getPlaceName();
                    String placeScope =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceScope())?"":oaAttendancePlace.getPlaceScope();
                    String latitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLatitude())?"":oaAttendancePlace.getLatitude();
                    String longitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLongitude())?"":oaAttendancePlace.getLongitude();
                    map3.put("placeName",placeName);
                    map3.put("placeScope",placeScope);
                    map3.put("latitude",latitude);
                    map3.put("longitude",longitude);
                }
                if (placeIds[3].equals("-1")){
                    map4.put("placeName","");
                    map4.put("placeScope","");
                    map4.put("latitude","");
                    map4.put("longitude","");
                    status4++;
                }else {
                    OaAttendancePlace oaAttendancePlace = oaAttendanceRuleService.getOaAttendancePlace(placeIds[3]);
                    String placeName = oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceName())?"":oaAttendancePlace.getPlaceName();
                    String placeScope =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceScope())?"":oaAttendancePlace.getPlaceScope();
                    String latitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLatitude())?"":oaAttendancePlace.getLatitude();
                    String longitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLongitude())?"":oaAttendancePlace.getLongitude();
                    map4.put("placeName",placeName);
                    map4.put("placeScope",placeScope);
                    map4.put("latitude",latitude);
                    map4.put("longitude",longitude);
                }
                if (placeIds[4].equals("-1")){
                    map5.put("placeName","");
                    map5.put("placeScope","");
                    map5.put("latitude","");
                    map5.put("longitude","");
                    status5++;
                }else {
                    OaAttendancePlace oaAttendancePlace = oaAttendanceRuleService.getOaAttendancePlace(placeIds[4]);
                    String placeName = oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceName())?"":oaAttendancePlace.getPlaceName();
                    String placeScope =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getPlaceScope())?"":oaAttendancePlace.getPlaceScope();
                    String latitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLatitude())?"":oaAttendancePlace.getLatitude();
                    String longitude =  oaAttendancePlace==null||StringUtils.isBlank(oaAttendancePlace.getLongitude())?"":oaAttendancePlace.getLongitude();
                    map5.put("placeName",placeName);
                    map5.put("placeScope",placeScope);
                    map5.put("latitude",latitude);
                    map5.put("longitude",longitude);
                }
            }
            List list = new ArrayList();
            if (status1!=2){
                list.add(map1);
                if (status2!=2){
                    list.add(map2);
                }if (status3!=2){
                    list.add(map3);
                }if (status4!=2){
                    list.add(map4);
                }if (status5!=2){
                    list.add(map5);
                }
            }
            oaAttendanceRule.setList(list);
		    j.put("data", oaAttendanceRule);
		    j.setMsg("获取考勤规则成功");
		    j.setErrorCode(ErrorCode.code_1004);
		}
		return j;
	}

	/**
	 * 保存考勤规则接口
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "saveCompanyRule" , method=RequestMethod.GET)
	public AjaxJson saveCompanyRule(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
        try {
            OaAttendanceRule oaAttendanceRule = new OaAttendanceRule();
            OaAttendanceRule oaAttRule = null;
            String ruleId = request.getParameter("ruleId");

            String companyId = request.getParameter("companyId");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String workdays = request.getParameter("workdays");
            /*String wifi = request.getParameter("wifi");
            String wifiName = request.getParameter("wifiName");
            String placeId = request.getParameter("place");
            if ((wifi == null || wifi == "") && (placeId == null || placeId == "")) {
                j.setSuccess(false);
                j.setErrorCode("304");
                j.setMsg("保存考勤规则失败！");
                return j;
            }*/
            String wifia = request.getParameter("wifia");
            String wifiNamea = request.getParameter("wifiNamea");
            String wifib = request.getParameter("wifib");
            String wifiNameb = request.getParameter("wifiNameb");
            String wific = request.getParameter("wific");
            String wifiNamec = request.getParameter("wifiNamec");
            String wifid = request.getParameter("wifid");
            String wifiNamed = request.getParameter("wifiNamed");
            String wifie = request.getParameter("wifie");
            String wifiNamee = request.getParameter("wifiNamee");
            String placeIda = request.getParameter("placea");
            String placeIdb = request.getParameter("placeb");
            String placeIdc = request.getParameter("placec");
            String placeIdd = request.getParameter("placed");
            String placeIde = request.getParameter("placee");
            companyId = UserUtils.getSelectCompany().getId();
            if ((wifia == null || wifia == "") && (placeIda == null || placeIda == "")) {
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2004);
                j.setMsg("保存考勤规则失败！");
                return j;
            }
            if (StringUtils.isBlank(wifia)) {wifia = "-1";}
            if (StringUtils.isBlank(wifib)) {wifib = "-1";}
            if (StringUtils.isBlank(wific)) {wific = "-1";}
            if (StringUtils.isBlank(wifid)) {wifid = "-1";}
            if (StringUtils.isBlank(wifie)) {wifie = "-1";}
            if (StringUtils.isBlank(wifiNamea)) {wifiNamea = "-1";}
            if (StringUtils.isBlank(wifiNameb)) {wifiNameb = "-1";}
            if (StringUtils.isBlank(wifiNamec)) {wifiNamec = "-1";}
            if (StringUtils.isBlank(wifiNamed)) {wifiNamed = "-1";}
            if (StringUtils.isBlank(wifiNamee)) {wifiNamee = "-1";}
            if (StringUtils.isBlank(placeIda)) {placeIda = "-1";}
            if (StringUtils.isBlank(placeIdb)) {placeIdb = "-1";}
            if (StringUtils.isBlank(placeIdc)) {placeIdc = "-1";}
            if (StringUtils.isBlank(placeIdd)) {placeIdd = "-1";}
            if (StringUtils.isBlank(placeIde)) {placeIde = "-1";}
            String wifi = wifia + "," + wifib + "," + wific + "," + wifid + "," + wifie;
            String placeId = placeIda + "," + placeIdb + "," + placeIdc + "," + placeIdd + "," + placeIde;
            String wifiName = wifiNamea + "," + wifiNameb + "," + wifiNamec + "," + wifiNamed + "," + wifiNamee;

            if (ruleId != null && !ruleId.equals("")) {
                oaAttendanceRule = oaAttendanceRuleService.get(ruleId);
            } else if (companyId != null && !companyId.equals("")) {
                oaAttRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId);
            } else {
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2006);
                j.setMsg("保存考勤规则失败！");
                return j;
            }
            if (oaAttRule != null) {
                oaAttendanceRule = oaAttRule;
            }
            oaAttendanceRule.setCompany(new Office(companyId));
            oaAttendanceRule.setStartTime(startTime);
            oaAttendanceRule.setEndTime(endTime);
            oaAttendanceRule.setWorkdays(workdays);
            oaAttendanceRule.setWifi(wifi);
            oaAttendanceRule.setWifiName(wifiName);
            oaAttendanceRule.setPlaceId(placeId);
            oaAttendanceRule.setIsNewRecord(false);
            oaAttendanceRuleService.save(oaAttendanceRule);
            j.put("data", oaAttendanceRule);
            j.setMsg("保存考勤规则成功");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            logger.info("e="+e.getMessage());
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
            j.setMsg("保存考勤规则失败");
        }
		return j;
	}
	
	
	
	
	/**
	 * 删除考勤规则接口
	 */
	@ResponseBody
	@RequestMapping(value = "deleteCompanyRule" , method=RequestMethod.GET)
	public AjaxJson deleteCompanyRule(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendanceRule oaAttendanceRule = new OaAttendanceRule();
		String ruleId=request.getParameter("ruleId");
		
		String companyId=request.getParameter("companyId");
		if(ruleId != null && !ruleId.equals("")){
			oaAttendanceRule =oaAttendanceRuleService.get(ruleId);
		}else if(companyId != null && !companyId.equals("")){
			oaAttendanceRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId); 
		}
		oaAttendanceRuleService.delete(oaAttendanceRule);
		j.put("data", "success");
		   
		j.setMsg("删除考勤规则成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
	
	/**
	 * 获取考勤地点接口
	 */
	@ResponseBody
	@RequestMapping(value = "getAttendancePlace" , method=RequestMethod.GET)
	public AjaxJson getAttendancePlace(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendanceRule oaAttendanceRule = null;
		String ruleId=request.getParameter("ruleId");
		
		String companyId=request.getParameter("companyId");
        companyId = UserUtils.getSelectCompany().getId();
		List<OaAttendancePlace> oaAttendancePlaceList =new ArrayList<OaAttendancePlace>();
		if(ruleId != null && !ruleId.equals("")){	
			oaAttendanceRule =oaAttendanceRuleService.get(ruleId);
		}else if(companyId != null && !companyId.equals("")){
			oaAttendanceRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId); 
		}
		if(oaAttendanceRule==null){
//			j.setSuccess(false);
//			j.setErrorCode("-1");
//			j.setMsg("考勤规则不存在");
		}
		oaAttendancePlaceList = oaAttendanceRuleService.findAttendancePlaceByCompany(companyId);

		j.put("data", oaAttendancePlaceList);
		   
		j.setMsg("获取考勤地点成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
	
	
	/**
	 * 保存考勤地点接口
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "saveAttendancePlace" , method=RequestMethod.GET)
	public AjaxJson saveAttendancePlace(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendanceRule oaAttendanceRule = null;
		OaAttendancePlace oaAttendancePlace = new OaAttendancePlace();
		String ruleId=request.getParameter("ruleId");
		
		String placeId=request.getParameter("placeId");
		String companyId=request.getParameter("companyId");
		companyId = UserUtils.getUser().getComId();
		String placeName=request.getParameter("placeName");
		String placeScope=request.getParameter("placeScope");
		
		String longitude=request.getParameter("longitude");
		String latitude=request.getParameter("latitude");
		
		if(placeName ==null || placeName.equals("")){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			j.setMsg("考勤地点不能为空！");
			return j;
		}
		
		if(placeScope ==null || placeScope.equals("")){
			placeScope = "100";
		}
		
		if(placeId != null && !placeId.equals("")){	
			oaAttendancePlace =oaAttendanceRuleService.getOaAttendancePlace(placeId);
		}

		if(ruleId != null && !ruleId.equals("")){	
			oaAttendanceRule =oaAttendanceRuleService.get(ruleId);
		}else if(companyId != null && !companyId.equals("")){
			oaAttendanceRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId); 
		}

		if(oaAttendanceRule !=null){
			oaAttendancePlace.setCompany(new Office(companyId));
			oaAttendancePlace.setPlaceName(placeName);
			oaAttendancePlace.setPlaceScope(placeScope);
			oaAttendancePlace.setLongitude(longitude);
			oaAttendancePlace.setLatitude(latitude);
			oaAttendancePlace.setOaAttendanceRule(oaAttendanceRule);
			oaAttendanceRuleService.saveOaAttendancePlace(oaAttendancePlace);
		}else if(companyId !=null  && !companyId.equals("")){
			oaAttendancePlace.setCompany(new Office(companyId));
			oaAttendancePlace.setPlaceName(placeName);
			oaAttendancePlace.setPlaceScope(placeScope);
			oaAttendancePlace.setLongitude(longitude);
			oaAttendancePlace.setLatitude(latitude);
			//oaAttendancePlace.setOaAttendanceRule(oaAttendanceRule);
			oaAttendanceRuleService.saveOaAttendancePlace(oaAttendancePlace);
		}else{
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			j.setMsg("考勤规则或公司不能为空！");
			return j;
		}
		
		j.put("data", oaAttendancePlace);
		   
		j.setMsg("保存考勤规则成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
	
	/**
	 * 删除考勤地点接口
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "deleteAttendancePlace" , method=RequestMethod.GET)
	public AjaxJson deleteAttendancePlace(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		OaAttendancePlace oaAttendancePlace  = new OaAttendancePlace();
		String placeId=request.getParameter("placeId");
		String ruleId = "";
		String companyId = "";
		if(placeId != null && !placeId.equals("")){	
			oaAttendancePlace =oaAttendanceRuleService.getOaAttendancePlace(placeId);
			if(oaAttendancePlace == null){
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_2005);
				j.setMsg("考勤地点不存在！");
				return j;
			}
			companyId = oaAttendancePlace.getCompany().getId();
			OaAttendanceRule oaAttRule = oaAttendanceRuleService.findAttendanceRuleByCompany(companyId);
			String placeIds =  "";
			String wifis =  "";
			String wifiNames =  "";
			String[] placeIdList = oaAttRule.getPlaceId().split(",");
			String[] wifiList = oaAttRule.getWifi().split(",");
			String[] wifiNameList = oaAttRule.getWifiName().split(",");
			int count = -1;
			for (int i =0 ;i<placeIdList.length;i++){
				if (placeId.equals(placeIdList[i])){
					placeIds += "-1"+",";
					count = i;
				}else {
					placeIds += placeIdList[i]+",";
				}
			}
			for (int i =0 ;i<wifiList.length;i++){
				if (i == count){
					wifis += "-1"+",";
				}else {
					wifis += wifiList[i]+",";
				}
			}
			for (int i =0 ;i<wifiNameList.length;i++){
				if (i == count){
					wifiNames += "-1"+",";
				}else {
					wifiNames += wifiNameList[i]+",";
				}
			}
			oaAttRule.setPlaceId(placeIds.substring(0,placeIds.length()-1));
			oaAttRule.setWifi(wifis.substring(0,wifis.length()-1));
			oaAttRule.setWifi(wifiNames.substring(0,wifiNames.length()-1));
			oaAttendanceRuleService.save(oaAttRule);
			//ruleId = oaAttendancePlace.getOaAttendanceRule().getId();
		}
		oaAttendanceRuleService.deletePlace(placeId);

		List<OaAttendancePlace> oaAttendancePlaceList =new ArrayList<OaAttendancePlace>();
		if(ruleId != null && !ruleId.equals("")){	
			oaAttendancePlaceList= oaAttendanceRuleService.getOaAttendancePlaceByRule(ruleId);
			j.put("data", oaAttendancePlaceList);
		}else if(companyId != null && !companyId.equals("")){
			oaAttendancePlaceList = oaAttendanceRuleService.findAttendancePlaceByCompany(companyId);
			j.put("data", oaAttendancePlaceList);
		}
		j.setMsg("删除考勤地点成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
}
