/**
 * There are <a href="http://www.jeeplus.org/">jeeplus</a> code generation
 */
package com.jeeplus.modules.oa.web;

import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.MyBeanUtils;
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.oa.entity.Leave;
import com.jeeplus.modules.oa.service.LeaveService;
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.service.OfficeService;
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.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.java_websocket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假Controller
 * @author liuj
 * @version 2013-04-05
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/leave")
public class LeaveController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected LeaveService leaveService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private ApprovalCopyService approvalCopyService;

	@Autowired
	private PushinfoService pushinfoService;

	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActAuditService actAuditService;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@ModelAttribute
	public Leave get(@RequestParam(required=false) String id){//,
//			@RequestParam(value="act.procInsId", required=false) String procInsId) {
		Leave leave = null;
		if (StringUtils.isNotBlank(id)){
			leave = leaveService.get(id);
//		}else if (StringUtils.isNotBlank(procInsId)){
//			testAudit = testAuditService.getByProcInsId(procInsId);
		}
		if (leave == null){
			leave = new Leave();
		}
		return leave;
	}


	@RequiresPermissions(value={"oa:leave:view","oa:leave:add","oa:leave:edit"},logical= Logical.OR)
	@RequestMapping(value = {"form"})
	public String form(Leave leave, Model model) {
		String view = "leaveForm";
		// 查看审批申请单
		if (StringUtils.isNotBlank(leave.getId())){//.getAct().getProcInsId())){

			// 环节编号
			String taskDefKey = leave.getAct().getTaskDefKey();
			if (taskDefKey!=null){
				// 查看工单
				if(leave.getAct().isFinishTask()){
					view = "leaveView";
				}
				// 修改环节
				else if ("apply_end".equals(taskDefKey)){
					view = "leaveAudit";
				}
				// 审核环节
				else if ("audit1".equals(taskDefKey)){
					if (StringUtils.isBlank(leave.getAct().getStatus())){
						model.addAttribute("disabled","true");
						leave.getAct().setProcInsId(leave.getProcessInstanceId());
					}else {
						model.addAttribute("disabled","false");
					}
					view = "leaveAudit";
				}
				//
				else if ("modifyApply".equals(taskDefKey)){
					view = "leaveForm";
				}
			}
			if (StringUtils.isNotBlank(leave.getName())){
				if (leave.getName().equals("view")){
					model.addAttribute("disabled","true");
					leave.getAct().setProcInsId(leave.getProcessInstanceId());
					view = "leaveAudit";
				}
			}
		}

		model.addAttribute("leave", leave);
		return "modules/oa/"+view;
	}

	/**
	 * 启动请假流程
	 * @param leave
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(Leave leave, @RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files, RedirectAttributes redirectAttributes) throws Exception{
		if (StringUtils.isNotBlank(leave.getId())) {
			Leave t = leaveService.get(leave.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(leave, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				leaveService.save(t);
			}
		} else {
			try {
				leave.setStatus("1");
				String approverId = "";
				List<String> adds = leave.getAdds();
				for(int i = 0;i<adds.size();i++){
					if(i + 1 == adds.size()){
						approverId += adds.get(i);
					}else{
						approverId += adds.get(i) + ",";
					}
				}
				leave.setIds(approverId);

				String type = "1";
				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 + "/oa/leave";
					}
					String[] approverIds = approverId.split(",");
					for (int i = 0; i < approverIds.length; i++) {
						assigneeList.add(approverIds[i]);
					}
					type = approverIds.length + "";
					alias = approverIds[0];
				}
				variables.put("assigneeList", assigneeList);
				variables.put("count", assigneeList.size());
				User CC = new User();
				CC.setId(leave.getCCId());
				User user = UserUtils.getUser();
				leave.setUser(user);
				leave.setCreateBy(user);
				leave.setUpdateBy(user);
				leave.setStatus("1");
				leave.setDelFlag("0");
				leave.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
				leave.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
				leaveService.save(leave, variables, type);

				if(this_upload_files!=null&&this_upload_files.length>0){
					OSSClientUtil ossClientUtil = new OSSClientUtil();
					for (int i = 0; i < this_upload_files.length; i++) {
						MultipartFile file = this_upload_files[i];
						if(file!=null && !file.isEmpty()&& file.getSize()>0){
							leaveService.uploadFile(ossClientUtil,file,leave,"71");
						}
					}
				}



				ApprovalCopy approvalCopy = new ApprovalCopy();
				approvalCopy.setCCId(leave.getCCId());
				approvalCopy.setUserId(user.getId());
				approvalCopy.setType("leave");
				approvalCopy.setApprovalId(leave.getId());
				approvalCopy.setRemarks(leave.getReason());
				approvalCopy.setApproverId(approverId);
				approvalCopy.setReadFlag("0");
				approvalCopyService.save(approvalCopy);

				//给抄送人、审批人发送通知
				if(approvalCopy!=null && StringUtils.isNotBlank(approvalCopy.getId())){
					String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
					String shenpiIds = alias;//给审批流程的第一个人发送通知
					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);//同时向本人发送消息
					}*/
					leaveService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
				}


				//推送
				String title = "审批";
				String content = UserUtils.getUser().getName() + "的请假申请需要你审批";
				String status = "待审批";
				String leaveType = leave.getLeaveType();
				if (leaveType.equals("1")) {
					//1:事假、2:病假、3:调休、4:年假、5:婚假、6:产假、7:其他
					leaveType = "事假";
				} else if (leaveType.equals("2")) {
					leaveType = "病假";
				} else if (leaveType.equals("3")) {
					leaveType = "调休";
				} else if (leaveType.equals("4")) {
					leaveType = "年假";
				} else if (leaveType.equals("5")) {
					leaveType = "婚假";
				} else if (leaveType.equals("6")) {
					leaveType = "产假";
				} else if (leaveType.equals("7")) {
					leaveType = "其他";
				}
				String remarks = "请假类型：" + leaveType + "\n"
						+ "开始时间：" + leave.getStartTime() + "\n"
						+ "结束时间：" + leave.getEndTime();
				Map extras = new HashMap();
				extras.put("type", "4001");
				extras.put("id", leave.getId());
				extras.put("procDefKey", "leave");

				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(leave.getId());
				pushinfo.setTitle(title);
				pushinfo.setContent(content);
				pushinfo.setStatus(status);
				pushinfo.setAddcontent("leave");
				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 + "/oa/leave";
				}
			} catch (Exception e) {
				logger.error("启动请假流程失败：", e);
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:" + adminPath + "/oa/leave";
	}


	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(Leave leave,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (StringUtils.isBlank(leave.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(leave, model);
		}*/
		//leaveService.auditSave(leave);
		Act act = leave.getAct();
		AjaxJson json = actAuditService.saveAudit(act, act.getProcInsId(), "leave", leave.getAct().getComment(), leave.getId(), "2");
		addMessage(redirectAttributes, json.getMsg());
		if (leave!=null && StringUtils.isNotBlank(leave.getHome()) && leave.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/oa/leave";
	}

	/**
	 * 任务列表
	 * @param leave
	 */
	/*@RequestMapping(value = {"list/task",""})
	public String taskList(HttpSession session, Model model) {
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());
		List<Leave> results = leaveService.findTodoTasks(userId);
		model.addAttribute("leaves", results);
		return "modules/oa/leaveTask";
	}*/

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequiresPermissions("oa:leave:list")
	@RequestMapping(value = {"list", ""})
	public String list(Leave leave, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			leave.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				leave.setCreateBy(user);
			}
		}
		Page<Leave> page = leaveService.find(new Page<Leave>(request, response), leave);
		model.addAttribute("page", page);
		return "modules/oa/leaveList";
	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"leaveTodoList"})
	public String leaveTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("leave");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Leave> lists = new ArrayList<Leave>();
		for (Act a : list) {
			Leave leave = leaveService.getByProcessInstanceId(a.getProcInsId());
			if (leave != null && leave.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());
					}
				}
				leave.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(leave.getId())){
					leave.setName(officeService.get(leave.getCompanyId()).getName());
				}
				lists.add(leave);
			}
		}
		model.addAttribute("list", lists);
		return "modules/oa/leaveTodoList";
	}

	/**
	 * 已办任务
	 * @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("leave");
		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<Leave> lists = new ArrayList<Leave>();
		for (Act a : list) {
			Leave leave = leaveService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (leave != null && leave.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				leave.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(a.getId())){
					leave.setName(officeService.get(leave.getCompanyId()).getName());
				}
				if (leave.getCreateDate()!=null){
					leave.setTime(sdf.format(leave.getCreateDate()));
				}
				lists.add(leave);
			}
		}
		model.addAttribute("list", lists);
		/*List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Act> lists = new ArrayList<Act>();
		for (Act a : list) {
			Leave leave = leaveService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (leave != null && leave.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				lists.add(a);
			}
		}
		model.addAttribute("list", lists);*/

		return "modules/oa/leaveHistoricList";
	}

	/**
	 * 审核企业信息
	 * @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);
	}

	/**
	 * 读取详细数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "detail/{id}")
	@ResponseBody
	public String getLeave(@PathVariable("id") String id) {
		Leave leave = leaveService.get(id);
		return JsonMapper.getInstance().toJson(leave);
	}

	/**
	 * 读取详细数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "detail-with-vars/{id}/{taskId}")
	@ResponseBody
	public String getLeaveWithVars(@PathVariable("id") String id, @PathVariable("taskId") String taskId) {
		Leave leave = leaveService.get(id);
		Map<String, Object> variables = taskService.getVariables(taskId);
		leave.setVariables(variables);
		return JsonMapper.getInstance().toJson(leave);
	}

	/**
	 * 请假申请撤销
	 * @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");
		String deleteReason = requestMap.get("reason");

		AjaxJson j = new AjaxJson();
		try {
			Leave leave = leaveService.getById(id);
			leave.setStatus("5");
			leave.preUpdate();
			leaveService.update(leave);
			Map map = leaveService.getLeaveById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, deleteReason);
			j.setMsg("撤销申请成功");

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