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

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
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.entity.WorkClientAttachment;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
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.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.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workvisa.entity.WorkVisa;
import com.jeeplus.modules.workvisa.dao.WorkVisaDao;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 工程签证Service
 * @author liuw
 * @version 2017-10-31
 */
@Service
@Transactional(readOnly = true)
public class WorkVisaService extends CrudService<WorkVisaDao, WorkVisa> {
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkVisaDao workVisaDao;
	@Autowired
	private OfficeService officeService;


	public WorkVisa get(String id) {
		//return super.get(id);

		WorkVisa workVisa = super.get(id);

		Workattachment workattachment = new Workattachment();
		workattachment.setAttachmentId(id);
		//workattachment.setAttachmentFlag("37");
		workVisa.setWorkAttachments(workattachmentService.findList(workattachment));

		return workVisa;
	}
	
	public List<WorkVisa> findList(WorkVisa workVisa) {
		return super.findList(workVisa);
	}

	public int findCount(String fullManageId){return workVisaDao.getCount(fullManageId);}

	public Page<WorkVisa> findPage(Page<WorkVisa> page, WorkVisa workVisa) {
		workVisa.getSqlMap().put("dsf", dataScopeFilter(workVisa.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		return super.findPage(page, workVisa);
	}

	public List<WorkVisa> findListByWF(WorkVisa workVisa){
		return workVisaDao.findListByWF(workVisa);
	}
	
	/*@Transactional(readOnly = false)
	public void save(WorkVisa workVisa,MultipartFile attachment_file) {
		super.save(workVisa);
		uploadattachment(attachment_file,workVisa);
	}*/
	@Transactional(readOnly = false)
	public void save(WorkVisa workVisa) {
		super.save(workVisa);
	}

	@Transactional(readOnly = false)
	public void delete(WorkVisa workVisa) {
		super.delete(workVisa);
	}
	
	public Page<WorkFullManage> findPageByfullManage(Page<WorkFullManage> page, WorkFullManage fullManage) {
		fullManage.setPage(page);
		page.setList(dao.findListByfullManage(fullManage));
		return page;
	}
	public Page<WorkVisa> findPageByfullMg(Page<WorkVisa> page, WorkVisa workVisa) {
		workVisa.setPage(page);
		page.setList(dao.findListByWF(workVisa));
		return page;
	}
	@Transactional(readOnly = false)
	public void update(WorkVisa workVisa) {
		workVisa.preUpdate();
		dao.update(workVisa);
	}
	/* * 审核审批保存
     * @param testAudit
     */
	@Transactional(readOnly = false)
	public String auditSave(WorkVisa workVisa) {
		try {
		String userId = UserUtils.getUser().getId();
		actTaskService.claim(workVisa.getAct().getTaskId(), userId);
		String comment = "";
		if (workVisa.getStatus().equals("3")){
			comment = ("yes".equals(workVisa.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workVisa.getAct().getFlag())?"[同意] ":"[驳回] ")+workVisa.getAct().getComment();
		}
		// 设置意见
		workVisa.getAct().setComment(comment);
		System.out.println("comment================="+workVisa.getAct().getComment());
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		//String comment = ("yes".equals(workVisa.getAct().getFlag())?"[同意] ":"[驳回] ")+workVisa.getAct().getComment();
		//workVisa.getAct().setComment(("yes".equals(workVisa.getAct().getFlag())?"[同意] ":"[驳回] ")+workVisa.getAct().getComment());
		/*try {
			workVisa.getAct().setComment(new String(comment.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workVisa.getAct().getTaskDefKey();
		workProjectNotify.setUser(workVisa.getCreateBy());
		workProjectNotify.setRemarks("待通知");
		System.out.println("taskDefKey====================="+taskDefKey);
		//业务逻辑对应的条件表达式
		String exp = "";
			String str = "";
			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9574872f45b84acd89jjj1e66a3db2c8",UserUtils.getSelectOffice());
			List<Activity> activitieList = activityService.getByProcessInstanceId(workVisa.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(workVisa.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			workVisa.setStatus("2");
			String taskCount = "";
			List<Activity> activities = workActivityMenu.getActivities();
			int key = 0;
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workVisa")) {
				key= 1;
					for (int i =0;i<workActivityProcesses.size();i++){
						WorkActivityProcess activityProcess = workActivityProcesses.get(i);
						//String count = taskDefKey.replace("task","");
						String count = taskDefKey.replace("task","").replace("audit","");
						if (taskDefKey.contains("audit")&& (activityProcess.getCount()+"").contains(count)){
							taskCount = count;
							exp = "pass";
							workActivityProcess.setId("");
							workActivityProcess.setCount(0);
							if (!"yes".equals(workVisa.getAct().getFlag())) {
								workVisa.setStatus("5");
								str = "工程签证审核：已撤销!";
								workActivityProcess.setIsApproval("2");
							}else {
								str = "工程签证审核：重新申请!";
								workActivityProcess.setIsApproval("1");
							}
						}else if ((activityProcess.getCount()+"").contains(count)){
							taskCount = count;
							workActivityProcess = activityProcess;
							if (!workActivityProcess.getIsApproval().equals("0")){
								workActivityProcess.setId("");
							}
							exp = "pass";
							if (!"yes".equals(workVisa.getAct().getFlag())) {
								workVisa.setStatus("3");
								str = "工程签证审核：被驳回!";
								workActivityProcess.setIsApproval("2");
								String returnBack = "-1";
								for (Activity activity:activities){
									if(activity.getCount()==Integer.parseInt(count)){
										returnBack = activity.getReturnBack();
										break;
									}
								}
								if (returnBack.equals("0")) {
									workActivityProcess.setId("");
								}
								workVisa.setRemarks("重新申请");
							}else {
								str = "工程签证审核：待审批!";
								workActivityProcess.setIsApproval("1");
							}
						}
					}
				}
			else {
				for (int i =0;i<workActivityProcesses.size();i++) {
					workActivityMenu.setId(workActivityProcesses.get(0).getId());
					workActivityMenu.setProcessType("workVisa");
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					//workActivityProcess = activityProcess;
					if (!activityProcess.getIsApproval().equals("0")){
						workActivityProcess.setId("");
					}
					taskCount = "1";// 默认流程只有一个审批环节
					// 审核环节
					if ("audit".equals(taskDefKey) && count.contains("1")) {
						workActivityProcess = activityProcess;
						exp = "pass";
						if (!"yes".equals(workVisa.getAct().getFlag())) {
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setRemarks("重新申请");
							workVisa.setStatus("3");
							workProjectNotify.setTitle("工程签证审核被驳回!");
						} else {
							workActivityProcess.setIsApproval("1");
							workVisa.setStatus("4");
						}
					} else if ("audits".equals(taskDefKey)&& count.contains("0")) {
						workActivityProcess.setCount(0);
						if ("yes".equals(workVisa.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("工程签证重新申请!");
							Role role = UserUtils.getSelectRole().get(0);
							StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
							buffer.append("bmzr");
							workProjectNotify.setNotifyRole(buffer.toString());
							workProjectNotify.setUser(new User());
							workProjectNotify.setRemarks("待审批");
							workVisa.setStatus("2");
						} else {
							workActivityProcess.setIsApproval("2");
							workVisa.setStatus("5");
						}
						exp = "pass";
					}
				}

				// 未知环节，直接返回
			}
		/*	workActivityProcess.setRemarks(comment);
			workActivityProcess.setProcessInstanceId(workVisa.getProcessInstanceId());
			workActivityProcess.setProcessKey(workActivityMenu.getProcessType());
			if (workActivityProcess!=null && StringUtils.isNotBlank(workActivityProcess.getIsApproval())){
				workActivityProcessService.save(workActivityProcess);
			}*/
		// 提交流程任务
		Map<String, Object> vars = Maps.newHashMap();
		vars.put(exp, "yes".equals(workVisa.getAct().getFlag()) ?true : false );
		System.out.println("vars============"+vars.toString());
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workVisa.getProcessInstanceId(),taskDefKey,"audits",workVisa.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workVisa.getAct().getTaskId(), workVisa.getAct().getProcInsId(), workVisa.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workVisa.getAct().getProcInsId());
			WorkProjectNotify projectNotify = new WorkProjectNotify();
			projectNotify.setNotifyId(workVisa.getId());
			workProjectNotifyService.readByNotifyId(projectNotify);
			workProjectNotify.setNotifyId(workVisa.getId());
			workProjectNotify.setCompanyId(workVisa.getCompanyId());
			workProjectNotify.setContent(workVisa.getAct().getComment());
			workProjectNotify.setType("22");
			workProjectNotify.setStatus("0");
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workVisa.getId());
			workProjectNotifyService.readByNotifyId(notify);
			if (!state){
				workVisa.setRemarks("待通知");
				if ("yes".equals(workVisa.getAct().getFlag())){
					workVisa.setStatus("4");
					workProjectNotify.setTitle("工程签证已通过!");
					Set<String> set = new HashSet<>();
					set.add(workVisa.getCreateBy().getId());
					for (String user :set){
						if (StringUtils.isNotBlank(user)) {
							workProjectNotify.setUser(new User(user));
							workProjectNotify.preInsert();
							workProjectNotifyService.insert(workProjectNotify);
						}
					}
				}else {
					if (!workVisa.getStatus().equals("5")) {
						workVisa.setStatus("3");
						workProjectNotify.setTitle("工程签证被驳回!");
						workProjectNotify = UtilNotify
								.saveNotify(workVisa.getId(),
										workVisa.getCreateBy(),
										workVisa.getCompanyId(),
										str,
										workVisa.getAct().getComment(),
										"22",
										"0",
										"待通知",
										"");
						workProjectNotifyService
								.save(workProjectNotify);
					}
				}
			}else {
				if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workVisa")) {
					workProjectNotify = UtilNotify
							.saveNotify(workVisa.getId(),
									new User(),
									workVisa.getCompanyId(),
									str,
									workVisa.getAct().getComment(),
									"22",
									"0",
									"待审批",
									"");
					String count = taskDefKey.replace("audit","").replace("task","");

					workProjectNotify = activityService.getByFlagAndTaskDefKey(
							activities,
							workProjectNotify,
							taskDefKey,
							workVisa.getAct().getFlag(),
							count,
							workVisa.getCreateBy());
					workProjectNotifyService
							.save(workProjectNotify);
				}else {

					if (!workVisa.getStatus().equals("5")) {
						workProjectNotifyService.save(workProjectNotify);
					}
				}
			}
			workVisa.preUpdate();
			this.update(workVisa);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:"+e);
			return "保存审核意见失败！！";
		}
	}
	/**
	 * 启动流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public void startProcess(WorkVisa workVisa, Map<String, Object> variables) {
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workVisa.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9574872f45b84acd89jjj1e66a3db2c8",officeService.get(workVisa.getOfficeId()));
		// 启动流程
		String businessKey = workVisa.getId().toString();
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		if (StringUtils.isNotBlank(workActivityMenu.getId())){
			workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
			List<Activity> activities = workActivityMenu.getActivities();
			for (Activity a:activities){
				if (a.getDelFlag().equals("0") && a.getCount() == 1){
					activity = a;
				}
			}
			buffer.append(activity.getRole().getEnname());
			variables.put("type", workActivityMenu.getProcessType());
		}else {
			processType= "workVisa";
			variables.put("type", "workVisa");
			Role role = UserUtils.getSelectRole().get(0);
			buffer = DateUtils.getByEnnme(role.getEnname());
			buffer.append("bmzr");
			variables.put("bmzr", buffer.toString());
		}

		variables.put("busId", businessKey);
		variables.put("title", workVisa.getRemarks());//设置标题；
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workVisa.setProcessInstance(processInstance);
		// 更新流程实例ID
		workVisa.setProcessInstanceId(processInstance.getId());
		dao.updateProcessInstanceId(workVisa);

		List<Activity> list= workActivityMenu.getActivities();
		if (list!=null && list.size()!=0){
			workActivityProcessService.saveList(list,processInstance.getId());
		}else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workVisa");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcess.setActivity(new Activity("9574872f45b84acd893010eggg0db2c8"));
			workActivityProcessService.save(workActivityProcess);
		}

		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("工程签证单-审批申请");
		workProjectNotify.setNotifyId(workVisa.getId());
		workProjectNotify.setNotifyRole(buffer.toString());
		workProjectNotify.setCompanyId(workVisa.getCompanyId());
		workProjectNotify.setContent(UserUtils.get(workVisa.getCreateBy().getId()).getName()+"发起工程签证单-审核,请审批!");
		workProjectNotify.setType("22");
		workProjectNotify.setStatus("0");
		workProjectNotify.setRemarks("待审批");
		if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
			//角色审批
			if(StringUtils.isNotBlank(activity.getRole().getEnname())){
				workProjectNotify.setNotifyRole(buffer.toString());
			}
			//人员审批
			if(StringUtils.isNotBlank(activity.getUser().getId())){
				workProjectNotify.setUser(new User(activity.getUser().getId()));
			}
		}else {
			workProjectNotify.setNotifyRole(buffer.toString());
		}
		workProjectNotifyService.save(workProjectNotify);
	}
	//上传附件
	@Transactional(readOnly = false)
	public String uploadEvaludate(MultipartHttpServletRequest multiRequest) {
		String userId = multiRequest.getParameter("id");
		OSSClientUtil ossUtil = new OSSClientUtil();
		Iterator<String> fileNames = multiRequest.getFileNames();
		while(fileNames.hasNext()){
			MultipartFile file = multiRequest.getFile(fileNames.next());
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
			if(file != null && !file.isEmpty()){
				String aliyunPath = ossUtil.uploadFile2OSS(file, "workVisa");
				Workattachment workattachment = new Workattachment();
				workattachment.setUrl(aliyunPath);
				workattachment.setType(fileType);
				workattachment.setAttachmentId(userId);
				workattachment.setAttachmentUser(UserUtils.getUser().getId());
				workattachment.setAttachmentName(fileName);
				workattachment.setAttachmentFlag("0");
				workattachmentService.save(workattachment);
				return workattachment.getId();
			}
		}
		return null ;
	}

	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkVisa getByProcessInstanceId(String processInstanceId) {
		WorkVisa workVisa = dao.getByProcessInstanceId(processInstanceId);
		return workVisa;
	}

	//删除附件
	//阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	//其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	@Transactional(readOnly = false)
	public void deleteFileFromAliyun(Workattachment workattachment) {
		String url = workattachment.getUrl();
		if(StringUtils.isNotBlank(url)){
			String aliyunUrl = Global.getAliyunUrl();
			String aliDownloadUrl = Global.getAliDownloadUrl();
			String cons = "";
			if (url.contains(aliyunUrl)){
				cons = aliyunUrl;
			}else if (url.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
				cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
			}else {
				cons = aliDownloadUrl;
			}
			final String[] arr = url.split(cons + "/");
			String key = arr[1];
			OSSClientUtil ossClientUtil = new OSSClientUtil();
			if(StringUtils.isNotBlank(key)){
				ossClientUtil.deleteSingleObject(key);
				workattachmentService.delete(workattachment);
			}
		}
	}
	public List<Workattachment> findAttachment(WorkVisa workVisa) {
		List<Workattachment>  workattachmentList = new ArrayList<>();
		if(workVisa != null){
			String attachmentId = workVisa.getId();
			if(StringUtils.isNotBlank(attachmentId)){
				workattachmentList = workVisaDao.getListOfAttachment(attachmentId);
			}
		}
		return workattachmentList ;
	}
	//上传
	@Transactional(readOnly = false)
	public void uploadattachment(MultipartFile file,WorkVisa workVisa) {
		if (!file.isEmpty() && file.getSize() > 0) {
			OSSClientUtil ossClientUtil = new OSSClientUtil();
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			String url = ossClientUtil.uploadFile2OSS(file, "workVisa");
			Workattachment workattachment = new Workattachment();
			workattachment.setUrl(url);
			workattachment.setType(fileType);
			workattachment.setAttachmentName(fileName);
			workattachment.setAttachmentUser(UserUtils.getUser().getId());
			workattachment.setAttachmentId(workVisa.getId());
			workattachment.setAttachmentFlag("37");
			workattachmentService.save(workattachment);
		}
	}
}