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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.SpringContextHolder;
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.sys.entity.Office;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcontent.entity.WorkContentType;
import com.jeeplus.modules.workprocesstype.entity.WorkProcessDetail;
import com.jeeplus.modules.workprocesstype.service.WorkProcessDetailService;
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.util.List;

/**
 * 过程控制类型Controller
 * @author 马鹏波
 * @version 2018-06-07
 */
@Controller
@RequestMapping(value = "${adminPath}/workprocesstype/workProcessDetail")
public class WorkProcessDetailController extends BaseController {

	private static WorkProcessDetailService workProcessDetailServices = SpringContextHolder.getBean(WorkProcessDetailService.class);
	@Autowired
	private WorkProcessDetailService workProcessDetailService;
	
	@ModelAttribute
	public WorkProcessDetail get(@RequestParam(required=false) String id) {
		WorkProcessDetail entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workProcessDetailService.get(id);
		}
		if (entity == null){
			entity = new WorkProcessDetail();
		}
		return entity;
	}
	
	/**
	 * 过程控制类型列表页面
	 */
	@RequiresPermissions("workprocesstype:workProcessDetail:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkProcessDetail workProcessDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		workProcessDetail.setCompanyId(UserUtils.getSelectCompany().getId());
		Page<WorkProcessDetail> page = workProcessDetailService.findPage(new Page<WorkProcessDetail>(request, response), workProcessDetail); 
		model.addAttribute("page", page);
		return "modules/workprocesstype/workProcessDetailList";
	}

	/**
	 * 查看，增加，编辑过程控制类型表单页面
	 */
	@RequiresPermissions(value={"workprocesstype:workProcessDetail:view","workprocesstype:workProcessDetail:add","workprocesstype:workProcessDetail:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkProcessDetail workProcessDetail, Model model) {
		model.addAttribute("workProcessDetail", workProcessDetail);
		return "modules/workprocesstype/workProcessDetailForm";
	}

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

	/**
	 * 导入Excel数据

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


	public static List<WorkProcessDetail> getContentList(){
		WorkProcessDetail workProcessDetail = new WorkProcessDetail();
		Office company = UserUtils.getSelectCompany();
		workProcessDetail.setCompanyId(company.getId());
		workProcessDetail.setDelFlag(WorkContentType.DEL_FLAG_NORMAL);
		return workProcessDetailServices.findListByState(workProcessDetail);
	}

}