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

import java.util.List;

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

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.sys.entity.SysRoleActivity;
import com.jeeplus.modules.sys.service.SysRoleActivityService;

/**
 * 工作流角色信息Controller
 * @author 杨帆
 * @version 2018-04-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/sysroleactivity")
public class SysRoleActivityController extends BaseController {

	@Autowired
	private SysRoleActivityService sysRoleActivityService;
	
	@ModelAttribute
	public SysRoleActivity get(@RequestParam(required=false) String id) {
		SysRoleActivity entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysRoleActivityService.get(id);
		}
		if (entity == null){
			entity = new SysRoleActivity();
		}
		return entity;
	}
	
	/**
	 * 工作流角色信息列表页面
	 */
	@RequiresPermissions("sys:sysroleactivity:list")
	@RequestMapping(value = {"list", ""})
	public String list(SysRoleActivity sysRoleActivity, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysRoleActivity> page = sysRoleActivityService.findPage(new Page<SysRoleActivity>(request, response), sysRoleActivity);
		model.addAttribute("page", page);
		return "modules/sys/sysroleactivityList";
	}

	/**
	 * 查看，增加，编辑工作流角色信息表单页面
	 */
	@RequiresPermissions(value={"sys:sysroleactivity:view","sys:sysroleactivity:add","sys:sysroleactivity:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(SysRoleActivity sysRoleActivity, Model model, HttpServletRequest request) {
		model.addAttribute("sysroleactivity", sysRoleActivity);
		String view = request.getParameter("view");
		if (!StringUtils.isBlank(view)) {
			return "modules/sys/sysroleactivityView";
		}
		return "modules/sys/sysroleactivityForm";
	}

	/**
	 * 保存工作流角色信息
	 */
	@RequiresPermissions(value={"sys:sysroleactivity:add","sys:sysroleactivity:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(SysRoleActivity sysRoleActivity, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception{
		if (!beanValidator(model, sysRoleActivity)){
			return form(sysRoleActivity, model,request);
		}
		if(!sysRoleActivity.getIsNewRecord()){//编辑表单保存
			SysRoleActivity t = sysRoleActivityService.get(sysRoleActivity.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(sysRoleActivity, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			sysRoleActivityService.save(t);//保存
		}else{//新增表单保存
			sysRoleActivityService.save(sysRoleActivity);//保存
		}
		addMessage(redirectAttributes, "保存工作流角色信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/sysroleactivity/?repage";
	}
	
	/**
	 * 删除工作流角色信息
	 */
	@RequiresPermissions("sys:sysroleactivity:del")
	@RequestMapping(value = "delete")
	public String delete(SysRoleActivity sysRoleActivity1, RedirectAttributes redirectAttributes) {
        SysRoleActivity sysRoleActivity = sysRoleActivityService.get(sysRoleActivity1.getId());
        if (!"1".equals(sysRoleActivity.getDelType()) ){
            String count = sysRoleActivityService.isSysRoleActivityRelation(sysRoleActivity);
            if ("0".equals(count)){
                sysRoleActivityService.delete(sysRoleActivity);
                addMessage(redirectAttributes, "删除工作流角色信息成功");
            }else {
                addMessage(redirectAttributes, "该角色为默认角色或存在管理岗位数据不允许删除");
            }
        }
		return "redirect:"+Global.getAdminPath()+"/sys/sysroleactivity/?repage";
	}
	
	/**
	 * 批量删除工作流角色信息
	 */
	@RequiresPermissions("sys:sysroleactivity:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		int count1 = 0;
		int count2 = 0;
		for(String id : idArray){
			SysRoleActivity sysRoleActivity = sysRoleActivityService.get(id);
			if (!"1".equals(sysRoleActivity.getDelType()) ){
				String count = sysRoleActivityService.isSysRoleActivityRelation(sysRoleActivity);
				if ("0".equals(count)){
					sysRoleActivityService.delete(sysRoleActivity);
					count1 ++;
				}else {
					count2 ++;
				}
			}else {
				count2 ++;
			}
		}
		addMessage(redirectAttributes, "删除工作流角色信息成功"+count1+"条,未成功"+count2+"条,默认角色/存在管理岗位数据不允许删除");
		return "redirect:"+Global.getAdminPath()+"/sys/sysroleactivity/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("sys:sysroleactivity:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(SysRoleActivity sysRoleActivity, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工作流角色信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<SysRoleActivity> page = sysRoleActivityService.findPage(new Page<SysRoleActivity>(request, response, -1), sysRoleActivity);
    		new ExportExcel("工作流角色信息", SysRoleActivity.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工作流角色信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/sysroleactivity/?repage";
    }

	/**
	 * 导入Excel数据

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

}