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

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.workborrowmangement.entity.WorkBorrowMangement;
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.workborrowmangement.entity.WorkBorrowBack;
import com.jeeplus.modules.workborrowmangement.service.WorkBorrowBackService;

/**
 * 归还Controller
 * @author chenyuping
 * @version 2018-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/workborrowmangement/workBorrowBack")
public class WorkBorrowBackController extends BaseController {

	@Autowired
	private WorkBorrowBackService workBorrowBackService;
	
	@ModelAttribute
	public WorkBorrowBack get(@RequestParam(required=false) String id) {
		WorkBorrowBack entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workBorrowBackService.get(id);
		}
		if (entity == null){
			entity = new WorkBorrowBack();
		}
		return entity;
	}
	
	/**
	 * 归还借用列表页面
	 */
	@RequiresPermissions("workborrowmangement:workBorrowBack:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBorrowBack workBorrowBack, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkBorrowBack> page = workBorrowBackService.findPage(new Page<WorkBorrowBack>(request, response), workBorrowBack); 
		model.addAttribute("page", page);
		return "modules/workborrowmangement/workBorrowBackList";
	}

	/**
	 * 查看，增加，编辑归还借用表单页面
	 */
	@RequiresPermissions(value={"workborrowmangement:workBorrowBack:view","workborrowmangement:workBorrowBack:add","workborrowmangement:workBorrowBack:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBorrowBack workBorrowBack, Model model) {
		model.addAttribute("workBorrowBack", workBorrowBack);
		return "modules/workborrowmangement/workBorrowBackForm";
	}

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

	/**
	 * 导入Excel数据

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


	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkBorrowBack workBorrowBack, Model model,
							RedirectAttributes redirectAttributes) {
		String str = workBorrowBackService.auditSave(workBorrowBack);
		addMessage(redirectAttributes, str);
		if (StringUtils.isNotBlank(workBorrowBack.getHome()) && "home".equals(workBorrowBack.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:" + Global.getAdminPath() + "/workborrowmangement/workBorrowMangement/?repage";
		}
	}

}