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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.service.BaseService;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.oa.entity.Leave;
import com.jeeplus.modules.oa.service.LeaveService;
import com.jeeplus.modules.oa_evection.entity.oa_evection.OaEvection;
import com.jeeplus.modules.oa_evection.service.oa_evection.OaEvectionService;
import com.jeeplus.modules.oaall.entity.OaAll;
import com.jeeplus.modules.oaall.service.OaAllService;
import com.jeeplus.modules.oabuy.entity.OaBuy;
import com.jeeplus.modules.oabuy.service.OaBuyService;
import com.jeeplus.modules.oaperformance.entity.OaPerformance;
import com.jeeplus.modules.oaperformance.service.OaPerformanceService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workgoout.entity.GoOut;
import com.jeeplus.modules.workgoout.service.GoOutService;
import com.jeeplus.modules.workovertimeform.entity.WorkOvertimeForm;
import com.jeeplus.modules.workovertimeform.service.WorkOvertimeFormService;
import com.jeeplus.modules.workpayment.entity.WorkPayment;
import com.jeeplus.modules.workpayment.service.WorkPaymentService;
import com.jeeplus.modules.workpettycash.entity.WorkPettyCash;
import com.jeeplus.modules.workpettycash.service.WorkPettyCashService;
import com.jeeplus.modules.workreimbur.entity.WorkReimbur;
import com.jeeplus.modules.workreimbur.service.WorkReimburService;
import com.jeeplus.modules.worksealform.entity.WorkSealForm;
import com.jeeplus.modules.worksealform.service.WorkSealFormService;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程定义相关Service
 * @author jeeplus
 * @version 2013-11-03
 */
@Service
@Transactional(readOnly = true)
public class ActAuditService extends BaseService {


	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private LeaveService leaveService;
	@Autowired
	private GoOutService goOutService;
	@Autowired
	private WorkSealFormService workSealFormService;
	@Autowired
	private OaPerformanceService oaPerformanceService;
	@Autowired
	private OaBuyService oaBuyService;

	@Autowired
	private OaEvectionService oaEvectionService;
	@Autowired
	private WorkOvertimeFormService workOvertimeFormService;
	@Autowired
	private OaAllService oaAllService;

	@Autowired
	private WorkPettyCashService workPettyCashService;
	@Autowired
	private WorkPaymentService workPaymentService;
	@Autowired
	private WorkReimburService workReimburService;
	@Autowired
	private PushinfoService pushinfoService;

	@Transactional(readOnly = false)
	public AjaxJson saveAudit(Act act, String procInsId,String procDefKey, String comment,String approvalId, String type){
		AjaxJson j = new AjaxJson();
		j.setMsg("流程审核成功");
		j.setSuccess(true);
		j.setErrorCode(ErrorCode.code_1004);
		try {
			Map map = new HashMap();
			String name = "";
			String title="审批";
			String content="";
			String remarks="";
			String aliase = "";
			String pushStatus="";
			if(procDefKey.equals("leave")){
				name = "请假";
				Leave leave = leaveService.getById(approvalId);
				leave.setAct(act);
				leave.setComment(comment);
				leaveService.auditSave(leave);
				map = leaveService.getLeaveById(approvalId,type);
				String leaveType = map.get("leaveType").toString();
				String startTime = map.get("startTime").toString();
				String endTime = map.get("endTime").toString();
				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 = "其他";
				}
				remarks = "请假类型："+leaveType+ "\n"
						+"开始时间："+startTime+ "\n"
						+"结束时间："+endTime;
			}else if(procDefKey.equals("goout")){
				name = "外出";
				GoOut out = goOutService.getById(approvalId);
				out.setAct(act);
				out.setComment(comment);
				goOutService.auditSave(out);
				map = goOutService.getGoOutById(approvalId,type);
				String gooutDay = map.get("gooutDay").toString();
				String startTime = map.get("startTime").toString();
				String endTime = map.get("endTime").toString();
				remarks =  "开始时间："+startTime+ "\n"
						+"结束时间："+endTime+ "\n"
						+"外出天数："+gooutDay;
			}else if(procDefKey.equals("evection")){
				name = "出差";
				OaEvection oaEvection = oaEvectionService.getById(approvalId);
				oaEvection.setAct(act);
				oaEvection.setComment(comment);
				oaEvectionService.auditSave(oaEvection);
				map = oaEvectionService.getEvectionById(approvalId, type);
				String address = map.get("address").toString();
				String startTime = map.get("startTime").toString();
				String endTime = map.get("endTime").toString();
				remarks =  "开始时间："+startTime+ "\n"
						+"结束时间："+endTime+ "\n"
						+"出差地点:"+address;
			}else if(procDefKey.equals("overtime")){
				name = "加班";
				WorkOvertimeForm workOvertimeForm = workOvertimeFormService.getById(approvalId);
				workOvertimeForm.setAct(act);
				workOvertimeForm.setComment(comment);
				workOvertimeFormService.auditSave(workOvertimeForm);
				map = workOvertimeFormService.getOverTimeById(approvalId, type);
				String longTime = map.get("longTime").toString();
				String startTime = map.get("startTime").toString();
				String endTime = map.get("endTime").toString();
				remarks =  "开始时间："+startTime+ "\n"
						+"结束时间："+endTime+ "\n"
						+"加班时长（小时）："+longTime;
			}else if(procDefKey.equals("sealform")){
				name = "用印";
				WorkSealForm workSealForm = workSealFormService.getById(approvalId);
				workSealForm.setAct(act);
				workSealForm.setComment(comment);
				workSealFormService.auditSave(workSealForm);
				map = workSealFormService.getUseSealById(approvalId, type);
				remarks = "用印部门："+ map.get("officeName")+"\n"
						+"经办人："+map.get("user")+ "\n"
						+"日期："+map.get("applicationDate");
			}else if(procDefKey.equals("pettyCash")){
				name = "备用金";
				WorkPettyCash workPettyCash = workPettyCashService.getById(approvalId);
				workPettyCash.setAct(act);
				workPettyCash.setComment(comment);
				workPettyCashService.auditSave(workPettyCash);
				map = workPettyCashService.getPettyCashById(approvalId, type);
				remarks = "备用金申请部门："+map.get("applicantOfficeName")+ "\n"
						+"申请人"+map.get("applicantName")+"\n"
						+"使用日期："+ map.get("useDateStr")+"\n"
						+"归还日期："+ map.get("returnDateStr");
			}else if(procDefKey.equals("payment")){
				name = "付款";
				WorkPayment workPayment = workPaymentService.getById(approvalId);
				workPayment.setAct(act);
				workPayment.setComment(comment);
				workPaymentService.auditSave(workPayment);
				map = workPaymentService.getPaymentById(approvalId, type);
				remarks = "付款申请部门："+map.get("officeName")+ "\n"
						+"付款事由："+map.get("reason")+"\n"
						+"付款金额："+map.get("amount");
			}else if(procDefKey.equals("reimbur")){
				name = "报销";
				WorkReimbur workReimbur = workReimburService.getById(approvalId);
				workReimbur.setAct(act);
				workReimbur.setComment(comment);
				workReimburService.auditSave(workReimbur);
				map = workReimburService.getReimburById(approvalId, type);
				remarks = "报销申请部门："+map.get("officeName")+ "\n"
						+"报销总额："+map.get("totalAmount");
			}else if(procDefKey.equals("oaPerformance")){
				name = "绩效自评";
				OaPerformance oaPerformance = oaPerformanceService.getById(approvalId);
				oaPerformance.setAct(act);
				oaPerformance.setComment(comment);
				oaPerformanceService.auditSave(oaPerformance);
				map = oaPerformanceService.getBuyById(approvalId, type);
				remarks = "绩效自评申请部门："+map.get("officeName")+ "\n"
						+"绩效自评内容："+map.get("lastPerformance")+"\n"
						+"绩效自评时间："+map.get("createDate");
			}else if(procDefKey.equals("allApprove")){
				name = "通用审批";
				OaAll oaAll = oaAllService.getById(approvalId);
				oaAll.setAct(act);
				oaAll.setComment(comment);
				oaAllService.auditSave(oaAll);
				map = oaAllService.getLeaveById(approvalId, type);
				remarks = "通用审批申请部门："+map.get("officeName")+ "\n"
						+"通用审批内容："+map.get("applyContent")+"\n"
						+"通用审批详情："+map.get("approveDetail");
			}
			else if(procDefKey.equals("oaBuy")){
				name = "采购";
				OaBuy oaBuy = oaBuyService.getById(approvalId);
				oaBuy.setAct(act);
				oaBuy.setComment(comment);
				oaBuyService.auditSave(oaBuy);
				map = oaBuyService.getBuyById(approvalId, type);
				remarks = "采购申请部门："+map.get("officeName")+ "\n"
						+"采购申请原由："+map.get("applyContent")+"\n"
						+"采购申请时间："+map.get("createDate");
			}

			String status = map.get("status").toString();
			Pushinfo pushinfo = new Pushinfo();
			Map extras = new HashMap();
			if (status.equals("3") || status.equals("4") ){
				extras.put("id", approvalId);
				extras.put("procDefKey",procDefKey);
				aliase = map.get("users").toString();
				pushinfo.setCurrentUser(UserUtils.getUser());
				pushinfo.setUserId(UserUtils.getUser().getId());
				if (status.equals("3")){
					content = "你的"+name+"申请已通过";
					extras.put("type", "4003");
					pushinfo.setType("4003");
					pushStatus = "审批通过";
				}else {
					content = "你的"+name+"申请已驳回";
					extras.put("type", "4004");
					pushinfo.setType("4004");
					pushStatus = "审批驳回";
				}

			}else if (status.equals("2")){
				content = map.get("userName").toString()+"的"+name+"申请需要你审批";
				extras.put("id", approvalId);
				extras.put("procDefKey",procDefKey);
				pushinfo.setCurrentUser(UserUtils.getUser());
				pushinfo.setUserId(UserUtils.getUser().getId());
				extras.put("type", "4001");
				pushinfo.setType("4001");
				pushStatus = "审批中";
				List<Map> process = (List<Map>)map.get("process");
				for (Map maps:process){
					if(maps.get("activityName").equals("待审批")){
						aliase = maps.get("userId").toString();
					}
				}
			}
			pushinfo.setPushId(approvalId);
			pushinfo.setTitle(title);
			pushinfo.setRemarks(remarks);
			pushinfo.setContent(content);
			pushinfo.setPushUserId(aliase);
			pushinfo.setRemarks(remarks);
			pushinfo.setStatus(pushStatus);
			pushinfo.setAddcontent(procDefKey);
			pushinfo.setParentType("singleApproval");
			User user = UserUtils.get(aliase);
			pushinfo.setMobile("ios,android");
			if (user!=null && user.getCompany()!=null && user.getCompany().getId()!=null){
				pushinfo.setCompanyId(user.getCompany().getId());
			}
			pushinfoService.save(pushinfo);
			String str = "";
			if (status.equals("3")){
				str = "审批信息 申请人:" + user.getName() + name + "申请 已通过!";
			}else if(status.equals("4")){
				str = "审批信息 申请人:" + user.getName() + name + "申请 被驳回!";
			}else {
				str = "审批信息 申请人:" + user.getName() + name + "申请 待审批!";
			}
			UserUtils.pushIm(aliase,str);
			/*ist<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(aliase);
			for (WebSocket toUserConn:toUserConns) {

				String message = "{\"to\":\""+aliase+"\"," +
						"\"msg\":\""+str+"\"," +
						"\"useType\":\"sys\"}";
				ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息

			}*/
			UserUtils.pushMeIm("");
			/*List<WebSocket> toUserConnList = ChatServerPool.getWebSocketByUser(UserUtils.getUser().getId());
			for (WebSocket toUserConn:toUserConnList) {
				String message = "{\"useType\":\"sys_me\"}";
				ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
			}*/
			Pushinfo selectPush = new Pushinfo();
			selectPush.setPushId(approvalId);
			selectPush.setPushUserId(UserUtils.getUser().getId());
			List<Pushinfo> pushinfos = pushinfoService.findList(selectPush);
			if (pushinfos!=null && pushinfos.size()!=0){
				Pushinfo push = pushinfos.get(0);
				push.setStatus(pushStatus);
				pushinfoService.save(push);
			}
			JPushClientUtil.sendNotificationToAlias(title, content, extras, aliase);
			j.put("data",map);
			actTaskService.isProcessEnd(procInsId);
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			j.setMsg("流程已审批，不能重新审批！");
			j.setErrorCode(ErrorCode.code_2004);
			j.setSuccess(false);
		}catch (Exception e){
			j.setErrorCode(ErrorCode.code_2004);
			j.setMsg("流程审核失败");
			j.setSuccess(false);
			logger.info("e="+e.getMessage());
		}
		return j;
	}



}
