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

import java.util.Date;
import java.util.List;

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

import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutineDetail;
import com.jeeplus.modules.workdailyroutine.service.WorkDailyRoutineDetailService;
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.workdailyroutine.entity.WorkDailyRoutine;
import com.jeeplus.modules.workdailyroutine.service.WorkDailyRoutineService;

/**
 * 日常事务Controller
 * @author ssrh
 * @version 2018-07-11
 */
@Controller
@RequestMapping(value = "${adminPath}/workdailyroutine/workDailyRoutine")
public class WorkDailyRoutineController extends BaseController {

	@Autowired
	private WorkDailyRoutineService workDailyRoutineService;
	@Autowired
    private WorkDailyRoutineDetailService workDailyRoutineDetailService;
	
	@ModelAttribute
	public WorkDailyRoutine get(@RequestParam(required=false) String id) {
		WorkDailyRoutine entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workDailyRoutineService.get(id);
		}
		if (entity == null){
			entity = new WorkDailyRoutine();
		}
		return entity;
	}
	
	/**
	 * 日常事务列表页面
	 */
	@RequiresPermissions("workdailyroutine:workDailyRoutine:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkDailyRoutine workDailyRoutine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkDailyRoutine> page = workDailyRoutineService.findPage(new Page<WorkDailyRoutine>(request, response), workDailyRoutine); 
		model.addAttribute("page", page);
		return "modules/workdailyroutine/workDailyRoutineList";
	}

	/**
	 * 查看，增加，编辑日常事务表单页面
	 */
	@RequiresPermissions(value={"workdailyroutine:workDailyRoutine:add","workdailyroutine:workDailyRoutine:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkDailyRoutine workDailyRoutine, Model model) {
	    if(StringUtils.isBlank(workDailyRoutine.getSource())){
	        workDailyRoutine.setSource("手工发送");
        }
	    if(StringUtils.isBlank(workDailyRoutine.getStatus())){
	        workDailyRoutine.setStatus("未完成");
        }
        if(workDailyRoutine.getCreateBy()==null){
	        workDailyRoutine.setCreateBy(UserUtils.getUser());
        }
        if(workDailyRoutine.getCreateDate()==null){
	        workDailyRoutine.setCreateDate(new Date());
        }
        if(workDailyRoutine.getOffice()==null||StringUtils.isBlank(workDailyRoutine.getOffice().getId())){
	        workDailyRoutine.setOffice(UserUtils.getSelectOffice());
        }
        if(StringUtils.isNotBlank(workDailyRoutine.getId())){
            workDailyRoutineService.queryDetails(workDailyRoutine);
        }
		model.addAttribute("workDailyRoutine", workDailyRoutine);
		return "modules/workdailyroutine/workDailyRoutineForm";
	}
	/**
	 * 查看，增加，编辑日常事务表单页面
	 */
	@RequiresPermissions(value={"workdailyroutine:workDailyRoutine:view"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkDailyRoutine workDailyRoutine, Model model) {
        if(StringUtils.isNotBlank(workDailyRoutine.getId())){
            workDailyRoutineService.queryDetails(workDailyRoutine);
        }
		model.addAttribute("workDailyRoutine", workDailyRoutine);
		return "modules/workdailyroutine/workDailyRoutineView";
	}

	/**
	 * 保存日常事务
	 */
	@RequiresPermissions(value={"workdailyroutine:workDailyRoutine:add","workdailyroutine:workDailyRoutine:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkDailyRoutine workDailyRoutine, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workDailyRoutine)){
			return form(workDailyRoutine, model);
		}
		if(!workDailyRoutine.getIsNewRecord()){//编辑表单保存
			WorkDailyRoutine t = workDailyRoutineService.get(workDailyRoutine.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workDailyRoutine, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workDailyRoutineService.save(t);//保存
		}else{//新增表单保存
			workDailyRoutineService.save(workDailyRoutine);//保存
		}
		addMessage(redirectAttributes, "保存日常事务成功");
		return "redirect:"+Global.getAdminPath()+"/workdailyroutine/workDailyRoutine/?repage";
	}

    @RequestMapping(value = "detailView")
    public String detailView(WorkDailyRoutine workDailyRoutine, Model model) {
        WorkDailyRoutineDetail workDailyRoutineDetail = workDailyRoutineDetailService.getByDailyId(workDailyRoutine.getId());
        model.addAttribute("workDailyRoutineDetail", workDailyRoutineDetail);
        return "modules/workdailyroutine/workDailyRoutineDetailView";
    }

    @RequestMapping(value = "detailForm")
    public String detailForm(WorkDailyRoutine workDailyRoutine, Model model) {
        WorkDailyRoutineDetail workDailyRoutineDetail = workDailyRoutineDetailService.getByDailyId(workDailyRoutine.getId());
        model.addAttribute("workDailyRoutineDetail", workDailyRoutineDetail);
        return "modules/workdailyroutine/workDailyRoutineDetailForm";
    }

    /**
     * 保存日常事务
     */
    @RequestMapping(value = "saveDetail")
    public String saveDetai(WorkDailyRoutineDetail workDailyRoutineDetail, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, workDailyRoutineDetail)){
            addMessage(redirectAttributes, "保存日常事务失败:"+model.asMap().get("message"));
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }
        if(!workDailyRoutineDetail.getIsNewRecord()){//编辑表单保存
            WorkDailyRoutineDetail t = workDailyRoutineDetailService.get(workDailyRoutineDetail.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(workDailyRoutineDetail, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            workDailyRoutineService.save(t);//保存
        }else{//新增表单保存
            workDailyRoutineService.save(workDailyRoutineDetail);//保存
        }
        addMessage(redirectAttributes, "保存日常事务成功");
        if (StringUtils.isNotBlank(workDailyRoutineDetail.getHome()) && "home".equals(workDailyRoutineDetail.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/workdailyroutine/workDailyRoutine/?repage";
        }
    }
	
	/**
	 * 删除日常事务
	 */
	@RequiresPermissions("workdailyroutine:workDailyRoutine:del")
	@RequestMapping(value = "delete")
	public String delete(WorkDailyRoutine workDailyRoutine, RedirectAttributes redirectAttributes) {
		workDailyRoutineService.delete(workDailyRoutine);
		addMessage(redirectAttributes, "删除日常事务成功");
		return "redirect:"+Global.getAdminPath()+"/workdailyroutine/workDailyRoutine/?repage";
	}

	/**
	 * 删除日常事务
	 */
	@RequiresPermissions("workdailyroutine:workDailyRoutine:edit")
	@RequestMapping(value = "close")
	public String close(String id, RedirectAttributes redirectAttributes) {
		workDailyRoutineService.close(id);
		addMessage(redirectAttributes, "关闭日常事务成功");
		return "redirect:"+Global.getAdminPath()+"/workdailyroutine/workDailyRoutine/?repage";
	}

	/**
	 * 批量删除日常事务
	 */
	@RequiresPermissions("workdailyroutine:workDailyRoutine:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workDailyRoutineService.delete(workDailyRoutineService.get(id));
		}
		addMessage(redirectAttributes, "删除日常事务成功");
		return "redirect:"+Global.getAdminPath()+"/workdailyroutine/workDailyRoutine/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workdailyroutine:workDailyRoutine:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkDailyRoutine workDailyRoutine, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "日常事务"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkDailyRoutine> page = workDailyRoutineService.findPage(new Page<WorkDailyRoutine>(request, response, -1), workDailyRoutine);
    		new ExportExcel("日常事务", WorkDailyRoutine.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出日常事务记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workdailyroutine/workDailyRoutine/?repage";
    }

	/**
	 * 导入Excel数据

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

}