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

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.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.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.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.workaskcheckprice.entity.WorkAskCheckPrice;
import com.jeeplus.modules.workaskcheckprice.dao.WorkAskCheckPriceDao;

/**
 * 询价与核价Service
 * @author liuw
 * @version 2017-11-06
 */
@Service
@Transactional(readOnly = true)
public class WorkAskCheckPriceService extends CrudService<WorkAskCheckPriceDao, WorkAskCheckPrice> {
	@Autowired
	private WorkAskCheckPriceDao workAskCheckPriceDao;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActivityService activityService;

	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;


	public WorkAskCheckPrice get(String id) {
		return super.get(id);
	}
	
	public List<WorkAskCheckPrice> findList(WorkAskCheckPrice workAskCheckPrice) {
		return super.findList(workAskCheckPrice);
	}
	public int findCount(String fullManageId){return workAskCheckPriceDao.getCount(fullManageId);}

	public List<WorkAskCheckPrice> findListByWF(WorkAskCheckPrice workAskCheckPrice){
		return workAskCheckPriceDao.findListByWF(workAskCheckPrice);
	}
	public Page<WorkAskCheckPrice> findPage(Page<WorkAskCheckPrice> page, WorkAskCheckPrice workAskCheckPrice) {
		workAskCheckPrice.getSqlMap().put("dsf", dataScopeFilter(workAskCheckPrice.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_ASKCHECKPRICE.getValue()));
		return super.findPage(page, workAskCheckPrice);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkAskCheckPrice workAskCheckPrice) {
		super.save(workAskCheckPrice);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkAskCheckPrice workAskCheckPrice) {
		super.delete(workAskCheckPrice);
	}
	
	public Page<WorkFullManage> findPageByfullManage(Page<WorkFullManage> page, WorkFullManage fullManage) {
		fullManage.setPage(page);
		page.setList(dao.findListByfullManage(fullManage));
		return page;
	}


	public Page<WorkAskCheckPrice> findPageByfullMg(Page<WorkAskCheckPrice> page, WorkAskCheckPrice workAskCheckPrice) {
		workAskCheckPrice.setPage(page);
		page.setList(dao.findListByWF(workAskCheckPrice));
		return page;
	}
	@Transactional(readOnly = false)
	public void update(WorkAskCheckPrice workAskCheckPrice) {
		workAskCheckPrice.preUpdate();
		dao.update(workAskCheckPrice);
	}
	/* * 审核审批保存
     * @param testAudit
     */
	@Transactional(readOnly = false)
	public String auditSave(WorkAskCheckPrice workAskCheckPrice) {
		try{
		String userId = UserUtils.getUser().getId();
		actTaskService.claim(workAskCheckPrice.getAct().getTaskId(), userId);
		String comment = "";
		if (workAskCheckPrice.getStatus().equals("3")){
			comment = ("yes".equals(workAskCheckPrice.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workAskCheckPrice.getAct().getFlag())?"[同意] ":"[驳回] ")+workAskCheckPrice.getAct().getComment();
		}
		// 设置意见
		workAskCheckPrice.getAct().setComment(comment);
		System.out.println("comment================="+workAskCheckPrice.getAct().getComment());
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		//workAskCheckPrice.getAct().setComment(("yes".equals(workAskCheckPrice.getAct().getFlag())?"[同意] ":"[驳回] ")+workAskCheckPrice.getAct().getComment());
		/*try {
			workVisa.getAct().setComment(new String(comment.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workAskCheckPrice.getAct().getTaskDefKey();
		workProjectNotify.setUser(workAskCheckPrice.getCreateBy());
		workProjectNotify.setRemarks("待通知");
		System.out.println("taskDefKey====================="+taskDefKey);
		//业务逻辑对应的条件表达式
		String exp = "";
		String str = "";
		//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9574872f45b84acd893010e66a3dyyy7",UserUtils.getSelectOffice());
		List<Activity> activitieList = activityService.getByProcessInstanceId(workAskCheckPrice.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(workAskCheckPrice.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		workAskCheckPrice.setStatus("2");
			String taskCount = "";
			List<Activity> activities = workActivityMenu.getActivities();
			int key = 0;
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workaskcheckprice")) {
			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(workAskCheckPrice.getAct().getFlag())) {
						workAskCheckPrice.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(workAskCheckPrice.getAct().getFlag())) {
						workAskCheckPrice.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("");
						}
						workAskCheckPrice.setRemarks("重新申请");
					}else {
						str = "询价与核价：待审批!";
						workActivityProcess.setIsApproval("1");
					}
				}
			}
		}else {
			for (int i =0;i<workActivityProcesses.size();i++) {
				workActivityMenu.setId(workActivityProcesses.get(0).getId());
				workActivityMenu.setProcessType("workaskcheckprice");
				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(workAskCheckPrice.getAct().getFlag())) {
						workActivityProcess.setIsApproval("2");
						workProjectNotify.setRemarks("重新申请");
						workAskCheckPrice.setStatus("3");
						workProjectNotify.setTitle("询价与核价被驳回!");
					} else {
						workActivityProcess.setIsApproval("1");
						workAskCheckPrice.setStatus("4");
					}
				} else if ("audits".equals(taskDefKey)&& count.contains("0")) {
					workActivityProcess.setCount(0);
					if ("yes".equals(workAskCheckPrice.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("待审批");
						workAskCheckPrice.setStatus("2");
					} else {
						workActivityProcess.setIsApproval("2");
						workAskCheckPrice.setStatus("5");
					}
					exp = "pass";
				}
			}
			// 未知环节，直接返回
		}
		/*workActivityProcess.setRemarks(comment);
		workActivityProcess.setProcessInstanceId(workAskCheckPrice.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(workAskCheckPrice.getAct().getFlag()) ?true : false );
		System.out.println("vars============"+vars.toString());
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workAskCheckPrice.getProcessInstanceId(),taskDefKey,"audits",workAskCheckPrice.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workAskCheckPrice.getAct().getTaskId(), workAskCheckPrice.getAct().getProcInsId(), workAskCheckPrice.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workAskCheckPrice.getAct().getProcInsId());
		WorkProjectNotify projectNotify = new WorkProjectNotify();
		projectNotify.setNotifyId(workAskCheckPrice.getId());
		workProjectNotifyService.readByNotifyId(projectNotify);
		workProjectNotify.setNotifyId(workAskCheckPrice.getId());
		workProjectNotify.setCompanyId(workAskCheckPrice.getCompanyId());
		workProjectNotify.setContent(workAskCheckPrice.getAct().getComment());
		workProjectNotify.setType("23");
		workProjectNotify.setStatus("0");
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workAskCheckPrice.getId());
		workProjectNotifyService.readByNotifyId(notify);
		if (!state){
			workAskCheckPrice.setRemarks("待通知");
			if ("yes".equals(workAskCheckPrice.getAct().getFlag())){
				workAskCheckPrice.setStatus("4");
				workProjectNotify.setTitle("询价与核价已通过!");
				Set<String> set = new HashSet<>();
				set.add(workAskCheckPrice.getCreateBy().getId());
				for (String user :set){
					if (StringUtils.isNotBlank(user)) {
						workProjectNotify.setUser(new User(user));
						workProjectNotify.preInsert();
						workProjectNotifyService.insert(workProjectNotify);
					}
				}
			}else {
				if (!workAskCheckPrice.getStatus().equals("5")) {
					workAskCheckPrice.setStatus("3");
					workProjectNotify.setTitle("询价与核价被驳回!");
					workProjectNotify = UtilNotify
							.saveNotify(workAskCheckPrice.getId(),
									workAskCheckPrice.getCreateBy(),
									workAskCheckPrice.getCompanyId(),
									str,
									workAskCheckPrice.getAct().getComment(),
									"23",
									"0",
									"待通知",
									"");
					workProjectNotifyService
							.save(workProjectNotify);
				}
			}
		}else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workaskcheckprice")) {
				workProjectNotify = UtilNotify
						.saveNotify(workAskCheckPrice.getId(),
								new User(),
								workAskCheckPrice.getCompanyId(),
								str,
								workAskCheckPrice.getAct().getComment(),
								"23",
								"0",
								"待审批",
								"");
				String count = taskDefKey.replace("audit","").replace("task","");

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

				if (!workAskCheckPrice.getStatus().equals("5")) {
					workProjectNotifyService.save(workProjectNotify);
				}
			}
		}
			workAskCheckPrice.preUpdate();
		this.update(workAskCheckPrice);
			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(WorkAskCheckPrice workAskCheckPrice, Map<String, Object> variables) {
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workAskCheckPrice.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9574872f45b84acd893010e66a3dyyy7",officeService.get(workAskCheckPrice.getOfficeId()));
		// 启动流程
		String businessKey = workAskCheckPrice.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= "workaskcheckprice";
			variables.put("type", "workaskcheckprice");
			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", workAskCheckPrice.getRemarks());//设置标题；
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workAskCheckPrice.setProcessInstance(processInstance);
		// 更新流程实例ID
		workAskCheckPrice.setProcessInstanceId(processInstance.getId());
		dao.updateProcessInstanceId(workAskCheckPrice);

		List<Activity> list= workActivityMenu.getActivities();
		if (list!=null && list.size()!=0){
			workActivityProcessService.saveList(list,processInstance.getId());
		}else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workaskcheckprice");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcess.setActivity(new Activity("9574872f45b84eee093010e66a3dyyy7"));                 //默认流程 id
			workActivityProcessService.save(workActivityProcess);
		}

		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("询价与核价-审批申请");
		workProjectNotify.setNotifyId(workAskCheckPrice.getId());
		workProjectNotify.setNotifyRole(buffer.toString());
		workProjectNotify.setCompanyId(workAskCheckPrice.getCompanyId());
		workProjectNotify.setContent(UserUtils.get(workAskCheckPrice.getCreateBy().getId()).getName()+"发起询价与核价-审核,请审批!");
		workProjectNotify.setType("23");
		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);
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkAskCheckPrice getByProcessInstanceId(String processInstanceId) {
		WorkAskCheckPrice workAskCheckPrice = dao.getByProcessInstanceId(processInstanceId);
		return workAskCheckPrice;
	}

	/*//上传附件
	@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 ;
	}*/

	/*//删除附件
	//阿里云文件地址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();
		String aliyunUrl = Global.getAliyunUrl();
		if(StringUtils.isNotBlank(url)){
			final String[] arr = url.split(aliyunUrl+"/");
			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);
		}
	}*/
	
	
}