/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workieavetemplate.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.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workieavetemplate.entity.WorkIeaveTemplateUser;
import com.jeeplus.modules.workieavetemplate.service.WorkIeaveTemplateUserService;
import com.jeeplus.modules.workregularapply.entity.WorkRegularApply;
import com.jeeplus.modules.workregularapply.entity.WorkRegularContent;
import com.jeeplus.modules.workregularapply.entity.WorkRegularScore;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
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.workieavetemplate.entity.WorkIeaveTemplate;
import com.jeeplus.modules.workieavetemplate.service.WorkIeaveTemplateService;

/**
 * 离职模板Controller
 * @author chenyuping
 * @version 2018-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/workieavetemplate/workIeaveTemplate")
public class WorkIeaveTemplateController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkIeaveTemplateService workIeaveTemplateService;
	@Autowired
	private WorkIeaveTemplateUserService workIeaveTemplateUserService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private OfficeDao officeDao;
	@ModelAttribute
	public WorkIeaveTemplate get(@RequestParam(required=false) String id) {
		WorkIeaveTemplate entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workIeaveTemplateService.get(id);
		}
		if (entity == null){
			entity = new WorkIeaveTemplate();
		}
		return entity;
	}
	
	/**
	 * 离职模板列表页面
	 */
	@RequiresPermissions("workieavetemplate:workIeaveTemplate:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkIeaveTemplate workIeaveTemplate, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkIeaveTemplate> page = workIeaveTemplateService.findPage(new Page<WorkIeaveTemplate>(request, response), workIeaveTemplate); 
		model.addAttribute("page", page);
		return "modules/workieavetemplate/workIeaveTemplateList";
	}

	/**
	 * 查看，增加，编辑离职模板表单页面
	 */
	@RequiresPermissions(value={"workieavetemplate:workIeaveTemplate:view","workieavetemplate:workIeaveTemplate:add","workieavetemplate:workIeaveTemplate:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkIeaveTemplate workIeaveTemplate, Model model) {
		String flat=request.getParameter("tabId");
		if("1".equals(flat)){

		}else{
			WorkIeaveTemplateUser workIeaveTemplateUser=new WorkIeaveTemplateUser();
			workIeaveTemplateUser.setTemplateId(workIeaveTemplate.getId());
			List<WorkIeaveTemplateUser> workIeaveTemplateList=workIeaveTemplateUserService.findList(workIeaveTemplateUser);
			workIeaveTemplate.setWorkIeaveTemplateUserList(workIeaveTemplateList);
		}
		model.addAttribute("workIeaveTemplate", workIeaveTemplate);
		return "modules/workieavetemplate/workIeaveTemplateForm";
	}

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

	/**
	 * 导入Excel数据

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


	@RequestMapping(value = "view")
	public String view(WorkIeaveTemplate workIeaveTemplate, Model model) {
		WorkIeaveTemplateUser workIeaveTemplateUser=new WorkIeaveTemplateUser();
		workIeaveTemplateUser.setTemplateId(workIeaveTemplate.getId());
		List<WorkIeaveTemplateUser> workIeaveTemplateList=workIeaveTemplateUserService.findList(workIeaveTemplateUser);
		workIeaveTemplate.setWorkIeaveTemplateUserList(workIeaveTemplateList);
		model.addAttribute("workIeaveTemplate", workIeaveTemplate);
		return "modules/workieavetemplate/workIeaveTemplateView";
	}
	@RequestMapping(value = "gridSelectUser")
	public String gridSelectUser(WorkStaffBasicInfo workStaffBasicInfo, String url, boolean isAll, String type, boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model){
		Office office=officeDao.get(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(office.getBranchOffice())){
			Office branchOffice =officeDao.get(office.getBranchOffice());
			workStaffBasicInfo.setBranchOffice(branchOffice);
		}else{
			workStaffBasicInfo.setCompany(UserUtils.getSelectCompany());
		}

		Page<WorkStaffBasicInfo> page = workStaffBasicInfoService.findTemplateUser(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		model.addAttribute("isSingle", isSingle);
		model.addAttribute("url", url);
		model.addAttribute("isAll", isAll);
		model.addAttribute("type", type);
		model.addAttribute("page", page);
		return  "modules/sys/gridSelectUser";
}

	/**
	 * 获取机构JSON数据。
	 *
	 * @param extId    排除的ID
	 * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade    显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeDataCompany")
	public List<Map<String, Object>> treeDataCompanyTemplate(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
													 @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office office = new Office();
		office.setParentIds(UserUtils.getSelectCompany().getId());
		List<Office> list = officeService.findByCompanyTemplate(office);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& Global.YES.equals(e.getUseable())) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
}