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

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
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.ActTaskService;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.oa.entity.OaNotifyRecord;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
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.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
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.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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
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 java.io.IOException;
import java.util.*;

/**
 * 通知通告Controller
 * @author jeeplus
 * @version 2014-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/oaNotify")
public class OaNotifyController extends BaseController {

	@Autowired
	private OaNotifyService oaNotifyService;
    @Autowired
    private ActTaskService actTaskService;
	@Autowired
	private PushinfoService pushinfoService;
	
	@ModelAttribute
	public OaNotify get(@RequestParam(required=false) String id) {
		OaNotify entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = oaNotifyService.get(id);
		}
		if (entity == null){
			entity = new OaNotify();
		}
		return entity;
	}
	//我的通告
	@RequestMapping(value = {"self"})
	public String listMyself(OaNotify oaNotify, HttpServletRequest request, HttpServletResponse response, Model model) {
		oaNotify.setSelf(true);
		Page<OaNotify> page = oaNotifyService.findMyself(new Page<OaNotify>(request, response), oaNotify);
		List<OaNotify> list = page.getList();
		for (OaNotify notify:list){
			if (StringUtils.isNotBlank(notify.getContent())){
				notify.setContent(notify.getContent().replace("\n",""));
			}
		}
		model.addAttribute("page", page);
		return "modules/oa/oaNotifyListMyself";
	}
	//通告管理
	@RequiresPermissions("oa:oaNotify:list")
	@RequestMapping(value = {"list", ""})
	public String list(OaNotify oaNotify, HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		User user = UserUtils.getUser();
		/*if(!UserUtils.isManager()){
			addMessage(redirectAttributes,"您在本公司非管理员，只能查看'我的通告'");
			String returnView = "redirect:" + adminPath + "/oa/oaNotify/self" ;
			return returnView;
		}*/
		if(!user.isAdmin()){
			oaNotify.setCompany(user.getCompany());
		}
		Page<OaNotify> page = oaNotifyService.findByPc(new Page<OaNotify>(request, response), oaNotify);
		model.addAttribute("page", page);
		return "modules/oa/oaNotifyList";
	}

	/**
	 * 查看，增加，编辑报告表单页面
	 */
	@RequiresPermissions(value={"oa:oaNotify:view","oa:oaNotify:add","oa:oaNotify:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(@RequestParam(value = "view",required = false)String view, OaNotify oaNotify, Model model) {
		if (StringUtils.isNotBlank(oaNotify.getId())){
			oaNotify = oaNotifyService.getRecordList2(oaNotify);
            oaNotifyService.queryDetails(oaNotify);
		}
		if (oaNotify.getCreateDate() == null){
			oaNotify.setCreateDate(new Date());
		}
		if (oaNotify.getCreateBy() == null || StringUtils.isBlank(oaNotify.getCreateBy().getId())){
			oaNotify.setCreateBy(UserUtils.getUser());
		}
		if(oaNotify.getOffice() == null || StringUtils.isBlank(oaNotify.getOffice().getId())){
            oaNotify.setOffice(UserUtils.getSelectOffice());
        }
		oaNotify.setContent("");
		model.addAttribute("oaNotify", oaNotify);
		if(StringUtils.isNotBlank(view)&& "view".equals(view)){
			return "modules/oa/oaNotifyView";
		}
		return "modules/oa/oaNotifyForm";
	}

	/**
	 * 删除附件
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("delFile")
	@ResponseBody
	public AjaxJson delFile(OaNotify oaNotify, HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		String attaId = request.getParameter("attaId");
		String attachmentUrl = request.getParameter("attachmentUrl");
		oaNotifyService.delFile(attaId,attachmentUrl);
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("attachmentUrl",attachmentUrl);
		return ajaxJson;
	}

    /**
     * 暂存
     * @param oaNotify
     * @param model
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"oa:oaNotify:add","oa:oaNotify:edit"},logical=Logical.OR)
    @RequestMapping(value = "tstore")
    public String tstore(OaNotify oaNotify, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, oaNotify)){
            return form("",oaNotify, model);
        }
        oaNotify.setStatus(String.valueOf(ProjectStatusEnum.TSTORE.getValue()));
        if(!oaNotify.getIsNewRecord()){//编辑表单保存
            OaNotify t = oaNotifyService.get(oaNotify.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(oaNotify, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            oaNotifyService.save(t);//保存
        }else{//新增表单保存
            oaNotifyService.save(oaNotify);//保存
        }
        addMessage(redirectAttributes, "暂存公告成功");
        return "redirect:"+ Global.getAdminPath()+"/oa/oaNotify/?repage";
    }

	//添加操作只在"通告管理"页面完成；
	@RequiresPermissions(value={"oa:oaNotify:add","oa:oaNotify:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(OaNotify oaNotify, Model model,RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, oaNotify)){
            return form("",oaNotify, model);
        }

        oaNotify.setState(String.valueOf(ProjectStatusEnum.IN_APRL.getValue()));
        String str = "";
        if(!oaNotify.getIsNewRecord()){//编辑表单保存
            OaNotify t = oaNotifyService.get(oaNotify.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(oaNotify, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            str = oaNotifyService.saveNotify(t);//保存
        }else{//新增表单保存
            str = oaNotifyService.saveNotify(oaNotify);//保存
        }
        if (StringUtils.isNotBlank(str)){
            addMessage(redirectAttributes, "保存公告失败:"+str);
        }else {
            addMessage(redirectAttributes, "保存公告成功");
        }

		return "redirect:" + adminPath + "/oa/oaNotify/?repage";
	}

	//删除只在"通告管理"页面操作，管理员完成;"我的通告"页面不提供删除修改操作；
	@RequiresPermissions("oa:oaNotify:del")
	@RequestMapping(value = "delete")
	public String delete(OaNotify oaNotify, RedirectAttributes redirectAttributes) {
		//oaNotifyService.delete(oaNotify);
		oaNotifyService.deleteByOaNotifyId(oaNotify.getId());
		oaNotify.setRemarks("关闭");
		oaNotifyService.save(oaNotify);
		pushinfoService.updateDelflagByPushId(oaNotify.getId(),"1");
		addMessage(redirectAttributes, "关闭通知成功");
		return "redirect:" + adminPath + "/oa/oaNotify/list?repage";
	}

    @RequiresPermissions("oa:oaNotify:del")
    @RequestMapping(value = "logicDelete")
    public String logicDelete(OaNotify oaNotify, RedirectAttributes redirectAttributes) {
        String sta = oaNotify.getStatus();
        if("5".equals(sta)|| "2".equals(sta)){
            if("5".equals(sta)){
                addMessage(redirectAttributes, "公告信息已审批通过，无法删除");
                return "redirect:"+Global.getAdminPath()+"/oa/oaNotify/list?repage";
            }else{
                addMessage(redirectAttributes, "公告信息正在审核中，无法删除");
                return "redirect:"+Global.getAdminPath()+"/oa/oaNotify/list?repage";
            }
        }
        oaNotifyService.logicDelete(oaNotify);
        addMessage(redirectAttributes, "删除公告成功");
        return "redirect:"+Global.getAdminPath()+"/oa/oaNotify/list?repage";
    }

	//删除只在"通告管理"页面操作，管理员完成;"我的通告"页面不提供删除修改操作；
	@RequiresPermissions("oa:oaNotify:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			oaNotifyService.delete(oaNotifyService.get(id));
		}
		addMessage(redirectAttributes, "删除通知成功");
		return "redirect:" + adminPath + "/oa/oaNotify/list?repage";
	}
	
	/**
	 * 我的通知列表
	 */
//	@RequestMapping(value = "self")
//	public String selfList(OaNotify oaNotify, HttpServletRequest request, HttpServletResponse response, Model model) {
//		User user = UserUtils.getUser();
//		if(!user.isAdmin()){
//			oaNotify.setSelf(true);
//			oaNotify.setCompany(user.getCompany());
//			oaNotify.setCreateBy(user);
//			oaNotify.setCurrentUser(user);
//		}
//		Page<OaNotify> page = oaNotifyService.find(new Page<OaNotify>(request, response), oaNotify);
//		model.addAttribute("page", page);
//		return "modules/oa/oaNotifyList";
//	}
//

	/**
	 * 我的通知列表-数据
	 */
	@RequiresPermissions("oa:oaNotify:view")
	@RequestMapping(value = "selfData")
	@ResponseBody
	public Page<OaNotify> listData(OaNotify oaNotify, HttpServletRequest request, HttpServletResponse response, Model model) {
		oaNotify.setSelf(true);
		Page<OaNotify> page = oaNotifyService.find(new Page<OaNotify>(request, response), oaNotify);
		return page;
	}
	
	/**
	 * 查看我的通知,重定向在当前页面打开
	 * (在查看时打开view方法就是改变阅读状态而不显示；在查看时打开form方法就是可以看到所有已阅未阅情况)
	 */
	@RequestMapping(value = "view")
	public String view(@RequestParam(value = "readAttr",required = false)String readAttr, OaNotify oaNotify, Model model) {
		if (StringUtils.isNotBlank(oaNotify.getId())){
			oaNotifyService.updateReadFlag(oaNotify);
			UserUtils.pushMeIm("");
			/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(UserUtils.getUser().getId());
			for (WebSocket toUserConn : toUserConns) {
				String message = "{\"useType\":\"sys_me\"}";
				ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
			}*/
			oaNotify = oaNotifyService.getRecordList(oaNotify);
			oaNotifyService.getUsers(oaNotify);
			oaNotifyService.getOffices(oaNotify);
			model.addAttribute("toReadMyNotify",true);
			model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
			model.addAttribute("oaNotify", oaNotify);
			return "modules/oa/oaNotifyView";
		}
		return "redirect:" + adminPath + "/oa/oaNotify/self?repage";

	}

	/**
	 * 查看我的通知-数据
	 */
	@RequestMapping(value = "viewData")
	@ResponseBody
	public OaNotify viewData(OaNotify oaNotify, Model model) {
		if (StringUtils.isNotBlank(oaNotify.getId())){
			oaNotifyService.updateReadFlag(oaNotify);
			return oaNotify;
		}
		return null;
	}
	
	/**
	 * 查看我的通知-发送记录
	 */
	@RequestMapping(value = "viewRecordData")
	@ResponseBody
	public OaNotify viewRecordData(OaNotify oaNotify, Model model) {
		if (StringUtils.isNotBlank(oaNotify.getId())){
			oaNotify = oaNotifyService.getRecordList(oaNotify);
			return oaNotify;
		}
		return null;
	}
	
	/**
	 * 获取我的通知数目
	 */
	@RequestMapping(value = "self/count")
	@ResponseBody
	public String selfCount(OaNotify oaNotify, Model model) {
		oaNotify.setSelf(true);
		oaNotify.setReadFlag("0");
		return String.valueOf(oaNotifyService.findCount(oaNotify));
	}

    //	审批页面
    @RequestMapping(value = "audit")
    public String workContractInfoAudit(Act act, OaNotify oaNotify, Model model) {
        if(StringUtils.isNotBlank(oaNotify.getId())){
            oaNotifyService.queryDetails(oaNotify);
        }
        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())) {
            oaNotify.setAct(act);
            model.addAttribute("processInstanceId", oaNotify.getProcessInstanceId());
        }
        model.addAttribute("oaNotify", oaNotify);
        return "modules/oa/oaNotifyAudit";
    }

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(OaNotify oaNotify, Model model,
                            RedirectAttributes redirectAttributes) {
        try {
            List<User> users = UserUtils.getByProssType(oaNotify.getProcessInstanceId(),1);
            String flag = oaNotify.getAct().getFlag();
            if ("yes".equals(flag) && (users==null || users.size()==0)){
                addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
            }else {
                String str = oaNotifyService.auditSave(oaNotify, users);
                addMessage(redirectAttributes, str);
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "公告流程审批失败");
        }

        if (StringUtils.isNotBlank(oaNotify.getHome()) && "home".equals(oaNotify.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/oa/oaNotify/list?repage";
        }
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(OaNotify oaNotify, Model model, HttpServletRequest request){
        model.addAttribute("processInstanceId", oaNotify.getProcessInstanceId());
        return "modules/worksendmessage/workSendMessageTask";
    }

    @RequiresPermissions(value={"oa:oaNotify:edit"},logical=Logical.OR)
    @RequestMapping(value = "modify")
    public String modify(OaNotify oaNotify, Model model,RedirectAttributes redirectAttributes) {
        oaNotify=oaNotifyService.get(oaNotify.getId());
        if(StringUtils.isNotBlank(oaNotify.getId())){
            oaNotifyService.queryDetails(oaNotify);
        }
        ProcessInstance processInstance = actTaskService.getProcIns(oaNotify.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);
            oaNotify.setAct(act);
        }

        model.addAttribute("oaNotify", oaNotify);
        return "modules/oa/oaNotifyModifyApply";
    }

    @RequiresPermissions(value={"oa:oaNotify: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 {
            OaNotify oaNotify = oaNotifyService.get(id);
            if("5".equals(oaNotify.getStatus())){
                addMessage(redirectAttributes, "公告信息已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/oa/oaNotify/list?repage";
            }
            oaNotifyService.cancelProcess(oaNotify);
            addMessage(redirectAttributes, "撤回该公告审批成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该公告审批失败");
        }
        return "redirect:" + Global.getAdminPath() + "/oa/oaNotify/list?repage";
    }
}