/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workregularapply.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.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlanThis;
import com.jeeplus.modules.workregularapply.dao.WorkRegularContentDao;
import com.jeeplus.modules.workregularapply.entity.WorkRegularContent;
import com.jeeplus.modules.workregularapply.entity.WorkRegularScore;
import com.jeeplus.modules.workregularapply.service.WorkRegularContentService;
import com.jeeplus.modules.workregularapply.service.WorkRegularScoreService;
import com.jeeplus.modules.workreimbursement.entity.WorkReimbursement;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
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.transaction.annotation.Transactional;
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.workregularapply.entity.WorkRegularApply;
import com.jeeplus.modules.workregularapply.service.WorkRegularApplyService;

/**
 * 转正申请Controller
 * @author chenyuping
 * @version 2018-07-30
 */
@Controller
@RequestMapping(value = "${adminPath}/workregularapply/workRegularApply")
public class WorkRegularApplyController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkRegularApplyService workRegularApplyService;
	@Autowired
	private WorkRegularContentService workRegularContentService;
	@Autowired
	private WorkRegularScoreService workRegularScoreService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;

	@ModelAttribute
	public WorkRegularApply get(@RequestParam(required=false) String id) {
		WorkRegularApply entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workRegularApplyService.get(id);
		}
		if (entity == null){
			entity = new WorkRegularApply();
		}
		return entity;
	}
	
	/**
	 * 转正申请列表页面
	 */
	@RequiresPermissions("workregularapply:workRegularApply:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkRegularApply workRegularApply, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkRegularApply> page = workRegularApplyService.findPage(new Page<WorkRegularApply>(request, response), workRegularApply); 
		model.addAttribute("page", page);
		WorkStaffBasicInfo basicInfo = workStaffAchivesDao.getByUserId(UserUtils.getUser().getId());
		model.addAttribute("user",basicInfo);
		return "modules/workregularapply/workRegularApplyList";
	}

	/**
	 * 查看1，增加，编辑转正申请表单页面
	 */
	@RequiresPermissions(value={"workregularapply:workRegularApply:view","workregularapply:workRegularApply:add","workregularapply:workRegularApply:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkRegularApply workRegularApply, Model model) {
		String flat=request.getParameter("tabId");

		//1 为 新增转正申请
		if("1".equals(flat)){
			// 如果当前用户在试用期，则将入职信息自动填写到Form
			WorkStaffBasicInfo basicInfo = workStaffAchivesDao.getByUserId(UserUtils.getUser().getId());
			if(basicInfo != null){
				String basicInfoId = basicInfo.getId();
				String userId = basicInfo.getUserId();
				String  pay = String.valueOf(basicInfo.getSalary());
				String jobName = basicInfo.getJobGrade().getName();
				String gradeId = basicInfo.getJobGrade().getId();
				workRegularApply.setPay(pay);
				workRegularApply.setBasicInfoId(basicInfoId);
				workRegularApply.setUserId(userId);
				workRegularApply.setJobName(jobName);
				WorkJobGrade workJobGrade = new WorkJobGrade();
				workJobGrade.setId(gradeId);
				workRegularApply.setJobGrade(workJobGrade);
			}
			workRegularApply.setWorkStaffBasicInfo(basicInfo);
			WorkRegularContent w=new WorkRegularContent();
			List<WorkRegularScore> workRegularScoreList=new ArrayList<>();
			List<WorkRegularContent> list=workRegularContentService.findList(w);
			//新增初始化鉴定内容
			for(WorkRegularContent workRegularContent:list){
				WorkRegularScore workRegularScore=new WorkRegularScore();
				workRegularScore.setRegularContentId(workRegularContent.getId());
				workRegularScore.setContent(workRegularContent.getContent());
				workRegularScoreList.add(workRegularScore);
			}
			workRegularApply.setWorkRegularScoreList(workRegularScoreList);
		}else{
			WorkRegularScore workRegularScore=new WorkRegularScore();
			workRegularScore.setRegularApplyId(workRegularApply.getId());
			List<WorkRegularScore> workRegularScoreList=workRegularScoreService.findList(workRegularScore);
			workRegularApply.setWorkRegularScoreList(workRegularScoreList);
		}
		model.addAttribute("workRegularApply", workRegularApply);
		return "modules/workregularapply/workRegularApplyForm";
	}
	/**
	 * 保存转正申请
	 */
	@RequiresPermissions(value={"workregularapply:workRegularApply:add","workregularapply:workRegularApply:edit"},logical=Logical.OR)
	@RequestMapping(value = "store")
	public String store(WorkRegularApply workRegularApply, Model model, RedirectAttributes redirectAttributes) throws Exception{
		long startTime=System.currentTimeMillis();   //获取开始时间
		if (!beanValidator(model, workRegularApply)){
			return form(workRegularApply, model);
		}
		workRegularApply.setState("1");
		if(!workRegularApply.getIsNewRecord()){//编辑表单保存
			WorkRegularApply t = workRegularApplyService.get(workRegularApply.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workRegularApply, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workRegularApplyService.save(t);//保存
		}else{//新增表单保存
			workRegularApply.setCompanyId(UserUtils.getSelectCompany().getId());
			workRegularApply.setOfficeId(UserUtils.getSelectOffice().getId());
			workRegularApplyService.save(workRegularApply);//保存
		}
		addMessage(redirectAttributes, "保存转正申请成功");
		long endTime=System.currentTimeMillis(); //获取结束时间
		logger.info("转正暂存运行时间： "+(endTime-startTime)+"ms");
		return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
	}
	/**
	 * 保存转正申请,并送审
	 */
	@RequiresPermissions(value={"workregularapply:workRegularApply:add","workregularapply:workRegularApply:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkRegularApply workRegularApply, Model model, RedirectAttributes redirectAttributes) throws Exception{
		long startTime=System.currentTimeMillis();   //获取开始时间
		if (!beanValidator(model, workRegularApply)){
			return form(workRegularApply, model);
		}
		workRegularApply.setState("2");
		if(!workRegularApply.getIsNewRecord()){//编辑表单保存
			WorkRegularApply t = workRegularApplyService.get(workRegularApply.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workRegularApply, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workRegularApplyService.saveApply(t);//保存
		}else{//新增表单保存
			workRegularApply.setCompanyId(UserUtils.getSelectCompany().getId());
			workRegularApply.setOfficeId(UserUtils.getSelectOffice().getId());
			workRegularApplyService.saveApply(workRegularApply);//保存
		}
		addMessage(redirectAttributes, "保存转正申请成功");
		long endTime=System.currentTimeMillis(); //获取结束时间
		logger.info("转正提交运行时间： "+(endTime-startTime)+"ms");
		return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
	}
	
	/**
	 * 删除转正申请
	 */
	@RequiresPermissions("workregularapply:workRegularApply:del")
	@RequestMapping(value = "delete")
	public String delete(WorkRegularApply workRegularApply, RedirectAttributes redirectAttributes) {
		if("5".equals(workRegularApply.getState())|| "2".equals(workRegularApply.getState())){
			if("5".equals(workRegularApply.getState())){
				addMessage(redirectAttributes, "转正申请已审批通过，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
			}else{
				addMessage(redirectAttributes, "转正申请正在审核中，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
			}
		}
		workRegularApplyService.delete(workRegularApply);
		addMessage(redirectAttributes, "删除转正申请成功");
		return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
	}
	
	/**
	 * 批量删除转正申请
	 */
	@RequiresPermissions("workregularapply:workRegularApply:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workRegularApplyService.delete(workRegularApplyService.get(id));
		}
		addMessage(redirectAttributes, "删除转正申请成功");
		return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workregularapply:workRegularApply:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkRegularApply workRegularApply, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "转正申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkRegularApply> page = workRegularApplyService.findPage(new Page<WorkRegularApply>(request, response, -1), workRegularApply);
    		new ExportExcel("转正申请", WorkRegularApply.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出转正申请记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workregularapply/workRegularApply/?repage";
    }

	/**
	 * 导入Excel数据

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

	//带出用户信息
	@RequestMapping("userInfo")
	@ResponseBody
	public WorkStaffBasicInfo getBeforeThisMonthMoney(String id) throws ParseException {
		WorkStaffBasicInfo workStaffBasicInfo = workRegularApplyService.getWorkStaffBasicInfo(id);
		return  workStaffBasicInfo;
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkRegularApply workRegularApply, Model model,
							RedirectAttributes redirectAttributes) {
//		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workRegularApply.getAct().getTaskDefKey();
			User user=userDao.get(workRegularApply.getUserId());
			Office applyOffice = officeDao.get(user.getOffice().getId());
			List<User> users = null;
//			if ("zzr".equals(taskDefKey)){
//				/*User user=userDao.get(workRegularApply.getUserId());
//				List<User> zzr=new ArrayList<>();
//				zzr.add(user);
//				users = zzr;*/
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),2);
//				if (users==null )
//					users = UserUtils.getByRoleActivityEnname("bmzr",2,applyOffice.getId(),"66",user);
//			}else if ("ywbfzr".equals(taskDefKey)){
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),3);
//				if (users==null )
//					users = UserUtils.getByRoleActivityEnname("fgld",2,applyOffice.getId(),"66",user);
//			}else  if ("fgld".equals(taskDefKey)){
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),4);
//				if (users==null )
//					users = UserUtils.getByRoleActivityEnname("zjl", 3, applyOffice.getId(), "66", user);
//			}else  if ("zjl".equals(taskDefKey)){
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),5);
//				if (users==null )
//					users = UserUtils.getByRoleActivityEnname("rlzy",3,applyOffice.getId(),"66",user);
//			}else if ("rlzy".equals(taskDefKey)){
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),5);
//			}else if ("modifyApply".equals(taskDefKey)){
//				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),1);
//			}
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("rsbzr", 3, applyOffice.getId(), "18", user);
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fzjl", 3, applyOffice.getId(), "18", user);
			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),4);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("zjl",3,applyOffice.getId(),"18",user);
			}else if ("rlzy".equals(taskDefKey)){
				List<User> list = Lists.newArrayList();
				list.add(UserUtils.getUser());
				users = list;
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workRegularApply.getProcessInstanceId(),1);
			}
			if (users==null || users.size()==0){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workRegularApplyService.auditSave(workRegularApply,users);
				addMessage(redirectAttributes, str);
			}
//		}catch (Exception e){
//			logger.info("Exception e:"+e);
//			addMessage(redirectAttributes, "审批失败");
//		}
		if (StringUtils.isNotBlank(workRegularApply.getHome()) && "home".equals(workRegularApply.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workregularapply/workRegularApply/?repage";
		}
	}


	//	审批页面
	@RequestMapping(value = "audit")
	public String workContractInfoAudit(Act act, WorkRegularApply workRegularApply, 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())) {
			workRegularApply.setAct(act);
			model.addAttribute("processInstanceId", workRegularApply.getProcessInstanceId());
		}
		model.addAttribute("workRegularApply", workRegularApply);
		return "modules/workregularapply/workRegularApplyAudit";
	}

	@RequiresPermissions(value={"workregularapply:workRegularApply:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkRegularApply workRegularApply, Model model, RedirectAttributes redirectAttributes) {
		workRegularApply=workRegularApplyService.get(workRegularApply.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workRegularApply.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);
			workRegularApply.setAct(act);
		}
		WorkRegularScore workRegularScore=new WorkRegularScore();
		workRegularScore.setRegularApplyId(workRegularApply.getId());
		List<WorkRegularScore> workRegularScoreList=workRegularScoreService.findList(workRegularScore);
		workRegularApply.setWorkRegularScoreList(workRegularScoreList);
		model.addAttribute("workRegularApply", workRegularApply);
		return "modules/workregularapply/workRegularApplyModifyApply";
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(WorkRegularApply workRegularApply, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workRegularApply.getProcessInstanceId());
		return "modules/workregularapply/workRegularApplyTask";
	}

	@RequiresPermissions(value={"workregularapply:workRegularApply: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 {
			workRegularApplyService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回转正申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回转正申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workregularapply/workRegularApply/?repage";
	}


	@RequestMapping(value = "view")
	public String view(WorkRegularApply workRegularApply, Model model) {
		WorkRegularScore workRegularScore=new WorkRegularScore();
		workRegularScore.setRegularApplyId(workRegularApply.getId());
		List<WorkRegularScore> workRegularScoreList=workRegularScoreService.findList(workRegularScore);
		workRegularApply.setWorkRegularScoreList(workRegularScoreList);
		model.addAttribute("workRegularApply", workRegularApply);
		return "modules/workregularapply/workRegularApplyView";
	}

}