package com.jeeplus.modules.API.works.workattendancecontroller;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
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.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 com.jeeplus.modules.workattendance.entity.WorkAttendanceInfo;
import com.jeeplus.modules.workattendance.entity.WorkAttendancePlace;
import com.jeeplus.modules.workattendance.entity.WorkAttendanceRule;
import com.jeeplus.modules.workattendance.service.WorkAttendanceInfoService;
import com.jeeplus.modules.workattendance.service.WorkAttendancePlaceService;
import com.jeeplus.modules.workattendance.service.WorkAttendanceRuleService;
import com.jeeplus.modules.workfield.entity.WorkField;
import com.jeeplus.modules.workfield.service.WorkFieldService;
import com.jeeplus.modules.workout.entity.WorkOut;
import com.jeeplus.modules.workout.service.WorkOutService;
import com.jeeplus.modules.workovertime.entity.WorkOvertime;
import com.jeeplus.modules.workovertime.service.WorkOvertimeService;
import groovy.util.IFileNameFinder;
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.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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}/work/workAttendanceInfo")
public class WorkAttendanceController extends BaseController {

	@Autowired
	private WorkAttendanceInfoService workAttendanceInfoService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private WorkAttendancePlaceService workAttendancePlaceService;


	/**
	 * 考勤信息列表页面
	 */
	@ResponseBody
	@RequestMapping(value = "getAttendanceList" , method=RequestMethod.GET)
	public AjaxJson getAttendanceList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
		String userId=request.getParameter("userId");
		String pageNo=request.getParameter("pageNo");
		workAttendanceInfo.setUserId(userId);
		Page<WorkAttendanceInfo> page = workAttendanceInfoService.findPage(new Page<WorkAttendanceInfo>(request, response), workAttendanceInfo);

		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<WorkAttendanceInfo>());
		    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){
				WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
				User user = UserUtils.getUser();
				workAttendanceInfo.setUserId(user.getId());
				workAttendanceInfo.setCompanyId(UserUtils.getSelectCompany().getId());
				List<WorkAttendanceInfo> list = workAttendanceInfoService.findList(workAttendanceInfo);
				List<Map<String,Object>> mapList = Lists.newArrayList();
				int count=DateUtils.getMaxDay(Integer.parseInt(year),Integer.parseInt(month));
				for (int i = 1; i <= count; i++) {
					int counts = 0;
					List<WorkAttendanceInfo> list1 = Lists.newArrayList();
					String day = "";
					if(i<10){
						day="0"+i;
					}else{
						day=i+"";
					}
					String days = year+"-"+month+"-"+day;
					int isHoliday = workAttendanceInfoService.isHolidays(days);
					//Boolean isWeek = StringUtils.isWeek(days);
					for(WorkAttendanceInfo o : list){
						String date1 = sdf.format(o.getAttendanceDate());
						String dates[] = date1.split("-");
						int a = Integer.parseInt(dates[2]);
						if(isHoliday==0 && dates[0].equals(year) && dates[1].equals(month) && a==i && !o.getAttendanceType().equals("0") && !o.getAttendanceType().equals("4") ){
							counts ++;
						}
					}
					Map<String,Object> map = Maps.newHashMap();
                    map.put("day", days);
                    map.put("type",counts);
                    map.put("isHoliday",isHoliday);
					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) throws ParseException {
		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");
		WorkAttendanceInfo WorkAttendanceInfo = new WorkAttendanceInfo();
		if(userId!=null &&!userId.equals("")) {
			WorkAttendanceInfo.setUserId(userId);
		}else{
			WorkAttendanceInfo.setUserId(UserUtils.getUser().getId());
		}
		WorkAttendanceInfo.setCompanyId(UserUtils.getSelectCompany().getId());
		Date signDate = null;
		try {
			signDate = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		WorkAttendanceInfo.setAttendanceDate(signDate);
		List<WorkAttendanceInfo> attList = workAttendanceInfoService.findList(WorkAttendanceInfo);
		List<Map<String,Object>> maps = new ArrayList<>();
		if (attList==null){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2005);
			j.setMsg("获取考勤信息失败,当前用户无人员档案");
			j.put("data", new HashMap<>());
		}else {
			if (attList.size() != 2) {
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_2005);
				j.setMsg("获取考勤信息失败");
				j.put("data", maps);
			} else {
				int status1 = 0;
				int status2 = 0;
				int status3 = 0;
				for (WorkAttendanceInfo workAttendanceInfo : attList) {
					Map<String, Object> map = new HashMap<>();
					map.put("am", workAttendanceInfo.getMorningAfternoon());//1上午 2下午
					if (workAttendanceInfo.getType().equals("1")) {
						if (workAttendanceInfo.getAttendanceType().equals("0")) {
							status3++;
						} else if (workAttendanceInfo.getAttendanceType().equals("4")) {
							status1++;
						} else {
							status2++;
						}
						if (status1 == 2 || status2 == 2 || status3 == 2) {
							continue;
						}
					}
					map.put("type", workAttendanceInfo.getAttendanceType());//0未打卡，旷工，1内勤/2外勤/3出差/4请假/
					map.put("attendanceDate", workAttendanceInfo.getAttendanceTime() == null ? "" : sdf2.format(workAttendanceInfo.getAttendanceTime()));//打卡时间
					map.put("lateEarlyTime", workAttendanceInfo.getLateEarlyTime());//迟到/早退时长
					map.put("lateEarly", workAttendanceInfo.getLateEarly());//0正常上班 1迟到 2早退
					map.put("attendancePlace", workAttendanceInfo.getAttendancePlace());//考勤地点
					map.put("isValid", workAttendanceInfo.getIsValid());//考勤时候有效 1有效 0 无效
					map.put("isEdit", StringUtils.isBlank(workAttendanceInfo.getRemarks()) ? false : true);
					maps.add(map);
				}
				j.setSuccess(true);
				j.setErrorCode(ErrorCode.code_1004);
				j.setMsg("获取考勤信息成功");
				j.put("data", maps);
			}
		}
		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) throws ParseException {
		AjaxJson j=new AjaxJson();
		WorkAttendanceInfo workAttendanceInfo = new WorkAttendanceInfo();
		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("")) {
			workAttendanceInfo.setUserId(userId);
		}else{

			workAttendanceInfo.setUserId(UserUtils.getUser().getId());
		}
		workAttendanceInfo.setCompanyId(UserUtils.getSelectCompany().getId());
		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();
		}
		workAttendanceInfo.setAttendanceDate(signDate);
		List<WorkAttendanceInfo> attList = workAttendanceInfoService.findListInfo(workAttendanceInfo);
		if (attList==null){
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2005);
			j.setMsg("获取考勤信息失败,当前用户无人员档案");
			j.put("data", new HashMap<>());
		}else {
			if (attList.size() < 2) {
				attList = workAttendanceInfoService.findList(workAttendanceInfo);
			}
			List<Map<String, Object>> maps = new ArrayList<>();
			if (attList.size() != 2) {
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_2005);
				j.setMsg("获取考勤信息失败");
				j.put("data", maps);
			} else {
				int count1 = 0;
				int count2 = 0;
				int countLeave1 = 0;
				int countLeave2 = 0;
				int status = 0;
				int status1 = 0;
				int c = 1;
				for (WorkAttendanceInfo attendanceInfo : attList) {
					Map<String, Object> map = new HashMap<>();
					if (attendanceInfo.getType().equals("1")) {
						if (attendanceInfo.getAttendanceType().equals("4")) {
							status1++;
						} else if (attendanceInfo.getAttendanceType().equals("0")) {
							c = 0;
						} else {
							status++;
						}
						if (status1 == 2 || status == 2) {
							if (status1 == 2) {
								c = 0;
							}
							continue;
						}
					} else {
						if (attendanceInfo.getType().equals("2")) {
							if (!attendanceInfo.getAttendanceType().equals("0") && !attendanceInfo.getAttendanceType().equals("4")) {
								status++;
							}
							if (status == 2) {
								count1 = 1;
								count2 = 1;
							}
						}
						if (!attendanceInfo.getAttendanceType().equals("0")) {
							if (attendanceInfo.getAttendanceType().equals("4")) {
								if (attendanceInfo.getMorningAfternoon().equals("1")) {
									countLeave1 = 1;
								} else {
									countLeave2 = 1;
								}
							} else {
								if (attendanceInfo.getType().equals("2")) {
									if (attendanceInfo.getMorningAfternoon().equals("1")) {
										count1 = 1;
									} else {
										count2 = 1;
									}
								}
							}
						}
					}
					map.put("type", attendanceInfo.getAttendanceType());//0未打卡，旷工，1内勤/2外勤/3出差/4请假/
					map.put("am", attendanceInfo.getMorningAfternoon());//1上午 2下午
					map.put("attendanceDate", attendanceInfo.getAttendanceTime() == null ? "" : sdf2.format(attendanceInfo.getAttendanceTime()));//打卡时间
					map.put("lateEarly", attendanceInfo.getLateEarly());//0正常上班 1迟到 2早退
					map.put("lateEarlyTime", attendanceInfo.getLateEarlyTime());//迟到/早退时长
					map.put("attendancePlace", attendanceInfo.getAttendancePlace());//考勤地点
					map.put("isValid", attendanceInfo.getIsValid());//考勤时候有效 1有效 0 无效
					maps.add(map);

				}
				j.setSuccess(true);
				j.setErrorCode(ErrorCode.code_1004);
				j.setMsg("获取考勤信息成功");
				j.put("data", maps);
				if (c == 1) {
					if (countLeave1 == 1) {
						if (countLeave2 == 1) {
							j.put("count", 0);
						} else {
							j.put("count", 2);
						}
					} else {
						if (countLeave2 == 1) {
							j.put("count", 1);
						} else {
							if (count1 == 1) {
								if (count2 == 1) {
									j.put("count", 0);
								} else {
									j.put("count", 2);
								}
							} else {
								j.put("count", 1);
							}
						}
					}
				} else {
					j.put("count", 0);
				}
			}
		}
		return j;
	}
	
	/**
	 * 打卡接口
	 */
	@ResponseBody
	@RequestMapping(value = "addPunchCard" , method=RequestMethod.GET)
	public AjaxJson addPunchCard(HttpServletRequest request, HttpServletResponse response) throws ParseException {
		AjaxJson j=new AjaxJson();
		WorkAttendanceInfo WorkAttendanceInfo = new WorkAttendanceInfo();
		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");
		String palce = request.getParameter("palce");
		String ruleType = request.getParameter("ruleType");
		String type = request.getParameter("type");
		if(!type.equals("1") && !type.equals("2")){
			j.setMsg("考勤类型异常");
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			return j;
		}
		User user = UserUtils.getUser();
		logger.info("http://localhost:8080/f/work/workAttendanceInfo/addPunchCard?userId="+userId+"&companyId="+companyId+"&ruleId="+ruleId+"&lnt="+lnt+"&lat="+lat+"&wifi="+wifi+"&cardType"+cardType+"&ruleType="+ruleType);
		workAttendanceInfoService.addPunchCard(user,lnt,lat,wifi,cardType,ruleType,type,palce,j);
		return j;
	}

	/**
	 * 打卡接口
	 */
	@ResponseBody
	@RequestMapping(value = "updatePunchCard" , method=RequestMethod.GET)
	public AjaxJson updatePunchCard(HttpServletRequest request, HttpServletResponse response) throws ParseException {
		AjaxJson j=new AjaxJson();
		WorkAttendanceInfo WorkAttendanceInfo = new WorkAttendanceInfo();
		String userId = request.getParameter("userId");
		String companyId = request.getParameter("companyId");
		if(Strings.isNullOrEmpty(companyId)){
			companyId = UserUtils.getSelectCompany().getId();
		}
		String lnt = request.getParameter("lnt");
		String ruleId = request.getParameter("ruleId");
		String lat = request.getParameter("lat");
		String wifi=request.getParameter("wifi");
		String cardType = request.getParameter("cardType");
		String palce = request.getParameter("palce");
		String ruleType = request.getParameter("ruleType");
		String type = request.getParameter("type");
		User user = UserUtils.getUser();
		if(!type.equals("1") && !type.equals("2")){
			j.setMsg("考勤类型异常");
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			return j;
		}
		logger.info("http://localhost:8080/f/work/workAttendanceInfo/updatePunchCard?userId="+userId+"&companyId="+companyId+"&ruleId="+ruleId+"&lnt="+lnt+"&lat="+lat+"&wifi="+wifi+"&cardType"+cardType+"&ruleType="+ruleType);
		workAttendanceInfoService.updatePunchCard(user,lnt,lat,wifi,cardType,ruleType,type,palce,j);
		return j;
	}

	/**
	 * 补卡接口
	 */
	@ResponseBody
	@RequestMapping(value = "addPunchCardAudit" , method=RequestMethod.GET)
	public AjaxJson addPunchCardAudit(HttpServletRequest request, HttpServletResponse response) throws ParseException {
		AjaxJson j=new AjaxJson();
		/*String companyId = request.getParameter("companyId");
		if(Strings.isNullOrEmpty(companyId)){
			companyId = UserUtils.getSelectCompany().getId();
		}
		String ruleId = request.getParameter("ruleId");*/
		String cardType = request.getParameter("cardType");
		String ruleType = request.getParameter("ruleType");
		String addendanceDate = request.getParameter("addendanceDate");
		//String dateTime = request.getParameter("dateTime");
		String reason = request.getParameter("reason");
		User user = UserUtils.getUser();
		if(!cardType.equals("1") && !cardType.equals("2") && !cardType.equals("3")){
			j.setMsg("考勤类型异常");
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			return j;
		}
		logger.info("http://localhost:8080/f/work/workAttendanceInfo/addPunchCardAudit?reason="+reason+"&addendanceDate="+addendanceDate+"&cardType"+cardType+"&ruleType="+ruleType);
		workAttendanceInfoService.addPunchCardAudit(user,cardType,ruleType,addendanceDate,reason,j);
		return j;
	}

	/**
	 * 获取考勤规则接口
	 */
	@ResponseBody
	@RequestMapping(value = "getCompanyRule" , method=RequestMethod.GET)
	public AjaxJson getCompanyRule(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j=new AjaxJson();
		WorkAttendanceInfo WorkAttendanceInfo = new WorkAttendanceInfo();
		String ruleId = request.getParameter("ruleId");
		String companyId = UserUtils.getSelectCompany().getId();
        User user = UserUtils.getUser();
        String officeId = UserUtils.getSelectOffice().getId();
        WorkAttendanceRule workAttendanceRule = workAttendanceInfoService.findAttendanceRuleByCompany(companyId,ruleId,officeId,user);
		if(workAttendanceRule==null || StringUtils.isBlank(workAttendanceRule.getId())){
			j.put("data", new WorkAttendanceRule());
		    j.setMsg("当前账号无考勤规则");
		    j.setErrorCode(ErrorCode.code_1004);
		}else{
		    j.put("data", workAttendanceRule);
		    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 {
            WorkAttendanceRule WorkAttendanceRule = new WorkAttendanceRule();
            WorkAttendanceRule 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("")) {
                WorkAttendanceRule = WorkAttendanceRuleService.get(ruleId);
            } else if (companyId != null && !companyId.equals("")) {
                oaAttRule = WorkAttendanceRuleService.findAttendanceRuleByCompany(companyId);
            } else {
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2006);
                j.setMsg("保存考勤规则失败！");
                return j;
            }
            if (oaAttRule != null) {
                WorkAttendanceRule = oaAttRule;
            }
            WorkAttendanceRule.setCompany(new Office(companyId));
            WorkAttendanceRule.setStartTime(startTime);
            WorkAttendanceRule.setEndTime(endTime);
            WorkAttendanceRule.setWorkdays(workdays);
            WorkAttendanceRule.setWifi(wifi);
            WorkAttendanceRule.setWifiName(wifiName);
            WorkAttendanceRule.setPlaceId(placeId);
            WorkAttendanceRule.setIsNewRecord(false);
            WorkAttendanceRuleService.save(WorkAttendanceRule);
            j.put("data", WorkAttendanceRule);
            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();
		WorkAttendanceRule WorkAttendanceRule = new WorkAttendanceRule();
		String ruleId=request.getParameter("ruleId");
		
		/*String companyId=request.getParameter("companyId");
		if(ruleId != null && !ruleId.equals("")){
			WorkAttendanceRule =WorkAttendanceRuleService.get(ruleId);
		}else if(companyId != null && !companyId.equals("")){
			WorkAttendanceRule = WorkAttendanceRuleService.findAttendanceRuleByCompany(companyId); 
		}
		WorkAttendanceRuleService.delete(WorkAttendanceRule);*/
		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();
		WorkAttendanceRule WorkAttendanceRule = null;
		String ruleId=request.getParameter("ruleId");
		
		/*String companyId=request.getParameter("companyId");
        companyId = UserUtils.getSelectCompany().getId();
		List<WorkAttendancePlace> WorkAttendancePlaceList =new ArrayList<WorkAttendancePlace>();
		if(ruleId != null && !ruleId.equals("")){	
			WorkAttendanceRule =WorkAttendanceRuleService.get(ruleId);
		}else if(companyId != null && !companyId.equals("")){
			WorkAttendanceRule = WorkAttendanceRuleService.findAttendanceRuleByCompany(companyId); 
		}
		if(WorkAttendanceRule==null){
//			j.setSuccess(false);
//			j.setErrorCode("-1");
//			j.setMsg("考勤规则不存在");
		}
		WorkAttendancePlaceList = WorkAttendanceRuleService.findAttendancePlaceByCompany(companyId);

		j.put("data", WorkAttendancePlaceList);*/
		   
		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();
		WorkAttendanceRule WorkAttendanceRule = null;
		WorkAttendancePlace WorkAttendancePlace = new WorkAttendancePlace();
		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("")){	
			WorkAttendancePlace =WorkAttendanceRuleService.getWorkAttendancePlace(placeId);
		}

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

		if(WorkAttendanceRule !=null){
			WorkAttendancePlace.setCompany(new Office(companyId));
			WorkAttendancePlace.setPlaceName(placeName);
			WorkAttendancePlace.setPlaceScope(placeScope);
			WorkAttendancePlace.setLongitude(longitude);
			WorkAttendancePlace.setLatitude(latitude);
			WorkAttendancePlace.setWorkAttendanceRule(WorkAttendanceRule);
			WorkAttendanceRuleService.saveWorkAttendancePlace(WorkAttendancePlace);
		}else if(companyId !=null  && !companyId.equals("")){
			WorkAttendancePlace.setCompany(new Office(companyId));
			WorkAttendancePlace.setPlaceName(placeName);
			WorkAttendancePlace.setPlaceScope(placeScope);
			WorkAttendancePlace.setLongitude(longitude);
			WorkAttendancePlace.setLatitude(latitude);
			//WorkAttendancePlace.setWorkAttendanceRule(WorkAttendanceRule);
			WorkAttendanceRuleService.saveWorkAttendancePlace(WorkAttendancePlace);
		}else{
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2003);
			j.setMsg("考勤规则或公司不能为空！");
			return j;
		}*/
		
		j.put("data", WorkAttendancePlace);
		   
		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();
		WorkAttendancePlace WorkAttendancePlace  = new WorkAttendancePlace();
		String placeId = request.getParameter("placeId");
		String ruleId = "";
		String companyId = "";
		/*if(placeId != null && !placeId.equals("")){
			WorkAttendancePlace =WorkAttendanceRuleService.getWorkAttendancePlace(placeId);
			if(WorkAttendancePlace == null){
				j.setSuccess(false);
				j.setErrorCode(ErrorCode.code_2005);
				j.setMsg("考勤地点不存在！");
				return j;
			}
			companyId = WorkAttendancePlace.getCompany().getId();
			WorkAttendanceRule oaAttRule = WorkAttendanceRuleService.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));
			WorkAttendanceRuleService.save(oaAttRule);
			//ruleId = WorkAttendancePlace.getWorkAttendanceRule().getId();
		}
		WorkAttendanceRuleService.deletePlace(placeId);

		List<WorkAttendancePlace> WorkAttendancePlaceList =new ArrayList<WorkAttendancePlace>();
		if(ruleId != null && !ruleId.equals("")){	
			WorkAttendancePlaceList= WorkAttendanceRuleService.getWorkAttendancePlaceByRule(ruleId);
			j.put("data", WorkAttendancePlaceList);
		}else if(companyId != null && !companyId.equals("")){
			WorkAttendancePlaceList = WorkAttendanceRuleService.findAttendancePlaceByCompany(companyId);
			j.put("data", WorkAttendancePlaceList);
		}*/
		j.setMsg("删除考勤地点成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
}
