/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workreceiptsrevise.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.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 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.workreceiptsrevise.entity.WorkReceiptsRevise;
import com.jeeplus.modules.workreceiptsrevise.service.WorkReceiptsReviseService;

/**
 * 收入调整Controller
 * @author lw
 * @version 2018-06-29
 */
@Controller
@RequestMapping(value = "${adminPath}/workreceiptsrevise/workReceiptsRevise")
public class WorkReceiptsReviseController extends BaseController {

	@Autowired
	private WorkReceiptsReviseService workReceiptsReviseService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private OfficeService officeService;
	@ModelAttribute
	public WorkReceiptsRevise get(@RequestParam(required=false) String id) {
		WorkReceiptsRevise entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReceiptsReviseService.get(id);
		}
		if (entity == null){
			entity = new WorkReceiptsRevise();
		}
		return entity;
	}
	
	/**
	 * 收入调整列表页面
	 */
	@RequiresPermissions("workreceiptsrevise:workReceiptsRevise:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReceiptsRevise workReceiptsRevise, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkReceiptsRevise> page = workReceiptsReviseService.findPage(new Page<WorkReceiptsRevise>(request, response), workReceiptsRevise); 
		model.addAttribute("page", page);
		return "modules/workreceiptsrevise/workReceiptsReviseList";
	}

	/**
	 * 查看，增加，编辑收入调整表单页面
	 */
	//@RequiresPermissions(value={"workreceiptsrevise:workReceiptsRevise:view","workreceiptsrevise:workReceiptsRevise:add","workreceiptsrevise:workReceiptsRevise:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReceiptsRevise workReceiptsRevise, Model model) {
		String view = "workReceiptsReviseForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workReceiptsReviseView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workReceiptsRevise.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);
				workReceiptsRevise.setAct(act);
				view = "workReceiptsReviseModify";
			}
		}else if("5".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workReceiptsRevise.getInvalidProcessInstanceId());
			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);
				workReceiptsRevise.setAct(act);
				view = "workReceiptsReviseInvalidModify";
			}
		}
		// 环节编号
		String taskDefKey = workReceiptsRevise.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workReceiptsReviseAudit";
		}
		if (workReceiptsRevise!=null && StringUtils.isBlank(workReceiptsRevise.getOfficeName())){
			workReceiptsRevise.setOfficeName(office.getTopCompany());
		}
		if (workReceiptsRevise!=null && StringUtils.isBlank(workReceiptsRevise.getUserName())){
			workReceiptsRevise.setUserName(UserUtils.getUser().getName());
		}
		if (workReceiptsRevise!=null && workReceiptsRevise.getReviseDate() == null){
			workReceiptsRevise.setReviseDate(new Date());
		}
		model.addAttribute("workReceiptsRevise", workReceiptsRevise);
		return "modules/workreceiptsrevise/"+view;
	}

	@RequestMapping(value = "store")
	public String store(WorkReceiptsRevise workReceiptsRevise,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReceiptsRevise)){
			return form(workReceiptsRevise, model);
		}

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

		} catch (Exception e) {
			addMessage(redirectAttributes, "收入调整申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
	}
	@RequestMapping(value = "invalid")
	public String invalid(WorkReceiptsRevise workReceiptsRevise, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReceiptsRevise)){
			return form(workReceiptsRevise, model);
		}
		User user = workReceiptsRevise.getCreateBy();
		String sta = workReceiptsRevise.getInvalidStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法申请作废");
			return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
		}
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workReceiptsReviseService.get(workReceiptsRevise.getId()).getInvalidProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workReceiptsRevise.setCompanyId(UserUtils.getSelectCompany().getId());
			workReceiptsRevise.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workReceiptsReviseService.invalidSave(workReceiptsRevise, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "收入调整作废申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "收入调整作废申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "收入调整作废申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workreceiptsreviseinvalid/workReceiptsReviseInvalid/list";
	}
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkReceiptsRevise workReceiptsRevise, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			String taskDefKey = workReceiptsRevise.getAct().getTaskDefKey();
			List<User> users = null;
			if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("scyfglbzr",3,workReceiptsRevise.getOfficeId(),"7",workReceiptsRevise.getCreateBy());
			}else if ("scyfglbzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getProcessInstanceId(),2);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getProcessInstanceId(),1);
			}
			String flag = workReceiptsRevise.getAct().getFlag();
			if ("yes".equals(flag) &&(users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workReceiptsReviseService.auditSave(workReceiptsRevise,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "项目登记流程审批失败");
		}
		if (StringUtils.isNotBlank(workReceiptsRevise.getHome()) && "home".equals(workReceiptsRevise.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
		}
	}
	@RequestMapping(value = "inauditSaveAudit")
	public String inauditSaveAudit(WorkReceiptsRevise workReceiptsRevise, Model model,
							RedirectAttributes redirectAttributes) {
		try {

			String taskDefKey = workReceiptsRevise.getAct().getTaskDefKey();
			List<User> users = null;
			if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getInvalidProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("scyfglbzr",3,workReceiptsRevise.getOfficeId(),"7",workReceiptsRevise.getCreateBy());
			}else if ("scyfglbzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getProcessInstanceId(),2);
			}else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workReceiptsRevise.getProcessInstanceId(),1);
			}
			String flag = workReceiptsRevise.getAct().getFlag();
			if ("yes".equals(flag) &&(users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workReceiptsReviseService.invalidAuditSave(workReceiptsRevise,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "项目登记流程审批失败");
		}

		if (StringUtils.isNotBlank(workReceiptsRevise.getHome()) && "home".equals(workReceiptsRevise.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workreceiptsreviseinvalid/workReceiptsReviseInvalid/list";
		}
	}
	/**
	 * 删除收入调整
	 */
	@RequiresPermissions("workreceiptsrevise:workReceiptsRevise:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReceiptsRevise workReceiptsRevise, RedirectAttributes redirectAttributes) {
		workReceiptsReviseService.delete(workReceiptsRevise);
		addMessage(redirectAttributes, "删除收入调整成功");
		return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
	}
	@RequiresPermissions("workreceiptsrevise:workReceiptsRevise:del")
	@RequestMapping(value = "deleteInvalid")
	public String deleteInvalid(WorkReceiptsRevise workReceiptsRevise, RedirectAttributes redirectAttributes) {
		workReceiptsReviseService.deleteInvalid(workReceiptsRevise);
		addMessage(redirectAttributes, "删除收入调整作废记录成功");
		return "redirect:"+Global.getAdminPath()+"/workreceiptsreviseinvalid/workReceiptsReviseInvalid/list";
	}
	/**
	 * 批量删除收入调整
	 */
	@RequiresPermissions("workreceiptsrevise:workReceiptsRevise:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workReceiptsReviseService.delete(workReceiptsReviseService.get(id));
		}
		addMessage(redirectAttributes, "删除收入调整成功");
		return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workreceiptsrevise:workReceiptsRevise:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkReceiptsRevise workReceiptsRevise, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收入调整"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkReceiptsRevise> page = workReceiptsReviseService.findPage(new Page<WorkReceiptsRevise>(request, response, -1), workReceiptsRevise);
    		new ExportExcel("收入调整", WorkReceiptsRevise.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出收入调整记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
    }

	/**
	 * 导入Excel数据

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

	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkReceiptsRevise workReceiptsRevise,Model model) {
		model.addAttribute("processInstanceId", workReceiptsRevise.getProcessInstanceId());
		return "modules/workreceiptsrevise/workReceiptsReviseTrack";
	}
	@RequestMapping(value = "getInvalidProcessOne")
	public String getInvalidProcessOne(WorkReceiptsRevise workReceiptsRevise,Model model) {
		model.addAttribute("processInstanceId", workReceiptsRevise.getInvalidProcessInstanceId());
		return "modules/workreceiptsrevise/workReceiptsReviseTrack";
	}

	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkReceiptsRevise workReceiptsRevise,RedirectAttributes redirectAttributes){
		workReceiptsReviseService.cancelInvalidate(workReceiptsRevise);
		return "redirect:"+Global.getAdminPath()+"/workreceiptsrevise/workReceiptsRevise/?repage";
	}
	@RequestMapping("cancelInvalidateInvalid")
	public String cancelInvalidateInvalid(WorkReceiptsRevise workReceiptsRevise,RedirectAttributes redirectAttributes){
		workReceiptsReviseService.cancelInvalidateInvalid(workReceiptsRevise);
		return "redirect:"+Global.getAdminPath()+"/workreceiptsreviseinvalid/workReceiptsReviseInvalid/list";
	}
}