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

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

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

import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.service.DictService;
import com.jeeplus.modules.sys.service.MainDictService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmodular.entity.SysModularField;
import com.jeeplus.modules.sysmodular.service.SysModularFieldService;
import com.jeeplus.modules.workchangejob.entity.WorkChangeJobUser;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
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.sysmodular.entity.SysModular;
import com.jeeplus.modules.sysmodular.service.SysModularService;

/**
 * 业务模块Controller
 * @author ssrh
 * @version 2018-08-17
 */
@Controller
@RequestMapping(value = "${adminPath}/sysmodular/sysModular")
public class SysModularController extends BaseController {

	@Autowired
	private MainDictService mainDictService;
	@Autowired
	private DictService dictService;
	@Autowired
	private SysModularService sysModularService;
	@Autowired
	private SysModularFieldService sysModularFieldService;
	@Autowired
	private HttpServletRequest request;

	@ModelAttribute
	public SysModular get(@RequestParam(required=false) String id) {
		SysModular entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysModularService.get(id);
		}
		if (entity == null){
			entity = new SysModular();
		}
		return entity;
	}
	
	/**
	 * 业务模块列表页面
	 */
	//@RequiresPermissions("sysmodular:sysModular:list")
	@RequestMapping(value = {"list", ""})
	public String list(SysModular sysModular, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysModular> page = sysModularService.findPage(new Page<SysModular>(request, response), sysModular); 
		model.addAttribute("page", page);
		return "modules/sysmodular/sysModularList";
	}

	/**
	 * 查看，增加，编辑业务模块表单页面
	 */
	@RequiresPermissions(value={"sysmodular:sysModular:view","sysmodular:sysModular:add","sysmodular:sysModular:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(SysModular sysModular, Model model) {
		String tabId = request.getParameter("tabId");
			List tableList=sysModularService.findTable(Global.getDbName());
			model.addAttribute("tableList", tableList);
			model.addAttribute("sysModular", sysModular);
			return "modules/sysmodular/sysModularFormAdd";

	}

	@RequestMapping(value = "formColumn")
	public String formColumn(SysModular sysModular, Model model) {
		String tabId = request.getParameter("tabId");
		SysModularField sysModularField=new SysModularField();
		sysModularField.setModularId(sysModular.getId());
		List<SysModularField> sysModularFieldList=sysModularFieldService.findList(sysModularField);
		sysModular.setSysModularFieldList(sysModularFieldList);
		model.addAttribute("sysModular", sysModular);
		if("1".equals(tabId)){
			List<String> dictList = dictService.findTypeList();
			List<String> mainDictList = mainDictService.findTypeList();
			dictList.addAll(mainDictList);
			HashSet set = new HashSet(dictList);
			dictList.clear();
			dictList.addAll(set);
			model.addAttribute("dictList", dictList);
			return "modules/sysmodular/sysModularForm";
		}else{
			return "modules/sysmodular/sysModularFormView";
		}
	}

	/**
	 * 保存业务模块
	 */
	@RequiresPermissions(value={"sysmodular:sysModular:add","sysmodular:sysModular:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(SysModular sysModular, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, sysModular)){
			return form(sysModular, model);
		}
		//校验模块是否存在
		List<SysModular> s=sysModularService.findByTableName(sysModular);
		if(s!=null&&s.size()>0){
			addMessage(redirectAttributes, "该模块已存在添加失败！");
			return "redirect:"+Global.getAdminPath()+"/sysmodular/sysModular/?repage";
		}
		if(!sysModular.getIsNewRecord()){//编辑表单保存
			SysModular t = sysModularService.get(sysModular.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(sysModular, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			sysModularService.save(t);//保存
		}else{//新增表单保存

			sysModularService.save(sysModular);//保存
		}
		addMessage(redirectAttributes, "保存业务模块成功");
		return "redirect:"+Global.getAdminPath()+"/sysmodular/sysModular/?repage";
	}

	@RequestMapping(value = "saveColumn")
	public String saveColumn(SysModular sysModular, Model model, RedirectAttributes redirectAttributes) throws Exception{
		sysModularService.saveColumn(sysModular);//保存
		addMessage(redirectAttributes, "保存业务模块成功");
		return "redirect:"+Global.getAdminPath()+"/sysmodular/sysModular/?repage";
	}

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

	/**
	 * 导入Excel数据

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

	@RequestMapping(value = "gridColumn")
	public String gridSelectUser(SysModularField sysModularField,String tableName, String url, HttpServletRequest request, HttpServletResponse response, Model model){
		/*sysModularField.setTableName(modularId);
		sysModularField.setDbName();*/
		List<SysModularField> list=sysModularFieldService.gridColumn("'"+tableName+"'","'"+Global.getDbName()+"'");
		model.addAttribute("sysModularField", sysModularField);
		model.addAttribute("url", url);
		model.addAttribute("tableName", tableName);
		model.addAttribute("list", list);
		return  "modules/sysmodular/sysModularFieldList";
	}
	

}