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

import java.lang.ref.ReferenceQueue;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.oa.entity.OaAttendance;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.poi.util.StringUtil;
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 com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workoutsignin.entity.WorkOutSignIn;
import com.jeeplus.modules.workoutsignin.service.WorkOutSignInService;

/**
 * 外勤签到Controller
 * @author 李韵轩
 * @version 2017-04-20
 */
@Controller
@RequestMapping(value = "${adminPath}/workoutsignin/workOutSignIn")
public class WorkOutSignInController extends BaseController {

	@Autowired
	private WorkOutSignInService workOutSignInService;
	@Autowired
	private SystemService systemService;
	@ModelAttribute
	public WorkOutSignIn get(@RequestParam(required=false) String id) {
		WorkOutSignIn entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOutSignInService.get(id);
		}
		if (entity == null){
			entity = new WorkOutSignIn();
		}
		return entity;
	}

	/**
	 * 签到列表页面--管理员查看本公司所有，普通用户只能查看自己的外勤签到记录
	 */
	@RequiresPermissions("workoutsignin:workOutSignIn:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkOutSignIn workOutSignIn, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		String username = request.getParameter("username");
		Page<WorkOutSignIn> page = null ;
		if(!user.isAdmin()){
			workOutSignIn.setCompanyId(user.getComId());
			if(UserUtils.isManager()){
				if(!StringUtils.isBlank(username)){
					User u = new User();
					u.setName(username);
					workOutSignIn.setUser(u);
				}
				page = workOutSignInService.findPage(new Page<WorkOutSignIn>(request,response),workOutSignIn);
			}else{
				workOutSignIn.setUser(user);
				if(!StringUtils.isBlank(username)){
					User u = new User();
					u.setId(user.getId());
					u.setName(username);
					workOutSignIn.setUser(u);
				}
				page = workOutSignInService.findPageByUser(new Page<WorkOutSignIn>(request,response),workOutSignIn);
			}
		}else{
			if(!StringUtils.isBlank(username)){
				User u = new User();
				u.setName(username);
				workOutSignIn.setUser(u);
			}
			page = workOutSignInService.findPage(new Page<WorkOutSignIn>(request,response),workOutSignIn);
		}
		model.addAttribute("username", username);
		model.addAttribute("page", page);
		return "modules/workoutsignin/workOutSignInList";
	}

	/**
	 * 查看，增加，编辑签到表单页面
	 */
	@RequiresPermissions(value={"workoutsignin:workOutSignIn:view","workoutsignin:workOutSignIn:add","workoutsignin:workOutSignIn:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(@RequestParam(value = "readAttr",required = false)String readAttr,WorkOutSignIn workOutSignIn, Model model) {
		model.addAttribute("workOutSignIn", workOutSignIn);
		model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
		return "modules/workoutsignin/workOutSignInForm";
	}

	/**
	 * 保存签到
	 */
	@RequiresPermissions(value={"workoutsignin:workOutSignIn:add","workoutsignin:workOutSignIn:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkOutSignIn workOutSignIn, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workOutSignIn)){
			return form("",workOutSignIn, model);
		}
		if(!workOutSignIn.getIsNewRecord()){//编辑表单保存
			WorkOutSignIn t = workOutSignInService.get(workOutSignIn.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workOutSignIn, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workOutSignInService.save(t);//保存
		}else{//新增表单保存
			workOutSignInService.save(workOutSignIn);//保存
		}
		addMessage(redirectAttributes, "保存签到成功");
		return "redirect:"+Global.getAdminPath()+"/workoutsignin/workOutSignIn/?repage";
	}
	
	/**
	 * 删除签到
	 */
	@RequiresPermissions("workoutsignin:workOutSignIn:del")
	@RequestMapping(value = "delete")
	public String delete(WorkOutSignIn workOutSignIn, RedirectAttributes redirectAttributes) {
		workOutSignInService.delete(workOutSignIn);
		addMessage(redirectAttributes, "删除签到成功");
		return "redirect:"+Global.getAdminPath()+"/workoutsignin/workOutSignIn/?repage";
	}
	
	/**
	 * 批量删除签到
	 */
	@RequiresPermissions("workoutsignin:workOutSignIn:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workOutSignInService.delete(workOutSignInService.get(id));
		}
		addMessage(redirectAttributes, "删除签到成功");
		return "redirect:"+Global.getAdminPath()+"/workoutsignin/workOutSignIn/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workoutsignin:workOutSignIn:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkOutSignIn workOutSignIn, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "签到"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkOutSignIn> page = workOutSignInService.findPage(new Page<WorkOutSignIn>(request, response, -1), workOutSignIn);
    		new ExportExcel("签到", WorkOutSignIn.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出签到记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workoutsignin/workOutSignIn/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workoutsignin:workOutSignIn: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<WorkOutSignIn> list = ei.getDataList(WorkOutSignIn.class);
			for (WorkOutSignIn workOutSignIn : list){
				try{
					workOutSignInService.save(workOutSignIn);
					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()+"/workoutsignin/workOutSignIn/?repage";
    }
	
	/**
	 * 下载导入签到数据模板
	 */
	@RequiresPermissions("workoutsignin:workOutSignIn:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "签到数据导入模板.xlsx";
    		List<WorkOutSignIn> list = Lists.newArrayList(); 
    		new ExportExcel("签到数据", WorkOutSignIn.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workoutsignin/workOutSignIn/?repage";
    }
	
	
	

}