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

import java.util.Date;
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.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workieavetemplate.entity.WorkIeaveTemplateUser;
import com.jeeplus.modules.workieavetemplate.service.WorkIeaveTemplateUserService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbursement.service.WorkReimbursementService;
import com.jeeplus.modules.workresignationtemplate.entity.WorkResignationTemplate;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.workresignation.entity.WorkResignation;
import com.jeeplus.modules.workresignation.service.WorkResignationService;

/**
 * 离职申请Controller
 * @author rh
 * @version 2018-08-04
 */
@Controller
@RequestMapping(value = "${adminPath}/workresignation/workResignation")
public class WorkResignationController extends BaseController {

	@Autowired
	private WorkResignationService workResignationService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkIeaveTemplateUserService workIeaveTemplateUserService;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;

	@ModelAttribute
	public WorkResignation get(@RequestParam(required=false) String id) {
		WorkResignation entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workResignationService.get(id);
		}
		if (entity == null){
			entity = new WorkResignation();
		}
		return entity;
	}
	
	/**
	 * 离职申请列表页面
	 */
	@RequiresPermissions("workresignation:workResignation:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkResignation workResignation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkResignation> page = workResignationService.findPage(new Page<WorkResignation>(request, response), workResignation); 
		model.addAttribute("page", page);
		return "modules/workresignation/workResignationList";
	}

	/**
	 * 查看，增加，编辑离职申请表单页面
	 */
	//@RequiresPermissions(value={"workresignation:workResignation:view","workresignation:workResignation:add","workresignation:workResignation:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkResignation workResignation, Model model) {
		String view = "workResignationForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workResignationView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workResignation.getProcessInstanceId());
			if (processInstance!=null) {
				Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
				Act act = new Act();
				act.setTaskId(taskInfok.getId());
				act.setTaskName(taskInfok.getName());
				act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
				act.setProcDefId(taskInfok.getProcessDefinitionId());
				act.setProcInsId(taskInfok.getProcessInstanceId());
				act.setTask(taskInfok);
				workResignation.setAct(act);
				view = "workResignationModify";
			}
		}
		// 环节编号
		String taskDefKey = workResignation.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("rlzy".equals(taskDefKey) || "bmzr".equals(taskDefKey))){
			view = "workResignationAudit";
		}
		if(StringUtils.isBlank(workResignation.getId())){
			workResignation.setDate(new Date());
			workResignation.setEndDate(new Date());
			//离职审核列表
			List<WorkIeaveTemplateUser> list = workIeaveTemplateUserService.findListforLeave();
			List<WorkResignationTemplate> templateList = Lists.newArrayList();
			if(list!=null && list.size()>0){
				for (WorkIeaveTemplateUser w:
					 list) {
					WorkResignationTemplate template = new WorkResignationTemplate();
					template.setAuditor(w.getAuditor());
					template.setOfficeId(w.getOfficeId());
					template.setComment(w.getComment());
					template.setOfficeName(w.getOfficeName());
					template.setUserName(w.getUserName());
					templateList.add(template);
				}
				workResignation.setTemplateList(templateList);
			}
		}
		model.addAttribute("workResignation", workResignation);
		return "modules/workresignation/"+view;
	}

	@RequestMapping(value = "store")
	public String store(WorkResignation workResignation,
						Model model,
//						@RequestParam(value = "upload_files",required = false) MultipartFile[] upload_files,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workResignation)){
			return form(workResignation, model);
		}

		User user = workResignation.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workResignation.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
		}
		workResignation.setStatus("1"); //暂存状态
		workResignation.setCompanyId(UserUtils.getSelectCompany().getId());
		workResignation.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workResignation.getProcessInstanceId()) && workResignation.getProcessInstanceId().equals("NULL")){
			workResignation.setProcessInstanceId("");
		}
		if(!workResignation.getIsNewRecord()){//编辑表单保存
			WorkResignation t = workResignationService.get(workResignation.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workResignation, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workResignationService.save(t);//保存
		}else{//新增表单保存
			workResignationService.save(workResignation);//保存
		}
		addMessage(redirectAttributes, "保存离职单成功");
		return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
	}
	/**
	 * 保存离职申请
	 */
	@RequiresPermissions(value={"workresignation:workResignation:add","workresignation:workResignation:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkResignation workResignation, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workResignation)){
			return form(workResignation, model);
		}
		User user = workResignation.getCreateBy();
		String sta = workResignation.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
		}
		//状态设置为审核中
		workResignation.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workResignationService.get(workResignation.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workResignation.setCompanyId(UserUtils.getSelectCompany().getId());
			workResignation.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workResignationService.save(workResignation, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "离职申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "离职申请已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "离职申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		if (StringUtils.isNotBlank(workResignation.getHome()) && "home".equals(workResignation.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workresignation/workResignation/?repage";
		}
	}

	@RequestMapping(value = "saveAudits")
	public String saveAudits(WorkResignation workResignation,
							RedirectAttributes redirectAttributes) {
		workResignationService.updateWorkReimbursementInfo(workResignation);
		List<WorkResignationTemplate> list = workResignation.getTemplateList();
		if(list!=null && list.size()>0){
			for (WorkResignationTemplate w:
				 list) {
				if("2".equals(w.getStatus())){
					workResignationService.cancelInvalidates(workResignation);
					break;
				}
			}
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyRole("各级审批");
		notify.setUser(UserUtils.getUser());
		workProjectNotifyService.readByNotifyUser(notify);
		addMessage(redirectAttributes, "审核完成");
		if (StringUtils.isNotBlank(workResignation.getHome()) && "home".equals(workResignation.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workresignation/workResignation/?repage";
		}
	}

	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkResignation workResignation, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			Office office =null;
			String sId = workResignation.getWorkStaffBasicInfo().getId();
			WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(sId);
			if(workStaffBasicInfo!=null){
				String uId = workStaffBasicInfo.getUserId();
				User user = UserUtils.get(uId);
				if(user ==null){
					addMessage(redirectAttributes, "审批失败,未找到申请人账号数据,请联系管理员！");
					if (StringUtils.isNotBlank(workResignation.getHome()) && "home".equals(workResignation.getHome())) {
						return "redirect:" + Global.getAdminPath() + "/home/?repage";
					} else {
						return "redirect:" + Global.getAdminPath() + "/workresignation/workResignation/?repage";
					}
				}else{
					office = user.getOffice();
					if(office ==null){
						addMessage(redirectAttributes, "审批失败,未找到申请人账号数据,请联系管理员！");
						if (StringUtils.isNotBlank(workResignation.getHome()) && "home".equals(workResignation.getHome())) {
							return "redirect:" + Global.getAdminPath() + "/home/?repage";
						} else {
							return "redirect:" + Global.getAdminPath() + "/workresignation/workResignation/?repage";
						}
					}
				}
			}
			String taskDefKey = workResignation.getAct().getTaskDefKey();
			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workResignation.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"18",workResignation.getCreateBy());
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workResignation.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("zjl", 3, workResignation.getOfficeId(), "18", workResignation.getCreateBy());
			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workResignation.getProcessInstanceId(),4);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("rlzy",3,workResignation.getOfficeId(),"18",workResignation.getCreateBy());
			}else if ("rlzy".equals(taskDefKey)){
				List<User> list = Lists.newArrayList();
				list.add(UserUtils.getUser());
				users = list;
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workResignation.getProcessInstanceId(),1);
			}
			String flag = workResignation.getAct().getFlag();
			if ("yes".equals(flag) && (users==null ||(users!=null && users.size() == 0))){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workResignationService.auditSave(workResignation,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workResignation.getHome()) && "home".equals(workResignation.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workresignation/workResignation/?repage";
		}
	}

	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkResignation workResignation,Model model) {
		model.addAttribute("processInstanceId", workResignation.getProcessInstanceId());
		return "modules/workrelationship/Track";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkResignation workResignation,RedirectAttributes redirectAttributes){
		workResignationService.cancelInvalidate(workResignation);
		return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
	}
	/**
	 * 删除离职申请
	 */
	@RequiresPermissions("workresignation:workResignation:del")
	@RequestMapping(value = "delete")
	public String delete(WorkResignation workResignation, RedirectAttributes redirectAttributes) {
		workResignationService.delete(workResignation);
		addMessage(redirectAttributes, "删除离职申请成功");
		return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
	}
	
	/**
	 * 批量删除离职申请
	 */
	@RequiresPermissions("workresignation:workResignation:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workResignationService.delete(workResignationService.get(id));
		}
		addMessage(redirectAttributes, "删除离职申请成功");
		return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workresignation:workResignation:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkResignation workResignation, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "离职申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkResignation> page = workResignationService.findPage(new Page<WorkResignation>(request, response, -1), workResignation);
    		new ExportExcel("离职申请", WorkResignation.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出离职申请记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workresignation/workResignation/?repage";
    }

	/**
	 * 导入Excel数据

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

}