/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workrepay.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.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
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.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.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workloan.dao.WorkLoanDao;
import com.jeeplus.modules.workloan.entity.WorkLoan;
import com.jeeplus.modules.workloan.service.WorkLoanService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workreimbursement.dao.ReimbursementVATTaxDao;
import com.jeeplus.modules.workreimbursement.dao.WorkAccountDao;
import com.jeeplus.modules.workreimbursement.dao.WorkReimbursementDao;
import com.jeeplus.modules.workreimbursementback.dao.WorkReimbursementBackDao;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.workrepay.entity.WorkRepay;
import com.jeeplus.modules.workrepay.dao.WorkRepayDao;

/**
 * 还款Service
 * @author ssrh
 * @version 2018-10-17
 */
@Service
@Transactional(readOnly = true)
public class WorkRepayService extends CrudService<WorkRepayDao, WorkRepay> {
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkProjectUserDao workProjectUserDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkLoanDao workLoanDao;
	@Autowired
	private WorkRepayDao workRepayDao;
	@Autowired
	@Lazy
	private WorkLoanService workLoanService;
	public WorkRepay get(String id) {
		WorkRepay workRepay = super.get(id);
		if(workRepay!=null && workRepay.getWorkLoan()!=null && StringUtils.isNotBlank(workRepay.getWorkLoan().getId())){
			WorkLoan workLoan = workLoanService.get(workRepay.getWorkLoan().getId());
			workRepay.setWorkLoan(workLoan);
			if(workLoan!=null && StringUtils.isNotBlank(workLoan.getMoney()) && StringUtils.isNotBlank(workLoan.getRepay())){
				Double notRepay =  Double.parseDouble(workLoan.getMoney()) - Double.parseDouble(workLoan.getRepay());
				workRepay.setNotRepay(notRepay+"");
			}else{
				workRepay.setNotRepay("0");
			}
		}
		return workRepay;
	}
	
	public List<WorkRepay> findList(WorkRepay workRepay) {
		return super.findList(workRepay);
	}
	
	public Page<WorkRepay> findPage(Page<WorkRepay> page, WorkRepay workRepay) {
		return super.findPage(page, workRepay);
	}
	
	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkRepay workRepay, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		super.save(workRepay);
		Office office = officeService.get(workRepay.getOfficeId());
		String str =  "还款人:"+user.getName()+",还款金额:"+workRepay.getMoney()+",所属部门:"+office.getName();
		String title = "还款人:"+user.getName();
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workRepay.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c887yha93555c75edfv", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workRepay.getId(),
						null,
						workRepay.getCompanyId(),
						title,
						str,
						"88",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> cns = UserUtils.getByRoleActivityEnname("cn",3,office.getId(),"30",workRepay.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(),"30",workRepay.getCreateBy());
					if (enusers.size()==0){
						super.delete(workRepay);
						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(),"30",workRepay.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("cnList", cns);
            /*variables.put("fgldList", fglds);
            variables.put("cwList", cws);
            variables.put("zjlList", zjls);
            variables.put("cwzjList", cwzjs);
            variables.put("cnList", cns);*/
			//|| fglds.size()==0 || cws.size()==0 || zjls.size()==0 || cwzjs.size()==0 || cns.size()==0
			if (cns.size()==0 ){
				super.delete(workRepay);
				return "流程审批人不能为空,角色出纳下无用户,请联系管理员！";
			}
           /* if (fglds.size()==0){
                return "流程审批人不能为空,角色分管领导下无用户,请联系管理员！";
            }
            if (cws.size()==0){
                return "流程审批人不能为空,角色财务主管下无用户,请联系管理员！";
            }
            if (zjls.size()==0){
                return "流程审批人不能为空,角色总经理下无用户,请联系管理员！";
            }
            if (cwzjs.size()==0){
                return "流程审批人不能为空,角色财务分管领导下无用户,请联系管理员！";
            }
            if (cns.size()==0){
                return "流程审批人不能为空,角色出纳下无用户,请联系管理员！";
            }*/
			variables.put("cncount",cns.size());
            /*variables.put("fgldcount",fglds.size());
            variables.put("cwcount",cws.size());
            variables.put("zjlcount",zjls.size());
            variables.put("cwzjcount",cwzjs.size());
            variables.put("cncount",cns.size());*/
			processType = "workrepay";
			users.addAll(cns);
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("出纳审批");
			workProjectNotifyService
					.save(workProjectNotify);
               /* List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn:toUserConns) {
                   String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 报销人:" + user.getName() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7002");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","88");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + user.getName()+"还款");//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workRepay.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workRepay.setProcessInstanceId(processInstance.getId());
		workRepayDao.updateProcessInstanceId(workRepay);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workrepay");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(cns,processInstance.getId(),1,1);
		}
		logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
				ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkRepay workRepay) {
		super.delete(workRepay);
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkRepay workRepay,List<User> auditUsers) {
		String userName = UserUtils.get(workRepay.getCreateBy().getId()).getName();
		Office office = officeService.get(workRepay.getOfficeId());
		String title = "还款人:"+userName;
		String str =  "还款人:"+userName+",还款金额:"+workRepay.getMoney()+",所属部门:"+office.getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workRepay.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workRepay.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			workRepay.getAct().setFlag("yes");
		}
		String comment = "";
		if (workRepay.getStatus().equals("4")){
			comment = ("yes".equals(workRepay.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workRepay.getAct().getFlag())?"[同意] ":"[驳回] ")+workRepay.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workRepay.setStatus(("yes".equals(workRepay.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(workRepay.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(workRepay.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workrepay")) {
			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(workRepay.getAct().getFlag())) {
						workRepay.setStatus("4");
						workActivityProcess.setIsApproval("2");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}

					} else {
						workActivityProcess.setIsApproval("1");
					}
				}else if(taskDefKey.equals("modifyApply")){
					notifyRole = "调整申请";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(workRepay.getAct().getFlag())) {
						workRepay.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workrepay");
			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 ("cn".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workRepay.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "审批驳回";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		workRepay.getAct().setComment(("yes".equals(workRepay.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workRepay.getAct().getComment());
		workRepay.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workRepay.getAct().getFlag()) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workRepay.getProcessInstanceId(),taskDefKey,"modifyApply",workRepay.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workRepay.getAct().getTaskId(), workRepay.getAct().getProcInsId(), workRepay.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workRepay.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
			users.add(workRepay.getCreateBy());
			if ("yes".equals(workRepay.getAct().getFlag())) {
				workRepay.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRepay.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workRepay.getId(),
										workRepay.getCreateBy(),
										workRepay.getCompanyId(),
										title,
										str,
										"88",
										"0",
										"待通知",
										notifyRole));
			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRepay.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workRepay.getStatus()) && !workRepay.getStatus().equals("3")){
					workRepay.setStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workRepay.getId(),
											workRepay.getCreateBy(),
											workRepay.getCompanyId(),
											title,
											"还款被驳回,原纪录被删除,请重新申请",
											"88",
											"0",
											"待通知",
											notifyRole));
				}
				this.delete(workRepay);
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workRepay.getProcessInstanceId());
		}
		if (users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),str);
			}
		}
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
		workRepayDao.update(workRepay);
		if("5".equals(workRepay.getStatus())){
			//修改还款状态
			if(StringUtils.isNotBlank(workRepay.getMoney()) && StringUtils.isNotBlank(workRepay.getNotRepay())){
				Double money = Double.parseDouble(workRepay.getMoney());
				Double notRepay = Double.parseDouble(workRepay.getNotRepay());
				if(money >= notRepay){
					WorkLoan workLoan = workRepay.getWorkLoan();
					if(workLoan!=null && StringUtils.isNotBlank(workLoan.getId())){
						workLoan.setRepayState("1");
						workLoanDao.updateReay(workLoan);
					}
				}else{
					WorkLoan workLoan = workRepay.getWorkLoan();
					if(workLoan!=null && StringUtils.isNotBlank(workLoan.getId())){
						workLoan.setRepayState("2");
						workLoanDao.updateReay(workLoan);
					}
				}
			}
		}
		return "保存审核意见成功！";
	}
	
	
}