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

import java.util.List;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcalendar.entity.CalendarCountEntity;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
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.workcalendar.entity.WorkCalendar;
import com.jeeplus.modules.workcalendar.service.WorkCalendarService;

/**
 * 工作日历Controller
 * @author ssrh
 * @version 2018-07-17
 */
@Controller
@RequestMapping(value = "${adminPath}/workcalendar/workCalendar")
public class WorkCalendarController extends BaseController {

	@Autowired
	private WorkCalendarService workCalendarService;
	
	@ModelAttribute
	public WorkCalendar get(@RequestParam(required=false) String id) {
		WorkCalendar entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workCalendarService.get(id);
		}
		if (entity == null){
			entity = new WorkCalendar();
		}
		return entity;
	}
	
	/**
	 * 工作日历列表页面
	 */
	@RequestMapping(value = {""})
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/workcalendar/workCalendarList";
	}

	/**
	 * 工作日历列表页面
	 */
	@RequestMapping(value = {"dayList"})
	public String dayList(WorkCalendar workCalendar,HttpServletRequest request, HttpServletResponse response, Model model) {
	    workCalendar.setEndDate(workCalendar.getStartDate());
        List<WorkCalendar> list = workCalendarService.findList(workCalendar);
        model.addAttribute("list",list);
        model.addAttribute("workCalendar",workCalendar);
        return "modules/workcalendar/workCalendarDayList";
	}

	/**
	 * 工作日历列表页面
	 */
	@RequestMapping(value = {"list"})
    @ResponseBody
	public AjaxJson eventlist(WorkCalendar workCalendar) {
	    AjaxJson ajaxJson = new AjaxJson();
        List<CalendarCountEntity> list = workCalendarService.findCountList(workCalendar);
        ajaxJson.getBody().put("list",list);
        return ajaxJson;
	}

	/**
	 * 查看，增加，编辑工作日历表单页面
	 */
	@RequestMapping(value = "form")
	public String form(WorkCalendar workCalendar, Model model) {
	    if(workCalendar.getCreateBy()==null){
	        workCalendar.setCreateBy(UserUtils.getUser());
        }
        if(StringUtils.isNotBlank(workCalendar.getId())){
            workCalendarService.queryDetails(workCalendar);
        }
		model.addAttribute("workCalendar", workCalendar);
		return "modules/workcalendar/workCalendarForm";
	}
	/**
	 * 查看，增加，编辑工作日历表单页面
	 */
	@RequestMapping(value = "view")
	public String view(WorkCalendar workCalendar, Model model) {
	    if(workCalendar.getCreateBy()==null){
	        workCalendar.setCreateBy(UserUtils.getUser());
        }
        if(StringUtils.isNotBlank(workCalendar.getId())){
            workCalendarService.queryDetails(workCalendar);
        }
		model.addAttribute("workCalendar", workCalendar);
		return "modules/workcalendar/workCalendarView";
	}

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

	/**
	 * 导入Excel数据

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

    @RequestMapping(value = "holidays")
    @ResponseBody
    public AjaxJson holidays(String year){
	    AjaxJson ajaxJson = new AjaxJson();
        workCalendarService.queryHoliday(year,ajaxJson);
        return ajaxJson;
    }
}