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

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.MyBeanUtils;
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.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.workbidingdocument.dao.WorkBidingDocumentDao;
import com.jeeplus.modules.workbidingdocument.entity.WorkBidingDocument;
import com.jeeplus.modules.workbidproject.dao.WorkBidProjectDao;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workproject.dao.WorkProjectDao;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectnotify.dao.WorkProjectNotifyDao;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 标书Service
 * @author fgy
 * @version 2017-10-16
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkBidingDocumentService extends CrudService<WorkBidingDocumentDao, WorkBidingDocument> {

	@Autowired
	private WorkProjectNotifyDao workProjectNotifyDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkBidingDocumentDao workBidingDocumentDao;
	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private WorkBidProjectDao workBidProjectDao;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private WorkProjectDao workProjectDao;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActivityService activityService;
	private Lock lock = new ReentrantLock();

	public WorkBidingDocument get(String id) {
		return super.get(id);
	}

	public List<WorkBidingDocument> findList(WorkBidingDocument workBidingDocument) {
		return super.findList(workBidingDocument);
	}

	public Page<WorkBidingDocument> findPage(Page<WorkBidingDocument> page, WorkBidingDocument workBidingDocument) {
		workBidingDocument.getSqlMap().put("dsf", dataScopeFilterOR(workBidingDocument.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		workBidingDocument.setPage(page);
		page.setList(findWorkBidProjectList(workBidingDocument));
		return page;
	}

	public List<WorkBidingDocument> findWorkBidProjectList(WorkBidingDocument workBidingDocument){
		List<WorkBidingDocument> bidList =workBidingDocumentDao.findlistWithWorkBidProject(workBidingDocument);
		List<WorkClientLinkman> linkmanList =new ArrayList<WorkClientLinkman>();
		if(bidList.size()>0){
			for(WorkBidingDocument document : bidList){
				if(StringUtils.isBlank(document.getId())){
					document.setStatus("0");
				}
				WorkBidProject workBidProject = document.getWorkBidProject();

				linkmanList = workClientInfoService.findLinkmanList(workBidProject.getId());
				workBidProject.setWorkClientLinkmanList(linkmanList);

				List<String> masterId = workBidProjectDao.getProjectMaster(workBidProject);
				List<User> masterList = new ArrayList<User>();
				for (int i = 0; i < masterId.size(); i++) {
					if(StringUtils.isNotBlank(masterId.get(i))){
						masterList.add(UserUtils.get(masterId.get(i)));
					}
				}
				workBidProject.setMasterList(masterList);
				List<String> memberId = workBidProjectDao.getProjectMember(workBidProject);
				List<User> memberList = new ArrayList<User>();
				for (int i = 0; i < memberId.size(); i++) {
					if(StringUtils.isNotBlank(memberId.get(i))){
						memberList.add(UserUtils.get(memberId.get(i)));
					}
				}
				workBidProject.setMemberList(memberList);

				String modifiable = getOptionFlag(masterId,workBidProject.getCreateBy().getId());
				document.setOptionFlag(modifiable);

				//流程结束state=false，未结束state=true
				boolean state = true;
				if(StringUtils.isNotBlank(document.getProcessInstanceId())){
					state = actTaskService.isProcessEnd(document.getProcessInstanceId());
				}else{
					state = false;
				}
				document.setProcessEnded(state);

			}
		}
		return bidList;
	}
	//项目负责人、项目登记人的修改权限为1(修改非已通过的标书)；部门负责人修改权限为2（还可以修改已通过的标书）
	public String getOptionFlag(List<String> masterId , String createBy){
		String userId = UserUtils.getUser().getId();
		if(masterId != null && masterId.size()>0){
			if(masterId.contains(userId)){
				return "1";
			}
		}
		if(createBy != null && createBy.equals(userId)){
			return "1";
		}
		Role role = UserUtils.getSelectRole().get(0);
		if(role != null && role.getEnname().contains("bmzr")){
			return "2";
		}
		return "0";
	}

	@Transactional(readOnly = false)
	public void save(WorkBidingDocument workBidingDocument) {
		super.save(workBidingDocument);
	}

	//添加项目负责人和组成员
	@Transactional(readOnly = false)
	public Map<String,Object> addMastersOrMembers(WorkBidingDocument workBidingDocument, MultipartHttpServletRequest multiRequest,String status) {
		Map<String,Object> map = new HashMap<>();

		String masterIds = multiRequest.getParameter("masterIds");
		String memberIds = multiRequest.getParameter("memberIds");
		WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
		String masterIdsDB = workBidProject.getProjectMaster();
		String memberIdsDB = workBidProject.getProjectMember();

		String masterIdString = uniqueStr(masterIds,masterIdsDB);
		String memberIdsString = uniqueStr(memberIds,memberIdsDB);
		memberIdsString = modifyMemberIds(masterIdString,memberIdsString);

		workBidProject.setProjectMaster(masterIdString);
		workBidProject.setProjectMember(memberIdsString);
		workBidingDocumentDao.updateMasterAndMemberOfWorkBidProject(workBidProject);
		int number1 = updateMasterOfWorkBidProjectAndWorkProjectUser(workBidProject.getId(),workBidProject.getProjectMaster());
		int number2 = updateMemberOfWorkBidProjectAndWorkProjectUser(workBidProject.getId(),workBidProject.getProjectMember());
		workBidingDocument.setWorkBidProject(workBidProject);
		workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		workBidingDocument.setStatus(status);
		super.save(workBidingDocument);

		//添加负责人或组成员之后，返回数据给页面
		if(StringUtils.isNotBlank(masterIds)){
			List<String> masters =  getMasterIdStrList(workBidProject);
			List<User> masterList = new ArrayList<User>();
			for (int i = 0; i < masters.size(); i++) {
				if(StringUtils.isNotBlank(masters.get(i))){
					User master = UserUtils.get(masters.get(i));
					Workattachment w = workattachmentService.getByAttachmentIdAndCompanyIdAndFlag(master.getId(),UserUtils.getSelectCompany().getId(),"0");

					map.put("number",number1);
					map.put("user",master);
					map.put("attachment",w);
				}
			}
		}
		if(StringUtils.isNotBlank(memberIds)){
			List<String> members = getMemberIdStrList(workBidProject);
			List<User> memberList = new ArrayList<User>();
			for (int i = 0; i < members.size(); i++) {
				if(StringUtils.isNotBlank(members.get(i))){
					User member = UserUtils.get(members.get(i));
					Workattachment w = workattachmentService.getByAttachmentIdAndCompanyIdAndFlag(member.getId(),UserUtils.getSelectCompany().getId(),"0");

					map.put("number",number2);
					map.put("user",member);
					map.put("attachment",w);
				}
			}
		}
		return map;
	}
	//保存、修改标书
	@Transactional(readOnly = false)
	public void save(WorkBidingDocument workBidingDocument,String status,String again) {
		String id = workBidingDocument.getId();
		WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
		workBidingDocument.setWorkBidProject(workBidProject);
		workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		workBidingDocument.setOfficeId(UserUtils.getSelectOffice().getId());
		workBidingDocument.setStatus(status);

		if(StringUtils.isNotBlank(again) && "again".equals(again)){
			workBidingDocument.setProcessInstanceId("");
			workBidingDocument.preUpdate();
		}
		super.save(workBidingDocument);
		if(StringUtils.isBlank(id)){
			List<Workattachment> workAttachments = workBidingDocument.getWorkAttachments();
			if(workAttachments!=null && workAttachments.size()>0){
				for (int i = 0; i < workAttachments.size(); i++) {
					Workattachment w = workAttachments.get(i);
					if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
						w.setAttachmentId(workBidingDocument.getId());
						w.setCompanyId(workBidingDocument.getCompanyId());
						w.setAttachmentUser(UserUtils.getUser().getId());
						w.setId("");
						workattachmentService.save(w);
					}
				}
			}
		}

		//0待编制，1暂存，2审核中，3通过，4未通过，5已撤销
		if("2".equals(status)){
			//进入审核流程
			Map<String,Object> variables = new HashMap<String,Object>();
			startProcess(workBidingDocument,variables);
		}
	}
	//重新申请或撤销
	@Transactional(readOnly = false)
	public void reapplyORrepeal(WorkBidingDocument workBidingDocument, String submit) {
		//0待编制，1暂存，2审核中，3通过，4未通过，5已撤销
		//撤销不保存数据，只结束流程
		if("repeal".equals(submit)){
			auditSave(workBidingDocument);
		}
		//重新申请，保存数据，继续上次的流程
		if("reapply".equals(submit)){
			WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
			workBidingDocument.setWorkBidProject(workBidProject);
			workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
			super.save(workBidingDocument);
			//uploadattachment(multiRequest,workBidingDocument);

			auditSave(workBidingDocument);
		}
	}

	//当member有和master重复时，以master为准
	@Transactional(readOnly = false)
	private String modifyMemberIds(String masterIdString, String memberIdsString) {
		List<String> list1 = new ArrayList<>();
		List<String> list2= new ArrayList<>();
		if(StringUtils.isNotBlank(masterIdString)){
			String[] arr1 = masterIdString.split(",");
			for(int i=0;i<arr1.length;i++){
				if(StringUtils.isNotBlank(arr1[i])){
					list1.add(arr1[i]);
				}
			}
		}
		if(StringUtils.isNotBlank(memberIdsString)){
			String[] arr2 = memberIdsString.split(",");
			for(int i=0;i<arr2.length;i++){
				if(StringUtils.isNotBlank(arr2[i])){
					list2.add(arr2[i]);
				}
			}
		}
		Iterator<String> iterator = list2.iterator();
		while (iterator.hasNext()){
			String str = iterator.next();
			if(list1 != null && list1.size()>0){
				for(String s : list1){
					if(str.equals(s)){
						iterator.remove();
					}
				}
			}
		}
		StringBuilder builder = new StringBuilder();
		if(list2 != null && list2.size()>0){
			for(String str : list2){
				builder.append(",").append(str);
			}
		}
		String str = builder.toString();
		if(StringUtils.isNotBlank(str) && str.length()>2){
			return  builder.toString().substring(1);

		}else {
			return "";
		}
	}

	@Transactional(readOnly = false)
	private String uniqueStr(String strOld, String strNew) {
		if(StringUtils.isBlank(strOld)){
			return strNew;
		}
		if(StringUtils.isBlank(strNew)){
			return strOld;
		}
		Set<String> set = new TreeSet<String>();
		if(StringUtils.isNotBlank(strOld) && StringUtils.isNotBlank(strNew)){
			String[] arr1 = strOld.split(",");
			for (String str : arr1){
				set.add(str);
			}

			String[] arr2 = strNew.split(",");
			for(String str : arr2){
				set.add(str);
			}
		}
		StringBuilder builder = new StringBuilder();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()){
			builder.append(",").append(iterator.next());
		}
		return builder.toString().substring(1);
	}

	//上传标书方案编制(1)
	@Transactional(readOnly = false)
	public String uploadattachment(MultipartHttpServletRequest multiRequest,WorkBidingDocument workBidingDocument){
		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, "workBidingDocument");
				Workattachment workattachment = new Workattachment();
				workattachment.setUrl(aliyunPath);
				workattachment.setType(fileType);
				workattachment.setAttachmentId(workBidingDocument.getId());
				workattachment.setAttachmentUser(UserUtils.getUser().getId());
				workattachment.setAttachmentName(fileName);
				workattachment.setAttachmentFlag("1");
				workattachmentService.save(workattachment);
				return workattachment.getId();
			}
		}

		return null;
	}
	//上传评价汇总(0)
	@Transactional(readOnly = false)
	public String uploadEvaludate(MultipartHttpServletRequest multiRequest) {
		String userId = multiRequest.getParameter("userId");
		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()){

				Workattachment w = workattachmentService.getByAttachmentIdAndCompanyIdAndFlag(userId,UserUtils.getSelectCompany().getId(),"0");
				if(w != null){
					workattachmentService.deleteFileFromAliyun(w,w==null?"":w.getUrl());
					workattachmentService.delete(w);
				}

				String aliyunPath = ossUtil.uploadFile2OSS(file, "userEvaluation");
				Workattachment workattachment = new Workattachment();
				workattachment.setUrl(aliyunPath);
				workattachment.setType(fileType);
				workattachment.setAttachmentId(userId);
				workattachment.setAttachmentUser(UserUtils.getUser().getId());
				workattachment.setAttachmentName(fileName);
				workattachment.setCompanyId(UserUtils.getSelectCompany().getId());
				workattachment.setAttachmentFlag("0");
				workattachmentService.save(workattachment);
				return workattachment.getUrl();
			}
		}
		return null ;
	}

	@Transactional(readOnly = false)
	public void delete(WorkBidingDocument workBidingDocument) {
		super.delete(workBidingDocument);
	}

	public Page<WorkBidProject> findPageByworkBidProject(Page<WorkBidProject> page, WorkBidProject workBidProject) {
		workBidProject.setPage(page);
		page.setList(dao.findListByworkBidProject(workBidProject));
		return page;
	}

	//根据投标项目id查询标书
	public WorkBidingDocument getByWorkBidProject(String id) {
		return workBidingDocumentDao.getByWorkBidProject(id);
	}

	//单个删除投标项目的负责人
	@Transactional(readOnly = false)
	public WorkBidProject deleteMasterOfWorkBidProject(WorkBidProject workBidProject,String masterId) {
		StringBuilder newMastersStr = new StringBuilder();
		String mastersStr = workBidProject.getProjectMaster();
		String[] arr = mastersStr.split(",");
		for(String str : arr){
			if(StringUtils.isNotBlank(str) && !masterId.equals(str)){
				newMastersStr.append(str).append(",");
			}
		}

		String masterIds = newMastersStr.toString();
		if(masterIds.endsWith(",")){
			masterIds = masterIds.substring(0, masterIds.lastIndexOf(","));
		}
		workBidProject.setProjectMaster(masterIds);
		workBidingDocumentDao.updateMasterAndMemberOfWorkBidProject(workBidProject);
		updateMasterOfWorkBidProjectAndWorkProjectUser(workBidProject.getId(),masterIds);
		return workBidProjectService.get(workBidProject.getId());
	}

	//更新项目负责人和work_project_user的对应关系
	@Transactional(readOnly = false)
	public int updateMasterOfWorkBidProjectAndWorkProjectUser(String workBidProjectId , String masterId){

		String[] arr = masterId.split(",");
		List<String> list = new ArrayList<>();
		for(String str : arr){
			if(StringUtils.isNotBlank(str)){
				list.add(str);
			}
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("workBidProjectId",workBidProjectId);
		map.put("masterIds",list);

		workBidingDocumentDao.deleteProjectMasterOfWorkProjectUser(workBidProjectId);
		int number = 0 ;
		if(list!=null && list.size()>0){
			number = workBidingDocumentDao.insertProjectMasterOfWorkProjectUser(map);
		}
		return number;
	}
	//更新项目组成员和work_project_user的对应关系
	@Transactional(readOnly = false)
	private int updateMemberOfWorkBidProjectAndWorkProjectUser(String workBidProjectId, String memberId) {

		String[] arr = memberId.split(",");
		List<String> list = new ArrayList<>();
		for(String str : arr){
			if(StringUtils.isNotBlank(str)){
				list.add(str);
			}
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("workBidProjectId",workBidProjectId);
		map.put("memberIds",list);

		workBidingDocumentDao.deleteProjectMemberOfWorkProjectUser(workBidProjectId);
		int number= 0 ;
		if(list!=null && list.size()>0){
			number = workBidingDocumentDao.insertProjectMemberOfWorkProjectUser(map);
		}
		return number;
	}

	//单个删除负责组成员
	@Transactional(readOnly = false)
	public WorkBidProject deleteMemberOfWorkBidProject(WorkBidProject workBidProject, String memberId) {
		StringBuilder newMembersStr = new StringBuilder();
		String membersStr = workBidProject.getProjectMember();
		String[] arr = membersStr.split(",");

		for(String str : arr){
			if(StringUtils.isNotBlank(str) && !memberId.equals(str)){
				newMembersStr.append(str).append(",");
			}
		}

		String memberIds = newMembersStr.toString();
		if(memberIds.endsWith(",")){
			memberIds = memberIds.substring(0, memberIds.lastIndexOf(","));
		}
		workBidProject.setProjectMember(memberIds);
		workBidingDocumentDao.updateMasterAndMemberOfWorkBidProject(workBidProject);
		updateMemberOfWorkBidProjectAndWorkProjectUser(workBidProject.getId(),memberIds);
		return workBidProjectService.get(workBidProject.getId());

	}

	public WorkBidingDocument getById(String workBidingDocumentId) {
		WorkBidingDocument workBidingDocument = workBidingDocumentDao.get(workBidingDocumentId);
		if(workBidingDocument != null){
			WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();

			List<String> masterId = getMasterIdStrList(workBidProject);
			List<User> masterList = getUserList(masterId);
			workBidProject.setMasterList(masterList);

			List<String> memberId = getMemberIdStrList(workBidProject);
			List<User> memberList = getUserList(memberId);
			workBidProject.setMemberList(memberList);

		}
		//流程结束state=false，未结束state=true
		boolean state = true;
		if(StringUtils.isNotBlank(workBidingDocument.getProcessInstanceId())){
			state = actTaskService.isProcessEnd(workBidingDocument.getProcessInstanceId());
		}else{
			state = false;
		}
		workBidingDocument.setProcessEnded(state);


		return workBidingDocument;
	}
	//获取项目负责人和项目组成员
	public List<User> getUserList(List<String> listStr){
		List<User> userList = new ArrayList<User>();
		for (int i = 0; i < listStr.size(); i++) {
			Workattachment workattachment = null ;
			User user = UserUtils.get(listStr.get(i));
			if(user != null){
				workattachment = workattachmentService.getByAttachmentIdAndCompanyIdAndFlag(user.getId(),UserUtils.getSelectCompany().getId(),"0");
				if(workattachment != null){
					user.setWorkattachment(workattachment);
				}
			}
			userList.add(user);
		}
		return userList;
	}
	//得到该项目的负责人
	public List<String> getMasterIdStrList(WorkBidProject workBidProject){
		return workBidProjectDao.getProjectMaster(workBidProject);
	}
	//得到该项目的组成员
	public List<String> getMemberIdStrList(WorkBidProject workBidProject){
		return workBidProjectDao.getProjectMember(workBidProject);
	}


	public List<Workattachment> findAttachment(WorkBidingDocument workBidingDocument) {
		List<Workattachment>  workattachmentList = new ArrayList<>();
		if(workBidingDocument != null){
			String attachmentId = workBidingDocument.getId();
			if(StringUtils.isNotBlank(attachmentId)){
				workattachmentList = workBidingDocumentDao.getListOfAttachment(attachmentId);
			}
		}
		return workattachmentList ;
	}

	/**
	 * 启动流程
	 * @param workBidingDocument
	 * @param variables
	 */
	@Transactional(readOnly = false)// 编制状态(0待编制、1暂存、2审核中、3已通过、4未通过)
	public void startProcess(WorkBidingDocument workBidingDocument, Map<String, Object> variables) {

		//用来设置启动流程的人员的id，引擎会自动把人员的id保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workBidingDocument.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("215ad3f24b1345bc800fa76a57bb45a8",officeService.get(workBidingDocument.getOfficeId()));
		//启动流程
		String businessKey = workBidingDocument.getId().toString();
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer1 = new StringBuffer();
		StringBuffer buffer2 = 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;
					break;
				}
			}
			variables.put("type", workActivityMenu.getProcessType());
		}else{
			processType = ActUtils.PD_WORKBIDINGDOCUMENT[0];
			variables.put("type", processType);
			Role role = UserUtils.getSelectRole().get(0);
			buffer1 = DateUtils.getByEnnme(role.getEnname());
			buffer2 = DateUtils.getByEnnme(role.getEnname());
			StringBuffer buffer3  = DateUtils.getByEnnme(role.getEnname());

			buffer1.append("bmzr");
			buffer2.append("zjl");
			buffer3.append("dsz");
			variables.put("type",processType);
			variables.put("bmzr",buffer1.toString());//部门负责人
			variables.put("zjl",buffer2.toString());//总经理
			variables.put("dsz",buffer3.toString());//董事长

		}

		variables.put("businessId",businessKey);
		variables.put("title",workBidingDocument.getRemarks());

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType,businessKey,variables);
		workBidingDocument.setProcessInstance(processInstance);
		workBidingDocument.setProcessInstanceId(processInstance.getId());
		workBidingDocumentDao.updateProcessInstanceId(workBidingDocument);

		workBidingDocument.setStatus("2");

		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.setIsApproval("0");
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setActivity(new Activity("c5804a90a93c4e28aa116c4cc3c439fd"));
			workActivityProcess.setCount(1);
			workActivityProcessService.save(workActivityProcess);

			workActivityProcess.setId("");
			workActivityProcess.setCount(2);
			workActivityProcessService.save(workActivityProcess);
		}

		//发起通知给审批角色或人员
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("您有新的标书编制待审批");
		workProjectNotify.setNotifyId(workBidingDocument.getId());
		workProjectNotify.setCompanyId(workBidingDocument.getCompanyId());
		workProjectNotify.setContent("审批任务-标书编制");
		workProjectNotify.setRemarks("待审批");
		workProjectNotify.setType("5");
		workProjectNotify.setStatus("0");
		workProjectNotify.setNotifyRole("");
		workProjectNotify.setUser(new User(""));

		if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
			//角色审批
			if(StringUtils.isNotBlank(activity.getRole().getEnname())){
				workProjectNotify.setNotifyRole(activity.getRole().getEnname());
			}
			//人员审批
			if(StringUtils.isNotBlank(activity.getUser().getId())){
				workProjectNotify.setUser(new User(activity.getUser().getId()));
			}
		}else {
			workProjectNotify.setNotifyRole(buffer1.toString());
		}

		workProjectNotifyService.save(workProjectNotify);
	}

	//获取流程信息
	public WorkBidingDocument getByProcessInstanceId(String processInstanceId) {
		return workBidingDocumentDao.getByProcessInstanceId(processInstanceId);
	}

	//删除附件
	//阿里云文件地址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);
			}
		}

	}


	//0待编制，1暂存，2审核中，3通过，4未通过，5已撤销
	@Transactional(readOnly = false)
	public String auditSave(WorkBidingDocument workBidingDocument) {
		try {
			String userId = UserUtils.getUser().getId();
			actTaskService.claim(workBidingDocument.getAct().getTaskId(), userId);
			// 设置意见
			String comment = "";
			if(workBidingDocument.getStatus().equals("4")){//如果是被驳回状态
				comment = ("yes".equals(workBidingDocument.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else{
				comment = ("yes".equals(workBidingDocument.getAct().getFlag())?"[同意] ":"[驳回] ")+workBidingDocument.getAct().getComment();
			}

			workBidingDocument.getAct().setComment(comment);
			workBidingDocument.setStatus("2");

			System.err.println("comment======"+workBidingDocument.getAct().getComment());
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workBidingDocument.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);//每执行一步审核操作，都把已发出的通知变更为"已读"

			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workBidingDocument.getAct().getTaskDefKey();
			System.err.println("taskDefKey======"+taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";
			String bmzr = "";
			String zjl = "";
			String dsz = "";

			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("215ad3f24b1345bc800fa76a57bb45a8",officeService.get(workBidingDocument.getOfficeId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workBidingDocument.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 selectedProcess = new WorkActivityProcess();
			selectedProcess.setProcessInstanceId(workBidingDocument.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectedProcess);

			//是自定义流程
			boolean isCustomProcess = StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals(ActUtils.PD_WORKBIDINGDOCUMENT[0]);

			String taskCount = "";
			int key = 0;

			List<Activity> activities = workActivityMenu.getActivities();
			if (isCustomProcess) {
				key = 1 ;
				for (int i =0;i<workActivityProcesses.size();i++){
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = taskDefKey.replace("task","").replace("audit","");

					//重申|撤销 （audit1,2,3... = yes|no）
					if(taskDefKey.contains("audit") && (activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workBidingDocument.getAct().getFlag())) {
							workBidingDocument.setStatus("5");//撤销
							workActivityProcess.setIsApproval("2");
						}else {
							workBidingDocument.setStatus("2");//重申
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("标书编制：重新申请");
							workProjectNotify.setRemarks("重新申请");//用于在通知页面做审核操作，这一步必须
							//对通知的人(角色)的设定在 提交任务里完成
						}
						break;
					}
					else if ((activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						workActivityProcess = activityProcess;
						workActivityProcess.setRemarks(comment);

						if (!workActivityProcess.getIsApproval().equals("0")){
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workBidingDocument.getAct().getFlag())) {
							workBidingDocument.setStatus("4");
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setTitle("您的标书编制申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workBidingDocument.getCreateBy());
							String returnBack = "-1";
							for (Activity activity:activities){
								if(activity.getCount()==Integer.parseInt(count)){
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}
							//0待编制，1暂存，2审核中，3通过，4未通过，5已撤销
						}else {
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("标书编制：待审批");
							//对通知的人(角色)的设定在 提交任务里完成
						}
					}
				}
			}else {
				workActivityMenu.setId(workActivityProcesses.get(0).getId());
				workActivityMenu.setProcessType(ActUtils.PD_WORKBIDINGDOCUMENT[0]);
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";

					if(! activityProcess.getIsApproval().equals("0")){
						workActivityProcess.setId("");
					}

					// 部门负责人审批
					if ("audit1".equals(taskDefKey) && count.contains("1")){
						taskCount = count ;
						workActivityProcess.setCount(1); //默认流程里部门负责人是第一个环节
						exp = "pass";
						if("yes".equals(workBidingDocument.getAct().getFlag())){
							workActivityProcess.setIsApproval("1");
							//状态不变
							//发起通知给下一步审批人---总经理或董事长
							workBidingDocument.setStatus("2");
							Role role = UserUtils.getSelectRole().get(0);
							String roleEnname = DateUtils.getByEnnme(role.getEnname()).toString();
							zjl = roleEnname+"zjl" ;
							dsz = roleEnname+"dsz";
							workProjectNotify.setTitle("您有新的标书编制待审批");
							workProjectNotify.setRemarks("待审批");
							workProjectNotify.setUser(new User(""));
						}else{
							workActivityProcess.setIsApproval("2");

							workBidingDocument.setStatus("4");//部门负责人驳回
							//跳转页面的所需，这里只能填"重新申请"
							workProjectNotify.setTitle("标书编制申请被驳回!");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workBidingDocument.getCreateBy());//发送通知给申请人
						}
					}else if("audit2".equals(taskDefKey) && count.contains("2")){
						taskCount = count ;
						workActivityProcess.setCount(2); //默认流程里 总经理|董事长 是第二个审批环节

						exp = "pass";
						if("yes".equals(workBidingDocument.getAct().getFlag())){
							workActivityProcess.setIsApproval("1");
							//最终通过
							workBidingDocument.setStatus("3");
							workProjectNotify.setTitle("您的标书编制申请已通过!");
							workProjectNotify.setRemarks("待通知");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workBidingDocument.getCreateBy());
						}else{
							workActivityProcess.setIsApproval("2");

							workBidingDocument.setStatus("4");//总经理或董事长驳回
							//跳转页面的所需，这里只能填"重新申请"
							workProjectNotify.setTitle("标书编制申请被驳回!");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workBidingDocument.getCreateBy());//发送通知给申请人
						}
					}
					//重申|撤销
					else if("reapply".equals(taskDefKey) && count.equals("0")){
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						exp = "pass";
						if("yes".equals(workBidingDocument.getAct().getFlag())){//重新申请
							workActivityProcess.setIsApproval("1");

							workBidingDocument.setStatus("2");//重新回到审核中状态
							Role role = UserUtils.getSelectRole().get(0);
							String roleEnname = DateUtils.getByEnnme(role.getEnname()).toString();
							bmzr = roleEnname+"bmzr";
							workProjectNotify.setTitle("标书编制重新申请");
							workProjectNotify.setRemarks("待审批");
							workProjectNotify.setUser(new User(""));
						}else{
							workActivityProcess.setIsApproval("2");
							workBidingDocument.setStatus("5");//撤销
						}
						break;
					}
					// 未知环节
				}
			}

			//更新自定义的流程追踪数据
			String defaultReapply = "reapply"; //默认流程中的重新申请任务标识
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workBidingDocument.getProcessInstanceId(),taskDefKey,defaultReapply,workBidingDocument.getAct().getFlag(),comment, activities);

			// 设置意见
			workBidingDocument.getAct().setComment(comment);
			workBidingDocument.preUpdate();

			// 提交流程任务
			Map<String, Object> vars = Maps.newHashMap();
			vars.put(exp, "yes".equals(workBidingDocument.getAct().getFlag()) ?true : false );
			System.out.println("vars======"+vars.toString());
			// 提交流程任务
			actTaskService.complete(workBidingDocument.getAct().getTaskId(), workBidingDocument.getAct().getProcInsId(), workBidingDocument.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workBidingDocument.getAct().getProcInsId());
			//流程结束可能是审批通过、驳回、或撤销
			//state=false流程结束，state=true流程未结束
			if (!state){

				if(isCustomProcess){
					if("yes".equals(workBidingDocument.getAct().getFlag())){
						workBidingDocument.setStatus("3");
					}else{
						if(! "4".equals(workBidingDocument.getStatus()))
							workBidingDocument.setStatus("5");
					}
				}

				//终审之后，发送通知给创建人
				if("3".equals(workBidingDocument.getStatus())){
					workProjectNotify.setTitle("您的标书编制申请已通过");
				}
				if("4".equals(workBidingDocument.getStatus())){
					workProjectNotify.setTitle("您的标书编制申请被驳回");
				}
				workProjectNotify.setRemarks("待通知");//用于在通知页面做查看操作，这一步必须
				workProjectNotify.setNotifyRole("");
				workProjectNotify.setUser(workBidingDocument.getCreateBy());

			}
			//流程未结束，一定是"审批中"
			else{

				//尚未到终审，
				//workProjectNotify.setRemarks("待审批");//用于在通知页面做审核操作，这一步必须
				//如果是自定义流程，则需要先知道下一步(可能是撤销到某一步)的执行人(角色)是谁
				if (isCustomProcess) {
					String count = taskDefKey.replace("audit","").replace("task","");
					Activity activity = new Activity();
					////撤销到某一步
					if (taskDefKey.contains("audit")) {
						if (activities.size() == 1 || count.equals("1")){
							activity = activities.get(0);
						}else if (activities.size()==Integer.parseInt(count)){
							activity = activities.get(activities.size()-1);
							String returnBack = activity.getReturnBack();
							if (returnBack.equals("1")){
								activity = activities.get(Integer.parseInt(count)-2);
							}else if (returnBack.equals("2")){
								activity = activities.get(0);
							}
						}else {
							activity = activities.get(Integer.parseInt(count)-1);
							String returnBack = activity.getReturnBack();
							if (returnBack.equals("1")){
								activity = activities.get(Integer.parseInt(count)-2);
							}else if (returnBack.equals("2")){
								activity = activities.get(0);
							}
						}
					}
					//中间步骤驳回
					else if(!"yes".equals(workBidingDocument.getAct().getFlag())){
						//驳回之后，创建人可以发起重申|撤销;将通知消息归类到审批列表，这一步必须
						//对通知的人（创建人）的设定在前面已完成
						workProjectNotify.setRemarks("重新申请");
						activity = new Activity();//驳回后将id置空
					}
					//中间某步骤同意
					else {
						//得到下一步要执行的activity
						activity = activities.get(Integer.parseInt(count));
						workProjectNotify.setRemarks("待审批");
					}
					//发送审批消息给下一步的人(角色)
					if(StringUtils.isNotBlank(activity.getId())){//在驳回时不走这一步，判断id必须
						workProjectNotify.setUser(activity.getUser());
						workProjectNotify.setNotifyRole(activity.getRole().getEnname());
					}
				}
				//如果是默认流程，
				else{
					//状态在前面已经设置
				}

			}

			//发送通知
			workProjectNotify.setNotifyId(workBidingDocument.getId());
			workProjectNotify.setCompanyId(workBidingDocument.getCompanyId());
			workProjectNotify.setContent(workBidingDocument.getAct().getComment());
			workProjectNotify.setType("5");
			workProjectNotify.setStatus("0");

			if(! "5".equals(workBidingDocument.getStatus())){
				//如果是自定义流程：
				if(isCustomProcess){
					workProjectNotifyService.save(workProjectNotify);
				}else{

					if(StringUtils.isNotBlank(bmzr)){
						workProjectNotify.setId("");
						workProjectNotify.setNotifyRole(bmzr);
						workProjectNotifyService.save(workProjectNotify);
					}
					if(StringUtils.isNotBlank(zjl)){
						workProjectNotify.setId("");
						workProjectNotify.setNotifyRole(zjl);
						workProjectNotifyService.save(workProjectNotify);
					}
					if(StringUtils.isNotBlank(dsz)){
						workProjectNotify.setId("");
						workProjectNotify.setNotifyRole(dsz);
						workProjectNotifyService.save(workProjectNotify);
					}
					if(StringUtils.isNotBlank(workProjectNotify.getUser().getId())){
						workProjectNotify.setId("");
						workProjectNotifyService.save(workProjectNotify);
					}
				}
			}

			//更新标书审核状态
			workBidingDocumentDao.updateStatus(workBidingDocument);

			//todo 不确定的需求1：当撤销后，删除这条标书，可以重新标书编制；
//			if("5".equals(workBidingDocument.getStatus())){
//				workBidingDocumentDao.delete(workBidingDocument);
//			}
			//todo 不确定的需求2：当撤销后，仍然保留这条数据，查看到的状态是已撤销；
			//TODO 然后给个可以重新编制标书，同时将这一条标书逻辑删除


			System.err.println("标书审批正常");
			return "审核执行成功";

		}catch (ActivitiObjectNotFoundException e){
			e.printStackTrace();
			System.err.println("标书编制--重复审批");
			logger.error("ActivitiObjectNotFoundException -- "+e);
			return "流程已审批，不能重新审批！";
		}
		catch (Exception e) {
			e.printStackTrace();
			System.err.println("标书审批异常");
			logger.error("Exception e:"+e);
			return "审核执行失败！！";
		}
	}
	//中标维护（仅项目登记人可以操作）
	public Page<WorkBidingDocument> documentMaintain(Page<WorkBidingDocument> page, WorkBidingDocument workBidingDocument) {
		workBidingDocument.getSqlMap().put("dsf", dataScopeFilter(workBidingDocument.getCurrentUser(), "o", "u","", MenuStatusEnum.END.getValue()));
		workBidingDocument.setPage(page);
		page.setList(findMaintainList(workBidingDocument));
		return page;
	}
	//中标维护
	private List<WorkBidingDocument> findMaintainList(WorkBidingDocument workBidingDocument) {

		if(!UserUtils.getUser().isAdmin()){
			workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
			workBidingDocument.setOfficeId(UserUtils.getSelectOffice().getId());
		}

		List<WorkBidingDocument> maintainList =workBidingDocumentDao.findMaintainlistWithWorkBidProject(workBidingDocument);
		List<WorkClientLinkman> linkmanList =new ArrayList<WorkClientLinkman>();
		if(maintainList.size()>0){
			for(WorkBidingDocument document : maintainList){
				WorkBidProject workBidProject = document.getWorkBidProject();

				linkmanList = workClientInfoService.findLinkmanList(workBidProject.getId());
				workBidProject.setWorkClientLinkmanList(linkmanList);

				List<String> masterId = workBidProjectDao.getProjectMaster(workBidProject);
				List<User> masterList = new ArrayList<User>();
				for (int i = 0; i < masterId.size(); i++) {
					masterList.add(UserUtils.get(masterId.get(i)));
				}
				workBidProject.setMasterList(masterList);
				List<String> memberId = workBidProjectDao.getProjectMember(workBidProject);
				List<User> memberList = new ArrayList<User>();
				for (int i = 0; i < memberId.size(); i++) {
					memberList.add(UserUtils.get(memberId.get(i)));
				}
				workBidProject.setMemberList(memberList);

				Double documentCost = workBidProject.getDocumentCost();
				Double bindCost = workBidProject.getBindCost();
				Double otherCost = workBidProject.getOtherCost();
				BigDecimal bigDocumentCoset = new BigDecimal(documentCost==null?"00": documentCost+"");
				BigDecimal bigBindCost = new BigDecimal(bindCost==null?"00":bindCost+"");
				BigDecimal bigOtherCost = new BigDecimal(otherCost==null?"00":otherCost+"");
				String totalAmount = bigDocumentCoset.add(bigBindCost).add(bigOtherCost).toString();
				//投标费用
				document.setName(totalAmount);

				//仅项目登记人可以选择送标员
				if(UserUtils.getUser().getId().toString().equals(workBidProject.getCreateBy().toString())){
					document.setOptionFlag("1");
				}else {
					document.setOptionFlag("0");
				}

				//选择送标员
				if(StringUtils.isNotBlank(document.getSender())){

					String senderName = UserUtils.get(document.getSender()).getName();
					document.setSender(senderName);
				}

			}
		}
		return maintainList;
	}

	@Transactional(readOnly = false)
	public void update(WorkBidingDocument workBidingDocument) {
		workBidingDocumentDao.update(workBidingDocument);
	}

	//确认定投标（仅送标员可以操作）
	public Page<WorkBidingDocument> documentConfirm(Page<WorkBidingDocument> page, WorkBidingDocument workBidingDocument) {
		workBidingDocument.setPage(page);
		page.setList(findConfirmList(workBidingDocument));
		return page;
	}
	//确认定投标
	private List<WorkBidingDocument> findConfirmList(WorkBidingDocument workBidingDocument) {
		//只允许送标员操作各自的页面
		String userId = UserUtils.getUser().getId();
		workBidingDocument.setName(userId);

		if(!UserUtils.getUser().isAdmin()){
			workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		}

		List<WorkBidingDocument> resultList = new ArrayList<>();
		List<WorkBidingDocument> list =workBidingDocumentDao.findConfirmlistWithWorkBidProject(workBidingDocument);
		List<WorkClientLinkman> linkmanList =new ArrayList<WorkClientLinkman>();
		if(list != null && list.size()>0){
			for(WorkBidingDocument w : list){
				if(StringUtils.isNotBlank(w.getSender())){
					resultList.add(w);
				}
			}
		}
		if(resultList != null && resultList.size()>0){
			for(WorkBidingDocument document : resultList){
				WorkBidProject workBidProject = document.getWorkBidProject();

				linkmanList = workClientInfoService.findLinkmanList(workBidProject.getId());
				workBidProject.setWorkClientLinkmanList(linkmanList);

				List<String> masterId = workBidProjectDao.getProjectMaster(workBidProject);
				List<User> masterList = new ArrayList<User>();
				for (int i = 0; i < masterId.size(); i++) {
					masterList.add(UserUtils.get(masterId.get(i)));
				}
				workBidProject.setMasterList(masterList);
				List<String> memberId = workBidProjectDao.getProjectMember(workBidProject);
				List<User> memberList = new ArrayList<User>();
				for (int i = 0; i < memberId.size(); i++) {
					memberList.add(UserUtils.get(memberId.get(i)));
				}
				workBidProject.setMemberList(memberList);

				Double documentCost = workBidProject.getDocumentCost();
				Double bindCost = workBidProject.getBindCost();
				Double otherCost = workBidProject.getOtherCost();
				BigDecimal bigDocumentCoset = new BigDecimal(documentCost==null?"00": documentCost+"");
				BigDecimal bigBindCost = new BigDecimal(bindCost==null?"00":bindCost+"");
				BigDecimal bigOtherCost = new BigDecimal(otherCost==null?"00":otherCost+"");
				String totalAmount = bigDocumentCoset.add(bigBindCost).add(bigOtherCost).toString();
				//投标费用
				document.setName(totalAmount);

				//回显送标员姓名
				if(StringUtils.isNotBlank(document.getSender())){
					String senderName = UserUtils.get(document.getSender()).getName();
					document.setSender(senderName);
				}
			}
		}
		return resultList;
	}

	//确认定投标，并更改投标状态为投标进行中
	@Transactional(readOnly = false)
	public void confirmSave(WorkBidProject workBidProject , WorkBidingDocument workBidingDocument) throws Exception {
		WorkBidProject t = workBidProjectService.get(workBidProject.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workBidProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		String depts = workBidProject.getImplementingDeptIds();
		String masters = workBidProject.getProjectMasterIds();
		String contacts = workBidProject.getContacts();
		t.setImplementingDept(depts);
		t.setProjectMaster(masters);
		t.setContacts(contacts);
		t.setCompanyId(UserUtils.getSelectCompany().getId());
		workBidProjectService.save(t);//修改项目
		workBidingDocument.setBidStatus("1");//修改中标状态为 投标进行中（0待投标，1投标进行中，2中标，3未中标）
		workBidingDocumentDao.updateBidStatus(workBidingDocument);//修改中标状态

		WorkProjectNotify workProjectNotify = workProjectNotifyService.getByWorkBidingDocument(workBidingDocument.getId());
		if(workProjectNotify!=null){
			workProjectNotify.setStatus("1");
			workProjectNotify.preUpdate();
			workProjectNotifyDao.update(workProjectNotify);
		}

		//项目归档
		WorkProject workProject = workProjectService.get(t.getWorkProject().getId());
		workProject.setState("1");//1为能归档
		workProjectDao.updateStatus(workProject);
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		buffer.append("gd");
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setRemarks("待通知");
		notify.setType("5");
		notify.setTitle("新的项目已投标");
		notify.setContent("新的项目已投标");
		notify.setStatus("0");
		notify.setCompanyId(workBidingDocument.getCompanyId());
		notify.setNotifyId(workBidingDocument.getId());
		notify.setUser(new User(""));
		notify.setNotifyRole(buffer.toString());
		workProjectNotifyService.save(notify);
	}
	@Transactional(readOnly = false)
	public void updateSender(String senderId, String workBidingDocumentId) {
		Map<String,String> map = new HashMap<>();
		map.put("senderId",senderId);
		map.put("workBidingDocumentId",workBidingDocumentId);
		workBidingDocumentDao.updateSender(map);

		//由于送标员可以多次选择，如果多次选择同一个人就会发送重复的通知，必须先删除历史数据；
		WorkProjectNotify workProjectNotify = workProjectNotifyService.getByWorkBidingDocument(workBidingDocumentId);
		if(workProjectNotify!=null){
			workProjectNotifyService.delete(workProjectNotify);
		}

		WorkBidingDocument document = super.get(workBidingDocumentId);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setTitle("有新的定投标任务等待您确认");
		notify.setNotifyId(document.getId());
		notify.setUser(UserUtils.get(document.getSender()));
		notify.setCompanyId(document.getCompanyId());
		notify.setContent("确认定投标");
		notify.setRemarks("待审批");
		notify.setType("6");
		notify.setStatus("0");
		workProjectNotifyService.save(notify);

	}
	//更新数据
	public void updateData(WorkBidingDocument workBidingDocument,MultipartHttpServletRequest multiRequest) {
		WorkBidProject workBidProject = workBidingDocument.getWorkBidProject();
		workBidingDocument.setWorkBidProject(workBidProject);
		workBidingDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		super.save(workBidingDocument);
		uploadattachment(multiRequest,workBidingDocument);
	}
}