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

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.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workchangejob.entity.WorkChangeJobUser;
import com.jeeplus.modules.workchangejob.service.WorkChangeJobUserService;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChange;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeService;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeUserService;
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.workchangejob.entity.WorkChangeJob;
import com.jeeplus.modules.workchangejob.service.WorkChangeJobService;

/**
 * 职级调整Controller
 * @author chenyuping
 * @version 2018-08-02
 */
@Controller
@RequestMapping(value = "${adminPath}/workchangejob/workChangeJob")
public class WorkChangeJobController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkOfficeChangeService workOfficeChangeService;
	@Autowired
	private WorkOfficeChangeUserService workOfficeChangeUserService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkChangeJobService workChangeJobService;
	@Autowired
	private WorkChangeJobUserService workChangeJobUserService;

	@ModelAttribute
	public WorkChangeJob get(@RequestParam(required=false) String id) {
		WorkChangeJob entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workChangeJobService.get(id);
		}
		if (entity == null){
			entity = new WorkChangeJob();
		}
		return entity;
	}
	
	/**
	 * 职级调整列表页面
	 */
	@RequiresPermissions("workchangejob:workChangeJob:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkChangeJob workChangeJob, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkChangeJob> page = workChangeJobService.findPage(new Page<WorkChangeJob>(request, response), workChangeJob); 
		model.addAttribute("page", page);
		return "modules/workchangejob/workChangeJobList";
	}

	/**
	 * 查看，增加，编辑职级调整表单页面
	 */
	@RequiresPermissions(value={"workchangejob:workChangeJob:view","workchangejob:workChangeJob:add","workchangejob:workChangeJob:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkChangeJob workChangeJob, Model model) {
		String flat=request.getParameter("tabId");
		if("1".equals(flat)){
			workChangeJob.setUserName(UserUtils.getUser().getName());
			workChangeJob.setChanger(UserUtils.getUser().getId());
		}else{
			WorkChangeJobUser workChangeJobUser=new WorkChangeJobUser();
			workChangeJobUser.setChangeId(workChangeJob.getId());
			List<WorkChangeJobUser> workChangeJobUserList=workChangeJobUserService.findList(workChangeJobUser);
			workChangeJob.setWorkChangeJobUserList(workChangeJobUserList);
		}
		model.addAttribute("workChangeJob", workChangeJob);
		return "modules/workchangejob/workChangeJobForm";
	}

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

	/**
	 * 导入Excel数据

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

	//获取入职信息
	@RequestMapping("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(WorkChangeJob workChangeJob, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workChangeJob.getAct().getTaskDefKey();
			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workChangeJob.getProcessInstanceId(),3);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workChangeJob.getProcessInstanceId(),1);
			}
				String str = workChangeJobService.auditSave(workChangeJob,users);
				addMessage(redirectAttributes, str);

		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workChangeJob.getHome()) && "home".equals(workChangeJob.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workchangejob/workChangeJob/?repage";
		}

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

	@RequiresPermissions(value={"workchangejob:workChangeJob:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkChangeJob workChangeJob, Model model, RedirectAttributes redirectAttributes) {
		workChangeJob=workChangeJobService.get(workChangeJob.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workChangeJob.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);
			workChangeJob.setAct(act);
		}
		WorkChangeJobUser workChangeJobUser=new WorkChangeJobUser();
		workChangeJobUser.setChangeId(workChangeJob.getId());
		List<WorkChangeJobUser> workChangeJobUserList=workChangeJobUserService.findList(workChangeJobUser);
		workChangeJob.setWorkChangeJobUserList(workChangeJobUserList);
		model.addAttribute("workChangeJob", workChangeJob);
		return "modules/workchangejob/workChangeJobModifyApply";
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(WorkChangeJob workChangeJob, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workChangeJob.getProcessInstanceId());
		return "modules/workchangejob/workChangeJobTask";
	}

	@RequiresPermissions(value={"workchangejob:workChangeJob: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 {
			workChangeJobService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回职级调整申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回职级调整申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workchangejob/workChangeJob/?repage";
	}


	@RequestMapping(value = "view")
	public String view(WorkChangeJob workChangeJob, Model model) {
		WorkChangeJobUser workChangeJobUser=new WorkChangeJobUser();
		workChangeJobUser.setChangeId(workChangeJob.getId());
		List<WorkChangeJobUser> workChangeJobUserList=workChangeJobUserService.findList(workChangeJobUser);
		workChangeJob.setWorkChangeJobUserList(workChangeJobUserList);
		model.addAttribute("workChangeJob", workChangeJob);
		return "modules/workchangejob/workChangeJobView";
	}
}