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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActAuditService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.oaall.entity.OaAll;
import com.jeeplus.modules.oaall.service.OaAllService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.java_websocket.WebSocket;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用审批功能Controller
 * @author mpb
 * @version 2018-01-11
 */
@Controller
@RequestMapping(value = "${adminPath}/oaall/oaAll")
public class OaAllController extends BaseController {

	@Autowired
	private OaAllService oaAllService;
	@Autowired
	private ApprovalCopyService approvalCopyService;
	@Autowired
	private PushinfoService pushinfoService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActAuditService actAuditService;
	
	@ModelAttribute
	public OaAll get(@RequestParam(required=false) String id) {
		OaAll entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = oaAllService.get(id);
		}
		if (entity == null){
			entity = new OaAll();
		}
		return entity;
	}
	
	/**
	 * 通用审批功能列表页面
	 */
	@RequiresPermissions("oaall:oaAll:list")
	@RequestMapping(value = {"list", ""})
	public String list(OaAll oaAll, HttpServletRequest request, HttpServletResponse response, Model model) {
		oaAll.setOfficeId(UserUtils.getSelectOffice().getId());
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			oaAll.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				oaAll.setCreateBy(user);
			}
		}
		Page<OaAll> page = oaAllService.findPage(new Page<OaAll>(request, response), oaAll);
		model.addAttribute("page", page);
		return "modules/oaall/oaAllList";
	}

	/**
	 * 查看，增加，编辑通用审批功能表单页面
	 */
	@RequiresPermissions(value={"oaall:oaAll:view","oaall:oaAll:add","oaall:oaAll:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(OaAll oaAll, Model model,HttpServletRequest request) {
		String view = "oaAllForm";
		String tabId = request.getParameter("tabId");
		if("0".equals(tabId)){
			view = "oaAllView";
		}
		// 环节编号
		String taskDefKey = oaAll.getAct().getTaskDefKey();
		// 审核环节
		if ("audit1".equals(taskDefKey)){
			if (org.apache.commons.lang3.StringUtils.isBlank(oaAll.getAct().getStatus())){
				model.addAttribute("disabled","true");
				oaAll.getAct().setProcInsId(oaAll.getProcessInstanceId());
			}else {
				model.addAttribute("disabled","false");
			}
			view = "oaAllAudit";
		}else if ("apply_end".equals(taskDefKey)){
			view = "oaAllAudit";
		}
		//
		else if ("modifyApply".equals(taskDefKey)){
			view = "oaAllForm";
		}

		model.addAttribute("oaAll", oaAll);
		return "modules/oaall/" + view;
	}

	/**
	 * 保存通用审批功能
	 */
	@RequiresPermissions(value={"oaall:oaAll:add","oaall:oaAll:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(OaAll oaAll, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (StringUtils.isNotBlank(oaAll.getId())) {
			OaAll t = oaAllService.get(oaAll.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(oaAll, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				oaAllService.save(t);
			}
		} else {
			try {
				oaAll.setStatus("1");
				String approverId = "";
				List<String> adds = oaAll.getAdds();
				for(int i = 0;i<adds.size();i++){
					if(i + 1 == adds.size()){
						approverId += adds.get(i);
					}else{
						approverId += adds.get(i) + ",";
					}
				}
				oaAll.setIds(approverId);

				Map<String, Object> variables = Maps.newHashMap();
				String alias = "1";
				List<String> assigneeList = new ArrayList<String>(); //分配任务的人员
				if (approverId != null && !approverId.equals("")) {
					if (!UserUtils.getUser().isAdmin() && approverId.contains(UserUtils.getUser().getId())) {
						logger.error("启动通用审批失败：");
						addMessage(redirectAttributes, "申请失败,审批人不能为本人！");
						return "redirect:" + adminPath + "/oaall/oaAll";
					}
					String[] approverIds = approverId.split(",");
					for (int i = 0; i < approverIds.length; i++) {
						assigneeList.add(approverIds[i]);
					}
					alias = approverIds[0];
				}
				variables.put("assigneeList", assigneeList);
				variables.put("count", assigneeList.size());
				User CC = new User();
				CC.setId(oaAll.getCCId());
				User user = UserUtils.getUser();
				oaAll.setUser(user);
				oaAll.setCreateBy(user);
				oaAll.setUpdateBy(user);
				oaAll.setStatus("1");
				oaAll.setDelFlag("0");
				oaAll.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
				oaAll.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
				oaAllService.save(oaAll, variables);
				ApprovalCopy approvalCopy = new ApprovalCopy();
				approvalCopy.setCCId(oaAll.getCCId());
				approvalCopy.setUserId(user.getId());
				approvalCopy.setType("allApprove");
				approvalCopy.setApprovalId(oaAll.getId());
				approvalCopy.setApproverId(approverId);
				approvalCopy.setReadFlag("0");
				approvalCopyService.save(approvalCopy);

				//给抄送人、审批人发送通知
				if(approvalCopy!=null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())){
					String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
					String shenpiIds = alias;//给审批流程的第一个人发送通知
					oaAllService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
					UserUtils.pushIm(alias,"申请人 "+user.getName() + ",通用审批申请 待审批!");
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(alias);
					for (WebSocket toUserConn:toUserConns) {
						String message = "{\"to\":\""+alias+"\"," +
								"\"msg\":\"审批信息 申请人:" + user.getName() + ",通用审批申请 待审批!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
				}


				//推送
				String title = "审批";
				String content = UserUtils.getUser().getName() + "的通用审批申请需要你审批";
				String status = "待审批";
				String remarks = "通用审批申请内容类型：" + oaAll.getApplyContent();
				Map extras = new HashMap();
				extras.put("type", "4001");
				extras.put("id", oaAll.getId());
				extras.put("procDefKey", "oaApprove");

				boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
				Pushinfo pushinfo = new Pushinfo();
				pushinfo.setCurrentUser(UserUtils.getUser());
				pushinfo.setRemarks(remarks);
				pushinfo.setUserId(UserUtils.getUser().getId());
				pushinfo.setType("4001");
				pushinfo.setPushId(oaAll.getId());
				pushinfo.setTitle(title);
				pushinfo.setContent(content);
				pushinfo.setStatus(status);
				pushinfo.setAddcontent("allApprove");
				pushinfo.setPushUserId(alias);
				pushinfo.setParentType("singleApproval");
				pushinfo.setMobile("ios,android");
				pushinfo.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
				pushinfoService.save(pushinfo);
				if (b) {
					addMessage(redirectAttributes, "通用审批申请已经提交");
				} else {
					logger.error("启动通用审批申请流程失败：");
					addMessage(redirectAttributes, "请假申请失败,通用审批申请推送失败！");
					return "redirect:" + adminPath + "/oaall/oaAll";
				}
			} catch (Exception e) {
				logger.error("启动通用审批流程失败：", e);
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/oaall/oaAll/?repage";
	}
	
	/**
	 * 删除通用审批功能
	 */
	@RequiresPermissions("oaall:oaAll:del")
	@RequestMapping(value = "delete")
	public String delete(OaAll oaAll, RedirectAttributes redirectAttributes) {
		oaAllService.delete(oaAll);
		addMessage(redirectAttributes, "删除通用审批功能成功");
		return "redirect:"+Global.getAdminPath()+"/oaall/oaAll/?repage";
	}
	
	/**
	 * 批量删除通用审批功能
	 */
	@RequiresPermissions("oaall:oaAll:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			oaAllService.delete(oaAllService.get(id));
		}
		addMessage(redirectAttributes, "删除通用审批功能成功");
		return "redirect:"+Global.getAdminPath()+"/oaall/oaAll/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("oaall:oaAll:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(OaAll oaAll, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "通用审批功能"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<OaAll> page = oaAllService.findPage(new Page<OaAll>(request, response, -1), oaAll);
    		new ExportExcel("通用审批功能", OaAll.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出通用审批功能记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oaall/oaAll/?repage";
    }

	/**
	 * 导入Excel数据

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


	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(OaAll oaAll, Model model) {
		//oaAllService.auditSave(oaAll);
		Act act = oaAll.getAct();
		actAuditService.saveAudit(act, act.getProcInsId(), "allApprove", oaAll.getAct().getComment(), oaAll.getId(), "2");
		if (oaAll!=null && org.apache.commons.lang3.StringUtils.isNotBlank(oaAll.getHome()) && oaAll.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/oa/leave";
	}


	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"leaveTodoList"})
	public String leaveTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("allApprove");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<OaAll> lists = new ArrayList<OaAll>();
		for (Act a : list) {
			OaAll oaAll = oaAllService.getByProcessInstanceId(a.getProcInsId());
			if (oaAll != null && oaAll.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
					if (user!=null) {
						a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
					}
				}
				oaAll.setAct(a);
//				if (com.jeeplus.common.utils.StringUtils.isNotBlank(oaAll.getId())){
//					oaAll.setName(officeService.get(oaAll.getCompanyId()).getName());
//				}
				lists.add(oaAll);
			}
		}
		model.addAttribute("list", lists);
		return "modules/oaall/oaAllTodoList";
	}


	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"leaveHistoricList"})
	public String leaveHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("allApprove");
		Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
		List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<OaAll> lists = new ArrayList<OaAll>();
		for (Act a : list) {
			OaAll oaAll = oaAllService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (oaAll != null && oaAll.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				oaAll.setAct(a);
//				if (StringUtils.isNotBlank(a.getId())){
//					oaAll.setName(officeService.get(oaAll.getCompanyId()).getName());
//				}
//				if (oaAll.getCreateDate()!=null){
//					oaAll.setTime(sdf.format(oaAll.getCreateDate()));
//				}
				lists.add(oaAll);
			}
		}
		model.addAttribute("list", lists);
		return "modules/oaall/oaAllHistoricList";
	}
	/**
	 * 审核企业信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		//String formKey = "/oa/leave/applyOnLeave";
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(OaAll oaAll, Model model) {
		model.addAttribute("processInstanceId", oaAll.getProcessInstanceId());
		return "modules/oaall/oaAllTrack";

	}

	/**
	 * 请假申请撤销
	 * @param
	 * @return
	 */
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, HttpServletResponse response) {

		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		AjaxJson j = new AjaxJson();
		try {
			OaAll oaAll = oaAllService.getById(id);
			oaAll.setStatus("5");
			oaAll.preUpdate();
			oaAllService.update(oaAll);
			Map map = oaAllService.getLeaveById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, "");
			j.setMsg("撤销申请成功");

			//撤销后，更改所有发送过的通知的阅读状态
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(oaAll.getId());
			workProjectNotifyService.readByNotifyId(notify);
		}catch (Exception e){
			j.setErrorCode("101");
			logger.info(e.getMessage());
			j.setMsg("撤销申请失败");
			j.setSuccess(false);
		}
		return "redirect:" + adminPath + "/oaall/oaAll?repage";
	}
}