/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.oa.web;

import com.google.common.collect.Lists;
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.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.oa.entity.OaAttendance;
import com.jeeplus.modules.oa.entity.OaAttendanceRule;
import com.jeeplus.modules.oa.service.OaAttendanceRuleService;
import com.jeeplus.modules.oa.service.OaAttendanceService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 考勤表Controller
 * @author 孟祥越
 * @version 2017-05-11
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/oaAttendance")
public class OaAttendanceController extends BaseController {

	@Autowired
	private OaAttendanceService oaAttendanceService;

	@Autowired
	private OaAttendanceRuleService oaAttendanceRuleService;

	@ModelAttribute
	public OaAttendance get(@RequestParam(required=false) String id) {
		OaAttendance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = oaAttendanceService.get(id);
		}
		if (entity == null){
			entity = new OaAttendance();
		}
		return entity;
	}
	
	/**
	 * 考勤信息列表页面
	 */
	@RequiresPermissions("oa:oaAttendance:list")
	@RequestMapping(value = {"list", ""})
	public String list(OaAttendance oaAttendance, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		String username = request.getParameter("user.name");
		String fromDate = request.getParameter("fromThisDay");
		String toDate = request.getParameter("toThisDay");
		if(! user.isAdmin()){
			oaAttendance.setCompany(UserUtils.getSelectCompany());
			if(! UserUtils.isManager()){
				oaAttendance.setUser(user);
			}
		}else{

		}
		Page<OaAttendance> page = oaAttendanceService.findPage(new Page<OaAttendance>(request,response),oaAttendance);

		String userId = user.getId();
		AjaxJson j=new AjaxJson();
		if(userId!=null &&!userId.equals("")) {
			oaAttendance.setUser(new User(userId));
		}else{
			oaAttendance.setUser(UserUtils.getUser());
		}
		oaAttendance.setCompany(UserUtils.getSelectCompany());
		SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

		for(OaAttendance attendance : page.getList()) {
			List<OaAttendance> oaAttList = oaAttendanceService.findList(attendance);
			if(oaAttList==null ){
				j.setSuccess(false);
				j.setErrorCode("1");
				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) {
					j.setSuccess(false);
					j.setErrorCode("1");
					j.setMsg("获取考勤信息失败");
					//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待打卡

				if(startTime!=null && endTime!=null){
					if(startTime.getTime()<=startRule.getTime()){
						attendance.setMorning("1");
					}else{
						attendance.setMorning("2");
					}
					if(endTime.getTime()>=endRule.getTime() && c3.compareTo(c1)<0){
						attendance.setAfternoon("1");
					}else if(endTime.getTime()<endRule.getTime()){
						attendance.setAfternoon("3");
					}else{
						attendance.setAfternoon("3");
					}
				}else if(startTime==null && endTime!=null){
					if(endTime.getTime()>=endRule.getTime() && c3.compareTo(c1)<0){
						attendance.setAfternoon("1");
						attendance.setMorning("5");
					}else if(endTime.getTime()<endRule.getTime()){
						attendance.setAfternoon("3");
						attendance.setMorning("5");
					}else{
						attendance.setAfternoon("3");
						attendance.setMorning("5");
					}
				}else if(startTime!=null && endTime==null){
					if(startTime.getTime()<=startRule.getTime()){
						attendance.setMorning("1");
						attendance.setAfternoon("5");
					}else{
						attendance.setMorning("2");
						attendance.setAfternoon("5");
					}
				}
			}else {
				attendance.setMorning("5");
				attendance.setAfternoon("5");
				j.setMsg("获取当日考勤成功");
			}
		}
		try {
			if(StringUtils.isNotBlank(fromDate)){
				Date fromThisDay =  new SimpleDateFormat("yyyy-MM-dd").parse(fromDate);
				model.addAttribute("fromThisDay",fromThisDay);
			}
			if(StringUtils.isNotBlank(toDate)){
				Date toThisDay = new SimpleDateFormat("yyyy-MM-dd").parse(toDate);
				model.addAttribute("toThisDay",toThisDay);
			}
		}catch (ParseException e){
			e.printStackTrace();
		}
		model.addAttribute("username",username);
		model.addAttribute("page", page);
		return "modules/oa/oaAttendanceList";
	}

	/**
	 * 查看，增加，编辑考勤信息表单页面
	 */
	@RequiresPermissions(value={"oa:oaAttendance:view","oa:oaAttendance:add","oa:oaAttendance:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(@RequestParam(value = "readAttr",required = false)String readAttr,OaAttendance oaAttendance, Model model) {
		model.addAttribute("oaAttendance", oaAttendance);
		model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
		return "modules/oa/oaAttendanceForm";
	}

	/**
	 * 保存考勤信息
	 */
	@RequiresPermissions(value={"oa:oaAttendance:add","oa:oaAttendance:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(OaAttendance oaAttendance, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, oaAttendance)){
			return form("",oaAttendance, model);
		}
		if(!oaAttendance.getIsNewRecord()){//编辑表单保存
			OaAttendance t = oaAttendanceService.get(oaAttendance.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(oaAttendance, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			oaAttendanceService.save(t);//保存
		}else{//新增表单保存
			oaAttendance.setOfficeId(UserUtils.getSelectOffice().getId());
			oaAttendanceService.save(oaAttendance);//保存
		}
		addMessage(redirectAttributes, "保存考勤信息成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
	}
	
	/**
	 * 删除考勤信息
	 */
	@RequiresPermissions("oa:oaAttendance:del")
	@RequestMapping(value = "delete")
	public String delete(OaAttendance oaAttendance, RedirectAttributes redirectAttributes) {
		oaAttendanceService.delete(oaAttendance);
		addMessage(redirectAttributes, "删除考勤信息成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
	}
	
	/**
	 * 批量删除考勤信息
	 */
	@RequiresPermissions("oa:oaAttendance:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			oaAttendanceService.delete(oaAttendanceService.get(id));
		}
		addMessage(redirectAttributes, "删除考勤信息成功");
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("oa:oaAttendance:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(OaAttendance oaAttendance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			User user = UserUtils.getUser();
			if(! user.isAdmin()){
				oaAttendance.setCompany(UserUtils.getSelectCompany());
				if(! UserUtils.isManager()){
					oaAttendance.setUser(user);
				}
			}else{

			}

            String fileName = "考勤信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<OaAttendance> page = oaAttendanceService.findPage(new Page<OaAttendance>(request, response, -1), oaAttendance);
    		new ExportExcel("考勤信息", OaAttendance.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("oa:oaAttendance:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<OaAttendance> list = ei.getDataList(OaAttendance.class);
			for (OaAttendance oaAttendance : list){
				try{
					oaAttendanceService.save(oaAttendance);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条考勤信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条考勤信息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入考勤信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
    }
	
	/**
	 * 下载导入考勤信息数据模板
	 */
	@RequiresPermissions("oa:oaAttendance:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "考勤信息数据导入模板.xlsx";
    		List<OaAttendance> list = Lists.newArrayList(); 
    		new ExportExcel("考勤信息数据", OaAttendance.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oa/oaAttendance/?repage";
    }
	
	
	/**
	 * 选择考勤规则
	 */
	@RequestMapping(value = "selectrule")
	public String selectrule(OaAttendanceRule rule, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<OaAttendanceRule> page = oaAttendanceService.findPageByrule(new Page<OaAttendanceRule>(request, response),  rule);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", rule);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	

}