/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workitemcollar.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.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workincomingmessage.entity.WorkIncomingMessage;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollarCatalog;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollarItem;
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.workitemcollar.entity.WorkItemCollar;
import com.jeeplus.modules.workitemcollar.service.WorkItemCollarService;

/**
 * 领用管理Controller
 * @author chenyuping
 * @version 2018-07-16
 */
@Controller
@RequestMapping(value = "${adminPath}/workitemcollar/workItemCollar")
public class WorkItemCollarController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkItemCollarService workItemCollarService;

	@Autowired
	private ActTaskService actTaskService;
	@ModelAttribute
	public WorkItemCollar get(@RequestParam(required=false) String id) {
		WorkItemCollar entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workItemCollarService.get(id);
		}
		if (entity == null){
			entity = new WorkItemCollar();
		}
		return entity;
	}
	
	/**
	 * 领用申请列表页面
	 */
	@RequiresPermissions("workitemcollar:workItemCollar:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkItemCollar workItemCollar, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkItemCollar> page = workItemCollarService.findPage(new Page<WorkItemCollar>(request, response), workItemCollar); 
		model.addAttribute("page", page);
		return "modules/workitemcollar/workItemCollarList";
	}

	/**
	 * 查看，增加，编辑领用申请表单页面
	 */
	@RequiresPermissions(value={"workitemcollar:workItemCollar:view","workitemcollar:workItemCollar:add","workitemcollar:workItemCollar:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkItemCollar workItemCollar, Model model) {
		String flat=request.getParameter("tabId");
		if("1".equals(flat)){
			workItemCollar.setOfficeName(UserUtils.getSelectOffice().getTopCompany());
			workItemCollar.setOfficeId(UserUtils.getSelectOffice().getId());
			workItemCollar.setCompanyId(UserUtils.getSelectCompany().getId());
			workItemCollar.setLeader(UserUtils.getUser().getId());
			workItemCollar.setUser(UserUtils.getUser());
			workItemCollar.setUserName(UserUtils.getUser().getName());
		}
		List<WorkItemCollarCatalog> workItemCollarCatalogList=workItemCollarService.findWorkItemCollarCatalogList(workItemCollar);
		workItemCollar.setWorkItemCollarCatalogList(workItemCollarCatalogList);
		List<WorkItemCollarItem> workItemCollarItem=workItemCollarService.findWorkItemCollarItemList(workItemCollar);
		workItemCollar.setWorkItemCollarItemList(workItemCollarItem);
		model.addAttribute("workItemCollar", workItemCollar);
		return "modules/workitemcollar/workItemCollarForm";
	}

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

	/**
	 * 导入Excel数据

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


	/**
	 * 查看，增加，编辑收文管理表单页面
	 */
	@RequiresPermissions(value={"workitemcollar:workItemCollar:view"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkItemCollar workItemCollar, Model model) {
		List<WorkItemCollarCatalog> workItemCollarCatalogList=workItemCollarService.findWorkItemCollarCatalogList(workItemCollar);
		workItemCollar.setWorkItemCollarCatalogList(workItemCollarCatalogList);
		List<WorkItemCollarItem> workItemCollarItem=workItemCollarService.findWorkItemCollarItemList(workItemCollar);
		workItemCollar.setWorkItemCollarItemList(workItemCollarItem);
		model.addAttribute("workItemCollar", workItemCollar);
		return "modules/workitemcollar/workItemCollarView";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkItemCollar workItemCollar, Model model,
							RedirectAttributes redirectAttributes) {
		String taskDefKey = workItemCollar.getAct().getTaskDefKey();
		List<User> users = null;
		if ("ywbzr".equals(taskDefKey)){
			users = UserUtils.getByProssType(workItemCollar.getProcessInstanceId(),2);
			if (users==null )
			users = UserUtils.getByRoleActivityEnname("xzzg",3,workItemCollar.getOfficeId(),"17",workItemCollar.getCreateBy());
		}else  if ("modifyApply".equals(taskDefKey)){
			if(workItemCollarService.isAssets(workItemCollar)){
				users = UserUtils.getByProssType(workItemCollar.getProcessInstanceId(),1);
				if (users==null )
				users = UserUtils.getByRoleActivityEnname("bmzr",2,workItemCollar.getOfficeId(),"17",workItemCollar.getCreateBy());
			}else {
				users = UserUtils.getByProssType(workItemCollar.getProcessInstanceId(),2);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("xzzg",3,workItemCollar.getOfficeId(),"17",workItemCollar.getCreateBy());
			}
		}else  if ("xzzg".equals(taskDefKey)){
			users = UserUtils.getByProssType(workItemCollar.getProcessInstanceId(),2);
			if (users==null )
				users = UserUtils.getByRoleActivityEnname("xzzg",3,workItemCollar.getOfficeId(),"17",workItemCollar.getCreateBy());
		}
		String flag = workItemCollar.getAct().getFlag();
		if ("yes".equals(flag) && (users==null || users.size()==0)){
			addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
		}else {
			String str = workItemCollarService.auditSave(workItemCollar,users);
			addMessage(redirectAttributes, str);
		}
		if (StringUtils.isNotBlank(workItemCollar.getHome()) && "home".equals(workItemCollar.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:" + Global.getAdminPath() + "/workitemcollar/workItemCollar/?repage";
		}
	}
	//	审批页面
	@RequestMapping(value = "audit")
	public String workContractInfoAudit(Act act, WorkItemCollar workItemCollar, 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())) {
			workItemCollar.setAct(act);
			model.addAttribute("processInstanceId", workItemCollar.getProcessInstanceId());
		}
		List<WorkItemCollarCatalog> workItemCollarCatalogList=workItemCollarService.findWorkItemCollarCatalogList(workItemCollar);
		workItemCollar.setWorkItemCollarCatalogList(workItemCollarCatalogList);
		List<WorkItemCollarItem> workItemCollarItem=workItemCollarService.findWorkItemCollarItemList(workItemCollar);
		workItemCollar.setWorkItemCollarItemList(workItemCollarItem);
		model.addAttribute("workItemCollar", workItemCollar);
		return "modules/workitemcollar/workItemCollarAudit";
	}

	@RequiresPermissions(value={"workitemcollar:workItemCollar:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkItemCollar workItemCollar, Model model, RedirectAttributes redirectAttributes) {
		workItemCollar=workItemCollarService.get(workItemCollar.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workItemCollar.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);
			workItemCollar.setAct(act);
		}
		List<WorkItemCollarCatalog> workItemCollarCatalogList=workItemCollarService.findWorkItemCollarCatalogList(workItemCollar);
		workItemCollar.setWorkItemCollarCatalogList(workItemCollarCatalogList);
		List<WorkItemCollarItem> workItemCollarItem=workItemCollarService.findWorkItemCollarItemList(workItemCollar);
		workItemCollar.setWorkItemCollarItemList(workItemCollarItem);
		model.addAttribute("workItemCollar", workItemCollar);
		return "modules/workitemcollar/workItemCollarModifyApply";
	}


	@RequestMapping(value = "getProcess")
	public String getProcess(WorkItemCollar workItemCollar, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workItemCollar.getProcessInstanceId());
		return "modules/workitemcollar/workItemCollarTask";
	}

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