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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

import com.google.common.collect.Maps;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.service.SysRoleActivityService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmodular.entity.SysModular;
import com.jeeplus.modules.sysmodular.entity.SysModularField;
import com.jeeplus.modules.sysmodular.service.SysModularFieldService;
import com.jeeplus.modules.sysmodular.service.SysModularService;
import com.jeeplus.modules.syswarning.entity.SysWarningRole;
import com.jeeplus.modules.syswarning.entity.SysWarningUser;
import com.jeeplus.modules.syswarning.service.SysWarningRoleService;
import com.jeeplus.modules.syswarning.service.SysWarningUserService;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
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.*;
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.syswarning.entity.SysWarning;
import com.jeeplus.modules.syswarning.service.SysWarningService;

/**
 * 系统预警Controller
 * @author chenyuping
 * @version 2018-08-14
 */
@Controller
@RequestMapping(value = "${adminPath}/syswarning/sysWarning")
public class SysWarningController extends BaseController {

	@Autowired
	private SysModularFieldService sysModularFieldService;
	@Autowired
	private SysModularService sysModularService;
	@Autowired
	private SysWarningService sysWarningService;
	@Autowired
	private SysRoleActivityService sysRoleActivityService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private SysWarningUserService sysWarningUserService;
	@Autowired
	private SysWarningRoleService sysWarningRoleService;
	@Autowired
	private OfficeDao officeDao;

	@ModelAttribute
	public SysWarning get(@RequestParam(required=false) String id) {
		SysWarning entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysWarningService.get(id);
		}
		if (entity == null){
			entity = new SysWarning();
		}
		return entity;
	}
	
	/**
	 * 系统预警列表页面
	 */
	@RequiresPermissions("syswarning:sysWarning:list")
	@RequestMapping(value = {"list", ""})
	public String list(SysWarning sysWarning, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysWarning> page = sysWarningService.findPage(new Page<SysWarning>(request, response), sysWarning); 
		model.addAttribute("page", page);
		return "modules/syswarning/sysWarningList";
	}

	/**
	 * 查看，增加，编辑系统预警表单页面
	 */
	@RequiresPermissions(value={"syswarning:sysWarning:view","syswarning:sysWarning:add","syswarning:sysWarning:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(SysWarning sysWarning, Model model) {
		String flat=request.getParameter("tabId");
		if("1".equals(flat)){

		}else{
			SysWarningUser sysWarningUser=new SysWarningUser();
			sysWarningUser.setWarningId(sysWarning.getId());
			List<SysWarningUser> sysWarningUserList=sysWarningUserService.findList(sysWarningUser);
			sysWarning.setSysWarningUserList(sysWarningUserList);

			SysWarningRole sysWarningRole=new SysWarningRole();
			sysWarningRole.setWarningId(sysWarning.getId());
			List<SysWarningRole> sysWarningRoleList=sysWarningRoleService.findList(sysWarningRole);
			sysWarning.setSysWarningRoleList(sysWarningRoleList);
		}
		model.addAttribute("sysWarning", sysWarning);
		return "modules/syswarning/sysWarningForm";
	}

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

	/**
	 * 导入Excel数据

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

	/**
	 * 移除恢复物品目录
	 */
	/*@RequiresPermissions("workcatalogueitem:workCatalogueItem:update")*/
	@RequestMapping(value = "update")
	public String update(SysWarning sysWarning, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String flat =request.getParameter("flat");
		if("2".equals(flat)){
			sysWarning.setState("0");
			sysWarningService.removeFlat(sysWarning);
			addMessage(redirectAttributes, "禁用预警成功");
		}
		if("3".equals(flat)){
			sysWarning.setState("1");
			sysWarningService.removeFlat(sysWarning);
			addMessage(redirectAttributes, "启用预警成功");
		}
		return "redirect:"+Global.getAdminPath()+"/syswarning/sysWarning/?repage";
	}

	@RequestMapping(value = "selectRole")
	public String gridSelectUser(SysRoleActivity sysRoleActivity, String url, boolean isAll, boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model){
		Page<SysRoleActivity> page = sysRoleActivityService.findPage(new Page<SysRoleActivity>(request, response), sysRoleActivity);
		model.addAttribute("page", page);
		model.addAttribute("sysRoleActivity", sysRoleActivity);
		model.addAttribute("isSingle", isSingle);
		model.addAttribute("url", url);
		model.addAttribute("isAll", isAll);
		return  "modules/syswarning/sysWarningRoleList";
	}
	@RequestMapping(value = "gridSelectUser")
	public String gridSelectUser(WorkStaffBasicInfo workStaffBasicInfo, String url, boolean isAll, boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model){
		workStaffBasicInfo.setCompany(UserUtils.getSelectCompany());
		Page<WorkStaffBasicInfo> page = sysWarningService.sysWarningUser(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		model.addAttribute("isSingle", isSingle);
		model.addAttribute("url", url);
		model.addAttribute("isAll", isAll);
		model.addAttribute("page", page);
		return  "modules/sys/gridSelectUser";
	}

	@RequestMapping(value = {"rulesIndex"})
	public String index(SysWarning sysWarning, Model model) {
		SysModular sysModular=new SysModular();
		List<SysModular> modularList=sysModularService.findList(sysModular);
		model.addAttribute("modularList", modularList);
		return "modules/syswarning/rulesIndex";
	}

	/**
	 * 模块-- 字段关系列表
	 * @param
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getField")
	public List<Map<String, Object>> getField(String modularId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		if(modularId==null){
			modularId="1";
		}
		SysModularField modularField=new SysModularField();
		modularField.setModularId(modularId);
		List<SysModularField> list = sysWarningService.findModularField(modularField);
		for (SysModularField e : list) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", 0);
			map.put("name", e.getNotes());
			mapList.add(map);
		}
		return mapList;
	}

	@ResponseBody
	@RequestMapping(value = "findField")
	public SysModularField findField(String id, HttpServletResponse response) {
		SysModularField sysModularField=sysModularFieldService.get(id);
		List list=new ArrayList();
		if(sysModularField!=null&&"2".equals(sysModularField.getShowType())){
			if("1".equals(sysModularField.getIsSysDict())){
				list=DictUtils.getMainDictList(sysModularField.getLogic());
			}else{
				list=DictUtils.getDictList(sysModularField.getLogic());
			}
			sysModularField.setDictList(list);
		}
		return sysModularField;
	}
	//验证sql是否正确
	@ResponseBody
	@RequestMapping(value = "sqlString")
	public Boolean sqlString(String sqlString, HttpServletResponse response) {
		try {
			int count=sysWarningService.getSqlString(sqlString);
		}catch (Exception e){
			System.out.println("SQL拼接有误！");
			return false;
		};
		return true;
	}

	//验证sql是否正确
	@ResponseBody
	@RequestMapping(value = "modularSql")
	public String modularSql(String modularSql, HttpServletResponse response) {
		SysModular sysModular=sysModularService.get(modularSql);
		return sysModular.getSqlString();
	}

}