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

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

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.UserDao;
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.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workborrowmangement.dao.WorkBorrowMangementDao;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workitem.dao.WorkItemDao;
import com.jeeplus.modules.workitem.entity.WorkItem;
import com.jeeplus.modules.workitem.service.WorkItemService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowBack;
import com.jeeplus.modules.workborrowmangement.dao.WorkBorrowBackDao;

/**
 * 归还Service
 * @author chenyuping
 * @version 2018-07-13
 */
@Service
@Transactional(readOnly = true)
public class WorkBorrowBackService extends CrudService<WorkBorrowBackDao, WorkBorrowBack> {
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private WorkBorrowBackDao workBorrowBackDao;
	@Autowired
	private WorkBorrowMangementDao workBorrowMangementDao;
	@Autowired
	private WorkItemService workItemService;
	@Autowired
	private WorkItemDao workItemDao;


	public WorkBorrowBack get(String id) {
		return super.get(id);
	}
	
	public List<WorkBorrowBack> findList(WorkBorrowBack workBorrowBack) {
		return super.findList(workBorrowBack);
	}
	
	public Page<WorkBorrowBack> findPage(Page<WorkBorrowBack> page, WorkBorrowBack workBorrowBack) {
		return super.findPage(page, workBorrowBack);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkBorrowBack workBorrowBack) {
		super.save(workBorrowBack);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkBorrowBack workBorrowBack) {
		super.delete(workBorrowBack);
	}


	@Transactional(readOnly = false)
	public String saveBack(WorkBorrowBack workBorrowBack) {
		updateBackStateById(workBorrowBack.getBorrowMangementId());//修改归还状态为2退回中
		WorkBorrowMangement workBorrowMangement=workBorrowMangementDao.get(workBorrowBack.getBorrowMangementId());
		super.save(workBorrowBack);
		return this.startAudit(workBorrowBack,workBorrowBack.getProcessInstanceId(),workBorrowMangement);
	}
	private void updateBackStateById(String borrowMangementId) {
		workBorrowMangementDao.updateBackStateById(borrowMangementId);
	}

	/**
	 * 启动审批流程
	 */
	@Transactional(readOnly = false)
	public String startAudit(WorkBorrowBack workBorrowBack, String processInstanceId,WorkBorrowMangement w){
		Map<String, Object> variables = new HashMap<String, Object>();
		identityService.setAuthenticatedUserId(workBorrowBack.getCurrentUser().getId());
		User createUser = UserUtils.getUser();
		String contentStr = "借用编号："+ w.getNumber()+"，借用日期："+ DateUtils.formatDate(w.getBorrowDate())+"，物品名称："+w.getItemName();
		String titleStr = "归还人："+createUser.getName();

		String businessKey = workBorrowBack.getId();
		Office office = UserUtils.getSelectOffice();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("gh3125f1f194c82bdegnnncdc750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workBorrowBack.getId(),
						null,
						workBorrowBack.getCompanyId(),
						titleStr,
						contentStr,
						"60",
						"0",
						"待审批",
						""
				);

		List<User> users = new ArrayList<>();
		List<User> xzzgList = UserUtils.getByRoleActivityEnname("xzzg",3,office.getId(),"16",workBorrowBack.getCreateBy());
		if (StringUtils.isNotBlank(workActivityMenu.getId())) {
			workProjectNotify.setNotifyRole("");
			workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
			List<Activity> activities = workActivityMenu.getActivities();
			for (Activity a : activities) {
				String encount = a.getEncount();
				String enlist = a.getEnlist();
				if (a.getRole()!=null && StringUtils.isNotBlank(a.getRole().getEnname())){
					List enusers = UserUtils.getByRoleActivityEnnames(a.getRole().getEnname(),office.getId(),"16",workBorrowBack.getCreateBy());
					if (enusers.size()==0){
						return "流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！";
					}
					variables.put(enlist, enusers);
					variables.put(encount, enusers.size());
				}
				if (a.getDelFlag().equals("0") && a.getCount() == 1) {
					activity = a;
				}
			}
			buffer.append(activity.getRole().getEnname());
			if (activity != null && StringUtils.isNotBlank(activity.getId())) {
				//角色审批
				if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
					users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),office.getId(),"16",workBorrowBack.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			if (xzzgList.size()==0){
				this.delete(workBorrowBack);
			}
			if (xzzgList.size()==0){
				return "流程审批人不能为空,角色行政主管下无用户,请联系管理员！";
			}
			processType = "backState";
			users.addAll(xzzgList);
		}
		List<String> userIds = new ArrayList<>(users.size());
		for (User u : users){
			userIds.add(u.getId());
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("行政主管审批");
			workProjectNotifyService.save(workProjectNotify);
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7001");
			extras.put("procDefKey","60");
			extras.put("id",workProjectNotify.getId());
			UserUtils.pushInfoToApp(titleStr, contentStr,extras,u.getId());
		}
		UserUtils.pushIm(userIds,contentStr);
		variables.put("busId", businessKey);
		variables.put("type", processType);
		variables.put("title", "审批单：" + w.getNumber());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey(processType);
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.insert(workActivityProcess);
			workActivityProcessService.insertAuditsByType(xzzgList,processInstance.getId(),1,1);

		}
		workBorrowBack.setProcessInstanceId(processInstance.getId());
		workBorrowBackDao.updateProcessIdAndStatus(workBorrowBack);
		return "";
	}

	/**
	 * 审核流程
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkBorrowBack workBorrowBack) {

		try {
			//归还哪个借用  归还成功后修改归还状态
			WorkBorrowMangement w=workBorrowMangementDao.get(workBorrowBack.getBorrowMangementId());
			//归还成功后清空物品一栏表中的使用人使用时间使用部门字段
			WorkItem workItem=workItemService.get(w.getFixedAssetsNumber());
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workBorrowBack.getAct().getTaskDefKey();
			workBorrowBack.getAct().setFlag("yes");

			String comment = "";
			comment = ("yes".equals(workBorrowBack.getAct().getFlag())?"[同意] ":"[驳回] ")+ workBorrowBack.getAct().getComment();
			//yes 的时候状态为审核通过 否则为未通过
			//1 审核中 2 未通过
			String buffer = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(), workBorrowBack.getCreateBy());
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int key = 0;
			String enname = "";
			String str="借用编号："+ w.getNumber()+"，借用日期："+ DateUtils.formatDate(w.getBorrowDate())+"，物品名称："+ w.getItemName();
			String notifyStr = "固定资产编号："+workItem.getNumber()+"，物品名称："+ w.getItemName();
			User createUser = userDao.get(w.getBorrower());
			String title ="归还人："+createUser.getName();
			String notifyTitle ="物品名称："+ w.getItemName();
			List<Activity> activitieList = activityService.getByProcessInstanceId(workBorrowBack.getProcessInstanceId());
			WorkActivityMenu workActivityMenu = new WorkActivityMenu();
			if (activitieList != null && activitieList.size() != 0) {
				workActivityMenu.setProcessType(activitieList.get(0).getProcessKey());
				workActivityMenu.setActivities(activitieList);
			}

			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			WorkActivityProcess selectProcess = new WorkActivityProcess();
			selectProcess.setProcessInstanceId(workBorrowBack.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			/*if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workBorrowManagement")) {
				key = 1;
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					if (taskDefKey.equals(activityProcess.getActivityTask()) && !taskDefKey.equals("modifyApply")) {
						taskCount = activityProcess.getCount()+"";
						workActivityProcess = activityProcess;
						if (!workActivityProcess.getIsApproval().equals("0")) {
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workBorrowMangement.getAct().getFlag())) {
							workBorrowMangement.setState("4");
							str += " 被驳回!";
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity : activities) {
								if (activity.getCount() == activityProcess.getCount()) {
									notifyRole = activity.getName();
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}

						} else {
							str += " 待审批!";
							workActivityProcess.setIsApproval("1");
						}
					}else if(taskDefKey.equals("modifyApply")){
						notifyRole = "调整借用信息";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workBorrowMangement.getAct().getFlag())) {
							workBorrowMangement.setState("3");
							str += " 已撤销!";
							workActivityProcess.setIsApproval("2");
						} else {
							str += " 重新申请!";
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {*/
				workActivityMenu.setProcessType("backState");
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					workActivityProcess = activityProcess;
					if (!workActivityProcess.getIsApproval().equals("0")) {
						workActivityProcess.setId("");
					}
					// 审核环节
					if ("xzzg".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workBorrowBack.getAct().getFlag())) {
							notifyRole = "归还完成";
							workActivityProcess.setIsApproval("1");
							w.setBackState("1");//已归还
							workItem.setState("1");
							workItem.setEndUser(null);
							workItem.setUserDate(null);
							workItem.setUserOfficeId(null);
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
							str += " 被驳回!";
						}
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			//}
			// 设置意见
			workBorrowBack.getAct().setComment(("yes".equals(workBorrowBack.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workBorrowBack.getAct().getComment());
			workBorrowBack.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workBorrowBack.getAct().getFlag()) ? true : false);
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount, workBorrowBack.getProcessInstanceId(),taskDefKey,"modifyApply", workBorrowBack.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workBorrowBack.getAct().getTaskId(), workBorrowBack.getAct().getProcInsId(), workBorrowBack.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workBorrowBack.getAct().getProcInsId());
			List<User> users = new ArrayList<>();
			List<User> userList = new ArrayList<>();
			if (!state) {
				users.add(workBorrowBack.getCreateBy());
				if ("yes".equals(workBorrowBack.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workBorrowBack.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workBorrowBack.getId(),
											workBorrowBack.getCreateBy(),
											workBorrowBack.getCompanyId(),
											notifyTitle,
											notifyStr,
											"60",
											"0",
											"待通知",
											notifyRole));

				} else {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workBorrowBack.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);

				}
				workActivityProcessService.deleteProcessIdAuditUsers(workBorrowBack.getProcessInstanceId());
			} else {
				if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("backState")) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workBorrowBack.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					WorkProjectNotify workProjectNotify = UtilNotify
							.saveNotify(workBorrowBack.getId(),
									new User(),
									workBorrowBack.getCompanyId(),
									notifyTitle,
									str,
									"60",
									"0",
									"待审批",
									notifyRole);
					List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
							activities,
							workProjectNotify,
							taskDefKey,
							workBorrowBack.getAct().getFlag(),
							taskCount,
							workBorrowBack.getCreateBy(),
							workBorrowBack.getOfficeId(),
							"60");
					for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
						users.add(workProjectNotify1.getUser());
						workProjectNotify1.setId("");
						workProjectNotify1.setIsNewRecord(false);
						workProjectNotifyService
								.save(workProjectNotify1);
					}

				} else {
					if (!"yes".equals(workBorrowBack.getAct().getFlag())) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workBorrowBack.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList);
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workBorrowBack.getId(),
												workBorrowBack.getCreateBy(),
												workBorrowBack.getCompanyId(),
												title,
												str,
												"60",
												"0",
												"重新申请",
												notifyRole));
						users.add( workBorrowBack.getCreateBy());
					} else {
						if (StringUtils.isNotBlank(enname)) {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workBorrowBack.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							//users.addAll(userList1);
							WorkProjectNotify workProjectNotify = UtilNotify
									.saveNotify(workBorrowBack.getId(),
											new User(),
											workBorrowBack.getCompanyId(),
											title,
											str,
											"60",
											"0",
											"待审批",
											notifyRole);
							List<User> userLists = UserUtils.getByRoleActivityEnnames(enname, workBorrowBack.getOfficeId(),"16", workBorrowBack.getCreateBy());
							users.addAll(userLists);
							for (User user1:userLists){
								workProjectNotify.setUser(user1);
								workProjectNotify.setId("");
								workProjectNotify.setIsNewRecord(false);
								workProjectNotifyService.save(workProjectNotify);
								Map<String,Object> extras = new HashMap<>();
								extras.put("type","7001");
								extras.put("procDefKey","60");
								extras.put("id",workProjectNotify.getId());
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());
							}
						}else {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workBorrowBack.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workBorrowBack.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workBorrowBack.getId(),
													workBorrowBack.getCreateBy(),
													workBorrowBack.getCompanyId(),
													title,
													str,
													"60",
													"0",
													"重新申请",
													notifyRole));
						}
					}
				}
			}
			if (users!=null && users.size()!=0) {
				for (User u : users) {
					UserUtils.pushIm(u.getId(),title);
				}
			}
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					UserUtils.pushMeIm(u.getId());
				}
			}
			dao.update(workBorrowBack);
            workItemDao.update(workItem);
            workBorrowMangementDao.update(w);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:",e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:",e);
			return "保存审核意见失败！！";
		}
	}

}