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

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlanThis;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeUserService;
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.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.*;
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.workofficechange.entity.WorkOfficeChange;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeService;

/**
 * 部门调转Controller
 * @author chenyuping
 * @version 2018-08-01
 */
@Controller
@RequestMapping(value = "${adminPath}/workofficechange/workOfficeChange")
public class WorkOfficeChangeController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkOfficeChangeService workOfficeChangeService;
	@Autowired
	private WorkOfficeChangeUserService workOfficeChangeUserService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private UserDao userDao;
	@ModelAttribute
	public WorkOfficeChange get(@RequestParam(required=false) String id) {
		WorkOfficeChange entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOfficeChangeService.get(id);
		}
		if (entity == null){
			entity = new WorkOfficeChange();
		}
		return entity;
	}
	
	/**
	 * 部门调转列表页面
	 */
	@RequiresPermissions("workofficechange:workOfficeChange:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkOfficeChange workOfficeChange, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkOfficeChange> page = workOfficeChangeService.findPage(new Page<WorkOfficeChange>(request, response), workOfficeChange); 
		model.addAttribute("page", page);
		return "modules/workofficechange/workOfficeChangeList";
	}

	/**
	 * 查看，增加，编辑部门调转表单页面
	 */
	@RequiresPermissions(value={"workofficechange:workOfficeChange:view","workofficechange:workOfficeChange:add","workofficechange:workOfficeChange:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkOfficeChange workOfficeChange, Model model) {
		String flat=request.getParameter("tabId");
		if("1".equals(flat)){
			workOfficeChange.setUserName(UserUtils.getUser().getName());
			workOfficeChange.setChanger(UserUtils.getUser().getId());
		}else{
			WorkOfficeChangeUser workOfficeChangeUser=new WorkOfficeChangeUser();
			workOfficeChangeUser.setChangeId(workOfficeChange.getId());
			List<WorkOfficeChangeUser> workOfficeChangeUserList=workOfficeChangeUserService.findList(workOfficeChangeUser);
			workOfficeChange.setWorkOfficeChangeUserList(workOfficeChangeUserList);
		}
		model.addAttribute("workOfficeChange", workOfficeChange);
		return "modules/workofficechange/workOfficeChangeForm";
	}

	/**
	 * 保存部门调转
	 */
	@RequiresPermissions(value={"workofficechange:workOfficeChange:add","workofficechange:workOfficeChange:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkOfficeChange workOfficeChange, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workOfficeChange)){
			return form(workOfficeChange, model);
		}
		workOfficeChange.setState("2");
		if(!workOfficeChange.getIsNewRecord()){//编辑表单保存
			WorkOfficeChange t = workOfficeChangeService.get(workOfficeChange.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workOfficeChange, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String str =workOfficeChangeService.saveChange(t);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "部门调转申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "部门调转申请已经提交");
			}
		}else{//新增表单保存
			workOfficeChange.setCompanyId(UserUtils.getSelectCompany().getId());
			workOfficeChange.setOfficeId(UserUtils.getSelectOffice().getId());
			String str=workOfficeChangeService.saveChange(workOfficeChange);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "部门调转申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "部门调转申请已经提交");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
	}
	/**
	 * 保存部门调转
	 */
	@RequiresPermissions(value={"workofficechange:workOfficeChange:add","workofficechange:workOfficeChange:edit"},logical=Logical.OR)
	@RequestMapping(value = "store")
	public String store(WorkOfficeChange workOfficeChange, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workOfficeChange)){
			return form(workOfficeChange, model);
		}
		workOfficeChange.setState("1");
		if(!workOfficeChange.getIsNewRecord()){//编辑表单保存
			WorkOfficeChange t = workOfficeChangeService.get(workOfficeChange.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workOfficeChange, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workOfficeChangeService.save(t);//保存
		}else{//新增表单保存
			workOfficeChange.setCompanyId(UserUtils.getSelectCompany().getId());
			workOfficeChange.setOfficeId(UserUtils.getSelectOffice().getId());
			workOfficeChangeService.save(workOfficeChange);//保存
		}
		addMessage(redirectAttributes, "保存部门调转成功");
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
	}
	/**
	 * 删除部门调转
	 */
	@RequiresPermissions("workofficechange:workOfficeChange:del")
	@RequestMapping(value = "delete")
	public String delete(WorkOfficeChange workOfficeChange, RedirectAttributes redirectAttributes) {
		if("5".equals(workOfficeChange.getState())|| "2".equals(workOfficeChange.getState())){
			if("5".equals(workOfficeChange.getState())){
				addMessage(redirectAttributes, "部门调转已审批通过，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
			}else{
				addMessage(redirectAttributes, "部门调转正在审核中，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
			}
		}
		workOfficeChangeService.delete(workOfficeChange);
		addMessage(redirectAttributes, "删除部门调转成功");
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
	}
	
	/**
	 * 批量删除部门调转
	 */
	@RequiresPermissions("workofficechange:workOfficeChange:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workOfficeChangeService.delete(workOfficeChangeService.get(id));
		}
		addMessage(redirectAttributes, "删除部门调转成功");
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workofficechange:workOfficeChange:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkOfficeChange workOfficeChange, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "部门调转"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkOfficeChange> page = workOfficeChangeService.findPage(new Page<WorkOfficeChange>(request, response, -1), workOfficeChange);
    		new ExportExcel("部门调转", WorkOfficeChange.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出部门调转记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChange/?repage";
    }

	/**
	 * 导入Excel数据

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


	//获取入职信息
	@RequestMapping(value = "getBasicInfo")
	@ResponseBody
	public List<WorkStaffBasicInfo> getBasicInfo(String ids)  {
		String arr[]=ids.split(",");
		List<WorkStaffBasicInfo> workStaffBasicInfoList=new ArrayList<>();
		for(String id:arr){
			WorkStaffBasicInfo workStaffBasicInfo =new WorkStaffBasicInfo();
			workStaffBasicInfo.setId(id);
			WorkStaffBasicInfo w=workOfficeChangeService.getWorkStaffBasicInfo(id);
			if(w!=null){
				workStaffBasicInfoList.add(w);
			}
		}
		return  workStaffBasicInfoList;
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkOfficeChange workOfficeChange, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workOfficeChange.getAct().getTaskDefKey();
			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workOfficeChange.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fgld",2,workOfficeChange.getOfficeId(),"68",workOfficeChange.getCreateBy());
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workOfficeChange.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("zjl", 3, workOfficeChange.getOfficeId(), "68", workOfficeChange.getCreateBy());
			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workOfficeChange.getProcessInstanceId(),3);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workOfficeChange.getProcessInstanceId(),1);
			}
			if (users==null || (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workOfficeChangeService.auditSave(workOfficeChange,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workOfficeChange.getHome()) && "home".equals(workOfficeChange.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workofficechange/workOfficeChange/?repage";
		}
	}

	//	审批页面
	@RequestMapping(value = "audit")
	public String workContractInfoAudit(Act act, WorkOfficeChange workOfficeChange, Model model) {

		if (act.getProcInsId() != null) {
			if (actTaskService.getProcIns(act.getProcInsId()) != null) {
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			} else {
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
			workOfficeChange.setAct(act);
			model.addAttribute("processInstanceId", workOfficeChange.getProcessInstanceId());
		}
		model.addAttribute("workOfficeChange", workOfficeChange);
		return "modules/workofficechange/workOfficeChangeAudit";
	}

	@RequiresPermissions(value={"workofficechange:workOfficeChange:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkOfficeChange workOfficeChange, Model model, RedirectAttributes redirectAttributes) {
		workOfficeChange=workOfficeChangeService.get(workOfficeChange.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workOfficeChange.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);
			workOfficeChange.setAct(act);
		}
		WorkOfficeChangeUser workOfficeChangeUser=new WorkOfficeChangeUser();
		workOfficeChangeUser.setChangeId(workOfficeChange.getId());
		List<WorkOfficeChangeUser> workOfficeChangeUserList=workOfficeChangeUserService.findList(workOfficeChangeUser);
		workOfficeChange.setWorkOfficeChangeUserList(workOfficeChangeUserList);
		model.addAttribute("workOfficeChange", workOfficeChange);
		return "modules/workofficechange/workOfficeChangeModifyApply";
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(WorkOfficeChange workOfficeChange, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workOfficeChange.getProcessInstanceId());
		return "modules/workofficechange/workOfficeChangeTask";
	}

	@RequiresPermissions(value={"workofficechange:workOfficeChange:edit"},logical=Logical.OR)
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		try {
			workOfficeChangeService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回调转申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回调转申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workofficechange/workOfficeChange/?repage";
	}


	@RequestMapping(value = "view")
	public String view(WorkOfficeChange workOfficeChange, Model model) {
		WorkOfficeChangeUser workOfficeChangeUser=new WorkOfficeChangeUser();
		workOfficeChangeUser.setChangeId(workOfficeChange.getId());
		List<WorkOfficeChangeUser> workOfficeChangeUserList=workOfficeChangeUserService.findList(workOfficeChangeUser);
		workOfficeChange.setWorkOfficeChangeUserList(workOfficeChangeUserList);
		model.addAttribute("workOfficeChange", workOfficeChange);
		return "modules/workofficechange/workOfficeChangeView";
	}
}