package com.goafanti.weChat.service.impl;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.*;
import com.goafanti.weChat.bo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;

import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.SendEmailUtil;
import com.goafanti.common.utils.WeChatUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.FollowBusinessBo;
import com.goafanti.customer.service.CustomerService;
import com.goafanti.weChat.service.PublicReleaseService;
import com.goafanti.core.websocket.SystemWebSocketHandler;

import cn.jiguang.common.utils.StringUtils;

@Service
public class PublicReleaseServiceImpl extends BaseMybatisDao<PublicReleaseMapper> implements PublicReleaseService {
	@Autowired
	private PublicReleaseMapper	publicReleaseMapper;
	@Autowired
	private PublicReleaseLogMapper publicReleaseLogMapper;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private PublicReleaseDetailsMapper publicReleaseDetailsMapper;
	@Autowired
	private WeChatUtils weChatUtils;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private	AsyncUtils asyncUtils;
	@Autowired
	private	UserMapper	userMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private SystemWebSocketHandler	systemWebSocketHandler;
	@Autowired
	private TOrderNewMapper tOrderNewMapper;
	@Autowired
	private DepartmentService	departmentService;
	@Autowired
	private PublicExamineMapper publicExamineMapper;

	@Override
	@Transactional
	public Map<String, Object> addPublicRelease(InputPublicRelease in) {
		Date date =new Date();
		if (in.getPublicAgain()==null)in.setPublicAgain(0);
		in.setCreateTime(date);
		in.setPublicType(0);
		in.setStatus(1);
		in.setAid(TokenManager.getAdminId());
		AdminListBo my = adminMapper.getDeptNameByAid(TokenManager.getAdminId());
		if (in.getAssist()==1){
//			in.setAssistAidName(getAssistAidName(in.getAssistAid()));
			in.setMainName(my.getName());
		}
		publicReleaseMapper.insertSelective(in);
		List<PublicReleaseDetails> prdList=new ArrayList<>();
		List<User> users=new ArrayList<>();
		StringBuffer str =new StringBuffer();
		if (in.getUids()!=null){
			List<String> split = Arrays.asList(in.getUids().split(","));
			int userCount=split.size();
			Double duration = in.getDuration();
			//计算平均
			double d = durationSum(duration, userCount);
			Integer index=1;
			//获取非已企业公出需要的审核人员
			for (String s : split) {
				PublicReleaseDetails prd=new PublicReleaseDetails();
				User u=userMapper.selectByPrimaryKey(s);
					users.add(u);
				str.append(u.getNickname()).append(",");
				if (u!=null&&u.getShareType()==2){
					prd.setNewUser(1);
				}else {
					prd.setNewUser(0);
				}
				if (u.getAid().equals(in.getAid())){
					prd.setMainStatus(1);
				}else {
					prd.setMainStatus(0);
				}
				prd.setPrid(in.getId());
				prd.setUid(s);
				prd.setSignSum(0);
				prd.setClockIn(0);
				prd.setDistrictName(in.getDistrictName());
				prd.setLatitude(in.getLatitude());
				prd.setLongitude(in.getLongitude());
				if (index<userCount){
					if (duration==0){
						prd.setDuration(duration);
					} else {
						prd.setDuration(d);
						duration=duration-d;
					}
					index++;
				}else {
					prd.setDuration(duration);
				}
				prdList.add(prd);
			}
			publicReleaseDetailsMapper.insertBatch(prdList);
		}
		String userNames=str.substring(0,str.length()-1);
		in.setUserNames(userNames);
		addpublicLog(in.getId(), PublicReleaseLog.states.fq.getCode(), "发起外出申请");
		Map<String, Object> map=addPublicReleaseLog(my, in,userNames,date,users);
		return map;
	}

	private void addPublicExamine(Integer id, String aid) {
		Admin admin = adminMapper.selectByPrimaryKey(aid);
		addPublicExamine(id,admin);
	}

	private void addPublicExamine(Integer id, Admin a) {
		List<PublicExamine> publicExamines = publicExamineMapper.selectByPrid(id);
		boolean flag=false;
		for (PublicExamine pe : publicExamines) {
			if (pe.getAid().equals(a.getId())){
				flag=true;
			}
		}
		if (!flag){
			PublicExamine pe=new PublicExamine();
			pe.setPrid(id);
			pe.setAid(a.getId());
			pe.setAname(a.getName());
			pe.setStatus(0);
			publicExamineMapper.insertSelective(pe);
		}
	}


	private  double durationSum(Double duration, Integer sum) {
			Double counts= Math.floor(duration/0.5);
			//计算当前时间
			Double my=Math.floor(counts/sum)*0.5;
			if (my<0.5)return 0.5;
			return my;
	}



	/**
	 *
	 * @param my 我的相关人员
	 * @param in 公出信息
	 * @param nickname	客户名称
	 * @param date	时间
	 */
	private Map<String, Object> addPublicReleaseLog(AdminListBo my,PublicRelease in,String nickname,Date date,List<User> users) {
		//获取公出审核人
		Admin a=adminMapper.selectByPrimaryKey(my.getReviewer());
		String str="["+my.getName()+"]发起["+nickname+"]的外出申请,请及时审核。";
		//默认上级审核
		AtomicReference<Integer> status= new AtomicReference<>(1);
		Map<String, Object>map=new HashMap<String, Object>();
		//不是业务员
		if (in.getType()==0){
			if (my.getPublicPurview()==0){
				users.forEach(u->{
					if (!u.getAid().equals(my.getId())){
						StringBuffer str2=new StringBuffer();
						str2=str2.append(my.getName()).append("(需审核)，准备公出您的企业");
						str2=str2.append("[").append(u.getNickname()).append("]!!!。");
						sendEmailAndNoticeAndSoucket(u.getAid(),3,str2.toString());
						Admin admin = adminMapper.selectByPrimaryKey(u.getAid());
						if (in.getType()==0){
							//不是自己的企业则需要审核并设置非自己客户待审核
							addPublicExamine(in.getId(), admin);
							if(in.getPublicType()==null|| in.getPublicType()==0)in.setPublicType(1);
						}
						pushNoticeAndSoucketAndEmail(my, in, date, admin, str, map);
						status.set(0);
					}
				});
			}else {
				users.forEach(u->{
					if (!u.getAid().equals(my.getId())){
						StringBuffer str2=new StringBuffer();
						str2=str2.append("业务员").append(my.getName()).append("(无需审核)，准备公出您的企业");
						str2=str2.append("[").append(u.getNickname()).append("]!!!");
						sendNoticeAndSoucket(u.getAid(),3,str2.toString());
					}
				});

			}
		}

		if (status.get()==1){
			pushNoticeAndSoucketAndEmail(my, in, date, a, str, map);
		}
			publicReleaseMapper.updateByPrimaryKeySelective(in);
			map.put("data", publicReleaseMapper.selectDtails(in.getId()));
		return map;
	}

	/**
	 *
	 * @param my 发送人信息
	 * @param in 公出信息
	 * @param date 时间
	 * @param a  接受者信息
	 * @param str  站内信内容
	 * @param map 返回实体
	 */
	private void pushNoticeAndSoucketAndEmail(AdminListBo my, PublicRelease in, Date date, Admin a,  String str, Map<String, Object> map) {
		sendNoticeAndSoucket(a.getId(),1, str);
		if (a.getOpenId() !=null) {
			Integer res= weChatUtils.addNotice(a.getOpenId(), in.getStatus(), in.getId(), date, my.getName(),"["+ my.getName()+"]发起外出申请");
			if (res!=0) {
				sendEmail(my, a,1);
			}
			map.put("code", res);
		}else {
			sendEmail(my, a,1);
			map.put("code", 2);
		}
	}

	private String getAssistAidName(String assistAid) {
		String [] ss=assistAid.split(",");
		StringBuffer sb=new StringBuffer();
		for (String s : ss) {
			Admin a=adminMapper.selectByPrimaryKey(s);
			if (a!=null&&a.getName()!=null)sb=sb.append(a.getName()).append(",");
		}
		if (sb.length()<1)return "";
		return  sb.deleteCharAt(sb.length() - 1).toString();
	}

	private void sendEmailAndNoticeAndSoucket(String id,Integer type,String content){
		sendNoticeAndSoucket(id,type,content);
		Admin admin = adminMapper.selectByPrimaryKey(id);
		String title="暂无标题";
		if (type==3)title=NoticeStatus.PUBLIC_OTHERS_USER.getDesc();
		EmailBo emailBo=new EmailBo(title,admin.getEmail(),content);
		asyncUtils.send(emailBo);

	}

	/**
	 *
	 * @param id 接受者编号
	 * @param type 状态 0驳回 1发起 2同意 3 公出他人企业
	 * @param content 内容
	 */
	private void sendNoticeAndSoucket(String id,Integer type,String content) {
		Integer noticeType=NoticeStatus.PUBLIC_RELEASE_START.getCode();
		if(type==0)noticeType=NoticeStatus.PUBLIC_RELEASE_NO.getCode();
			else if (type==2)noticeType=NoticeStatus.PUBLIC_RELEASE_YES.getCode();
			else if (type==3)noticeType=NoticeStatus.PUBLIC_OTHERS_USER.getCode();
			//触发通知有未读消息
		systemWebSocketHandler.sendMessageToUser(id, new TextMessage("unread"));
		Notice n =new Notice();
		n.setId(UUID.randomUUID().toString());
		n.setAid(id);
		n.setNoticeType(noticeType);
		n.setContent(content);
		n.setReaded(0);//未读
		asyncUtils.addNotice(n);
	}

	/**
	 *
	 * @param my 发送人
	 * @param a 接受者
	 * @param type 类型
	 */
	private void sendEmail(AdminListBo my, Admin a,Integer type) {
		StringBuffer title=new StringBuffer();
		if (type==0) title=title.append("外出申请驳回提醒");
		else if (type==1) title=title.append("外出申请提醒");
		else if (type==2) title=title.append("外出申请同意提醒");
		if (SendEmailUtil.isEmail(a.getEmail())) {
			EmailBo email=new EmailBo(title.toString(),a.getEmail() , my.getDepartmentName(), my.getName(),"详情请登录微信打卡小程序查看,谢谢!") ;
			asyncUtils.send(email);
		}
	}



	@Override
	public int updatePublicRelease(InputPublicRelease in) {
		Date date = new Date();
		try {
			if(in.getReleaseStarts()!=null)in.setReleaseStart(DateUtils.parseDate(in.getReleaseStarts(), AFTConstants.YYYYMMDDHHMMSS));
			if(in.getReleaseEnds()!=null)in.setReleaseEnd(DateUtils.parseDate(in.getReleaseEnds(), AFTConstants.YYYYMMDDHHMMSS));
		} catch (ParseException e) {
			e.printStackTrace();
			throw new BusinessException("转换异常");
		}
		List<User> uses=null;
		PublicRelease use = publicReleaseMapper.selectByPrimaryKey(in.getId());

		String userNames=publicReleaseDetailsMapper.getNamesByPrid(in.getId());
		PublicReleaseLog log=new PublicReleaseLog(in.getId(),TokenManager.getAdminId(),null,in.getReason(),date);
		in.setUserNames(userNames);
		if(in.getStatus()==null||in.getStatus()!=3) {
			if (in.getUids()!=null){
				List<String> split = Arrays.asList(in.getUids().split(","));
				List<OutPublicReleaseDetails> prList = publicReleaseDetailsMapper.selectByPCid(in.getId());
				uses=pushPublicReleaseDetails(split,prList,use,in);
			}
			in.setStatus(1);
			log.setStatus(PublicReleaseLog.states.xg.getCode());
			in.setUpdateStatus(1);
			//如果是业务切公出则撤销营销审核与审核人
			if(in.getType()==1&&use.getType()==0){
				in.setPublicType(0);
				publicExamineMapper.deletePrid(in.getId());
			}
			//如果是业务公出，切审核状态为其他，则重置审核
			if(in.getType()==0&&(use.getPublicType()==2||use.getPublicType()==3)){
				in.setPublicType(1);
				PublicExamine pe=new PublicExamine();
				pe.setPrid(in.getId());
				pe.setStatus(0);
				publicExamineMapper.updatePrid(pe);
			}
			AdminListBo my = adminMapper.getDeptNameByAid(TokenManager.getAdminId());

			//重新发起
			addPublicReleaseLog(my,in,in.getUserNames(),date,uses);
		}else {
			List<PublicRelease> list = publicReleaseMapper.selectByMainId(in.getId(),3,null);
			List<PublicRelease> list2 = publicReleaseMapper.selectByMainId(in.getId(),4,null);
			log.setStatus(PublicReleaseLog.states.cx.getCode());
			for (PublicRelease out : list) {
				addpublicLog(out.getId(), PublicReleaseLog.states.sc.getCode(), "修改撤销协单");
				out.setStatus(3);
				publicReleaseMapper.updateByPrimaryKeySelective(out);
			}

			for (PublicRelease out : list2) {
				addpublicLog(out.getId(), PublicReleaseLog.states.sc.getCode(), "修改撤销协单助手");
				out.setStatus(3);
				publicReleaseMapper.updateByPrimaryKeySelective(out);
			}
		}
		publicReleaseLogMapper.insertSelective(log);
		publicReleaseMapper.updateByPrimaryKeySelective(in);

		return 1;
	}

	private List<User> pushPublicReleaseDetails(List<String> split, List<OutPublicReleaseDetails> prList, PublicRelease use, InputPublicRelease in) {
		//先删除，再修改个，再新增，有利于减少计算
		deletePRD(split,prList);
		publicReleaseDetailsMapper.updateDistrictByPrid(in);
		List<User> users = addPRD(split, prList, use,in);


		return users;
	}



	private void deletePRD(List<String> split, List<OutPublicReleaseDetails> prdList) {
		for (OutPublicReleaseDetails prd : prdList) {
			boolean flag=true;
			for (String s : split) {
				if (prd.getUid().equals(s)){
					flag=false;
				}
			}
			if (flag){
				publicReleaseDetailsMapper.deleteByPrimaryKey(prd.getId());
			}
		}
	}

	/**
	 *  @param split 修改后客户集
	 * @param prdList 修改前客户集
	 * @param use 原订单信息
	 */
	private List<User>  addPRD(List<String> split, List<OutPublicReleaseDetails> prdList, PublicRelease use, InputPublicRelease in) {
		List<PublicReleaseDetails> addPrdList=new ArrayList<>();
		List<User> users=new ArrayList<>();
		Integer publicType = use.getPublicType();
		//计算平均
		Integer userCount=split.size();
		Integer index=0;
		Double duration= in.getDuration();
 		double d = durationSum(duration,userCount );
		for (String s : split) {
			User u=userMapper.selectByPrimaryKey(s);
			users.add(u);
			boolean flag=true;
			Integer id=null;
			String districtName=null,latitude=null,longitude=null;
			for (OutPublicReleaseDetails prd : prdList) {
				if (id==null)id=prd.getPrid();
				if (districtName==null)districtName=prd.getDistrictName();
				if (latitude==null)latitude=prd.getLatitude();
				if (longitude==null)longitude=prd.getLongitude();
				if (s.equals(prd.getUid())){
					flag=false;

				}
			}
			//计算下
			if (flag){
				PublicReleaseDetails prd=new PublicReleaseDetails();
				if (u!=null&&u.getShareType()==2){
					prd.setNewUser(1);
				}else {
					prd.setNewUser(0);
				}
				if (u.getAid().equals(use.getAid())){
					prd.setMainStatus(1);
				}else {
					prd.setMainStatus(0);
				}
				prd.setPrid(id);
				prd.setUid(s);
				prd.setSignSum(0);
				prd.setDistrictName(districtName);
				prd.setLatitude(latitude);
				prd.setLongitude(longitude);
				prd.setClockIn(0);
				addPrdList.add(prd);
				//设置时长
				if (index<userCount){
					if (in.getDuration()==0){
						prd.setDuration(in.getDuration());
					} else {
						prd.setDuration(d);
						duration=duration-d;
					}
				}else {
					prd.setDuration(duration);
				}
				index++;
				if (!use.getAid().equals(u.getAid())){
					addPublicExamine(use.getId(), u.getAid());
					if (publicType==1)publicType=1;
				}
			}else {
				InputPublicRelease inp=new InputPublicRelease();
				inp.setId(in.getId());
				inp.setUid(s);
				PublicReleaseDetails publicReleaseDetails = publicReleaseDetailsMapper.selectBypridAndUid(inp);
				PublicReleaseDetails newprd =new PublicReleaseDetails();
				newprd.setId(publicReleaseDetails.getId());
				//设置时长
				if (index<userCount){
					if (in.getDuration()==0){
						newprd.setDuration(in.getDuration());
					} else {
						newprd.setDuration(d);
						duration=duration-d;
					}
				}else {
					newprd.setDuration(duration);
				}
				index++;
				publicReleaseDetailsMapper.updateByPrimaryKeySelective(newprd);
			}
		}
		StringBuffer str=new StringBuffer();
		for (User u : users) {
			str=str.append(use.getUserNames()).append(",");
		}
		if (publicType!=use.getPublicType()){
			PublicRelease newP=new PublicRelease();
			newP.setId(use.getId());
			if (str.length()>1)newP.setUserNames(str.substring(0,str.length()-1));
			newP.setPublicType(publicType);
			publicReleaseMapper.updateByPrimaryKeySelective(newP);
		}
		if (!addPrdList.isEmpty())publicReleaseDetailsMapper.insertBatch(addPrdList);
		return users;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutPublicReleaseList> listPublicRelease(InputPublicReleaseList in) {
		Map<String,Object> map =new HashMap<String, Object>();
		map.put("type", in.getType()==null?0:in.getType());
		if (in.getType()==3) {
			in.setAssist(2);
			if (!TokenManager.hasRole(AFTConstants.TECH_FINANCE_DIRECTOR))map.put("aid",TokenManager.getAdminId());
		}else{
			map.put("aid",TokenManager.getAdminId());
		}
		if (StringUtils.isNotEmpty(in.getClockTime()))	map.put("clockTime", in.getClockTime());
		if(StringUtils.isNotEmpty(in.getReleaseStarts()))	map.put("releaseStarts", in.getReleaseStarts());
		if(StringUtils.isNotEmpty(in.getReleaseEnds()))	map.put("publicEnd", in.getReleaseEnds()+" 23:59:59");
		if(StringUtils.isNotEmpty(in.getUserName()))	map.put("userName", in.getUserName());
		if(in.getStatus()!=null)	map.put("status", in.getStatus());
		if(in.getClockIn()!=null)	map.put("clockIn", in.getClockIn());
		map.put("assist",in.getAssist()==null?0:in.getAssist());
		Pagination<OutPublicReleaseList> p=(Pagination<OutPublicReleaseList>) findPage("listPublicRelease", "countPublicRelease", map, in.getPageNo(), in.getPageSize());
		if(in.getType()==0||in.getType()==4){
			pushExamines(p);


		}
		return p;
	}

	private void pushExamines(Pagination<OutPublicReleaseList> p) {
		List<OutPublicReleaseList> list = (List<OutPublicReleaseList>) p.getList();
		if (!list.isEmpty()){
			List<Integer> ids=new ArrayList<>();
			list.forEach(e ->{ ids.add(e.getId()); });
			List<PublicExamine> publicExamines = publicExamineMapper.selectByIds(ids);
			for (OutPublicReleaseList e : list) {
				if (!publicExamines.isEmpty()){
					StringBuffer str =new StringBuffer();
					for (PublicExamine pe : publicExamines) {
						if (e.getId().equals(pe.getPrid())){
							str=str.append(pe.getAname());
							if (pe.getStatus()==0)str=str.append(" 未审核,");
							if (pe.getStatus()==1)str=str.append(" 已审核,");
						}
						if (str.length()>1) e.setAdminExamine(str.substring(0,str.length()-1));
					}

				}
			}
		}


	}

	@Override
	@Transactional
	public int pushExaminePublicRelease(Integer id, Integer status, String remarks,Integer examineType) {
		PublicRelease p=new PublicRelease();
		Date date =new Date();
		boolean flag=false;
		String aid=TokenManager.getAdminId();
		p.setId(id);
		PublicRelease use=publicReleaseMapper.selectByPrimaryKey(id);
		if (use.getStatus()!=1) {
			throw new BusinessException("只能修改发起的状态公出");
		}
		//当前审核人员
		Admin ad=adminMapper.selectByPrimaryKey(aid);
		//公出负责人
		Admin a;
		Admin publicAdmin =adminMapper.selectByPrimaryKey(use.getAid());
		a=publicAdmin;
		StringBuffer str=new StringBuffer();
		str=str.append("（").append(ad.getName()).append("）");
		StringBuffer content=new StringBuffer().append("[").append(use.getUserNames()).append("]公司的外出申请,");
		//上级审核
		if(examineType==0){
			p.setStatus(status);
			if (status==0){
				str=str.append("驳回，");
				if (use.getAssist()==2){
					content=content.append("技术协单被[").append(ad.getName()).append("]拒绝!");
				}else {
					content=content.append("未通过公出审核!");
				}
				if(use.getPublicType()>1){
					p.setPublicType(1);
					PublicExamine inpe=new PublicExamine();
					inpe.setStatus(0);
					inpe.setPrid(use.getId());
					publicExamineMapper.updatePrid(inpe);
				}
			}else if(status==2){
				str=str.append("同意，");
				//如果是协单公出主公出，在审核通过
				if (use.getAssist()==1){
					pushPublicReleaseAssist(use,status,date,a);
				}else if (use.getAssist()==0){
					publicReleaseMapper.updateStatusByMainId(3,use.getId(),null,null);
				}
				content=content.append("已通过审核!");
			}
			str=str.append(remarks);
			p.setAuditInfo(str.toString());
			p.setAuditTime(date);
			p.setRejectName(ad.getName());
			addpublicLog(id, status, remarks);
			flag=true;
			//营销员审核
		}else if (examineType==1){
			//通知公出人切换成公出人审核人
			a=adminMapper.selectByPrimaryKey(a.getReviewer());
			if (status==2){//审核通过
				str=str.append("同意公出我的企业，").append(remarks);
				content=content.append("已通过审核,请尽快审核。");
				List<PublicExamine> publicExamines = publicExamineMapper.selectByPrid(use.getId());
				int x=0;
				for (PublicExamine pe : publicExamines) {
					if (pe.getAid().equals(aid)){
						pe.setStatus(1);
						PublicExamine newp=new PublicExamine();
						newp.setId(pe.getId());
						newp.setStatus(1);
						publicExamineMapper.updateByPrimaryKeySelective(newp);
						x++;
					}else {
						if (pe.getStatus()==1){
							x++;
						}
					}
				}
				if (x==publicExamines.size()){
					p.setPublicType(2);
					flag=true;
				}
				addpublicLog(id, status, str.toString());

			}else if (status==0){//审核驳回
				//切换通知人公出负责人
				a=publicAdmin;
				str=str.append("不同意公出我的企业，").append(remarks);;
				content=content.append("未通过审核,请修改后重新发起。");
				p.setPublicType(3);
				p.setStatus(0);
				p.setAuditInfo(str.toString());
				p.setRejectName(ad.getName());
				addpublicLog(id, 0, str.toString());
			}
		}
		AdminListBo my = adminMapper.getDeptNameByAid(TokenManager.getAdminId());
		if (flag){
			sendNoticeAndSoucket(a.getId(),status,content.toString());
		}
		if (p.getStatus()!=null||p.getPublicType()!=null){
			publicReleaseMapper.updateByPrimaryKeySelective(p);
		}
		if (a.getOpenId()!=null) {
			if (remarks.length()>19) {
				remarks=remarks.substring(0, 15)+"...";
			}
			Integer res=weChatUtils.addNotice(a.getOpenId(),status,p.getId(),date,my.getName(),remarks);
			if (res!=0) {
				sendEmail( my,  a, status);

			}
			return res;
		}else {
		}
			return 1;
	}

	private void addpublicLog(Integer id, Integer status, String remarks) {
		PublicReleaseLog log = new PublicReleaseLog(id, TokenManager.getAdminId(), status, remarks, new Date());
		publicReleaseLogMapper.insertSelective(log);
	}

	@Override
	public int pushTechReject(Integer id,  String remarks) {
		Integer status=0;
		PublicRelease use=publicReleaseMapper.selectByPrimaryKey(id);
		PublicRelease mainPublic= publicReleaseMapper.selectByPrimaryKey(use.getMainId());
		Admin ad=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
		StringBuffer str=new StringBuffer();
		if (use.getAssist()!=2){
			throw  new BusinessException("只有技术公出能发起技术驳回");
		}
		str=str.append("拒绝技术协单，").append(remarks);
		PublicRelease newMain=new PublicRelease();
		newMain.setId(mainPublic.getId());
		newMain.setStatus(4);
		newMain.setRejectName(ad.getName());
		newMain.setAuditInfo(str.toString());
		addWeChatNotice(mainPublic.getAid(),0,str.toString(),mainPublic.getId());
		publicReleaseMapper.updateByPrimaryKeySelective(newMain);
		PublicRelease up=new PublicRelease();
		up.setId(id);
		up.setAuditInfo(str.toString());
		up.setStatus(3);
		addpublicLog(id, status, remarks);
		publicReleaseMapper.updateByPrimaryKeySelective(up);
		deleteAssistantPulicRelease(use,null);
		return addNoticeAndWeChat(mainPublic.getId(), mainPublic.getAid(), str.toString(), status);
	}

	/**
	 * 新增日志、站内信、微信提醒
	 * @param id 日志公出编号
	 * @param aid 接受者
	 * @param remarks 日志内容
	 * @param status 0驳回
	 * @return
	 */
	private Integer addNoticeAndWeChat(Integer id,String aid, String remarks,  Integer status) {
		AdminListBo my = adminMapper.getDeptNameByAid(aid);
		Admin a = adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
		if (my.getOpenId()!=null) {
			if (remarks.length()>19) {
				remarks=remarks.substring(0, 15)+"...";
			}
			return weChatUtils.addNotice(my.getOpenId(),status,id,new Date(),my.getName(), remarks);
		}else {
			sendEmail( my,  a, status);
			return 1;
		}
	}

	/**
	 *
	 * @param use 原始公出信息
	 * @param status 状态
	 * @param date 时间
	 * @param a
	 */
	private void pushPublicReleaseAssist(PublicRelease use,Integer status,Date date,Admin a) {
		if (use.getAssistAid()!=null){
			updatePushassist(use, status, date,a);
			if(use.getAssistantAid()!=null){
				updatepushAssistant(use,a);
			}

		}
	}

	/**
	 * 处理技术协单
	 * @param use
	 * @param status
	 * @param date
	 */
	private void updatePushassist(PublicRelease use, Integer status, Date date, Admin a) {
		//协单
		List<PublicRelease> list = publicReleaseMapper.selectByMainId(use.getId(),3,null);
		String []ss= use.getAssistAid().split(",");
		//数据库与传入比对，如果不存在就标记撤销 ，如果存在就修改成
		for (PublicRelease out : list) {
			boolean flag=false;
			for (String s : ss) {
				if (out.getAid().equals(s)){
					flag=true;
					break;
				}
			}
			if (!flag){
				PublicRelease in = new PublicRelease();
				in.setId(out.getId());
				in.setStatus(3);
				publicReleaseMapper.updateByPrimaryKeySelective(in);
				StringBuffer str = new StringBuffer("[").append(a.getName()).append("]取消公出").append("[").append(use.getUserNames()).append("]。");
				PublicReleaseLog log = new PublicReleaseLog(in.getId(), TokenManager.getAdminId(), PublicReleaseLog.states.cx.getCode(), str.toString(), date);
				publicReleaseLogMapper.insertSelective(log);
				sendNoticeAndSoucket(out.getAid(),in.getStatus(),str.toString());
			}else {
				PublicRelease np = new PublicRelease();
				BeanUtils.copyProperties(use,np);
				np.setId(out.getId());
				np.setMainId(null);
				np.setType(null);
				np.setAssist(2);
				np.setStatus(status);
				np.setAid(null);
				publicReleaseMapper.updateByPrimaryKeySelective(np);
				updatePublicReleaseDtails(use,np.getId());
				StringBuffer str = new StringBuffer("[").append(a.getName()).append("]修改了公出").append("[").append(use.getUserNames()).append("]。");
				PublicReleaseLog log = new PublicReleaseLog(np.getId(), TokenManager.getAdminId(), PublicReleaseLog.states.xg.getCode(),str.toString(), date);
				publicReleaseLogMapper.insertSelective(log);
				sendNoticeAndSoucket(out.getAid(),np.getStatus(),str.toString());
			}
		}
		for (String s : ss) {
			boolean flag2 = false;
			for (PublicRelease o : list) {
				if (s.equals(o.getAid())) {
					flag2 = true;
				}
			}
			if (!flag2) {
				PublicRelease np = new PublicRelease();
				BeanUtils.copyProperties(use,np);
				np.setAssist(2);
				np.setAid(s);
				np.setStatus(2);
				np.setType(3);
				np.setMainId(use.getId());
				np.setId(null);
				publicReleaseMapper.insertSelective(np);
				//补充客户表
				addpublicReleaseDtails(use,np.getId());
				StringBuffer str = new StringBuffer("[").append(a.getName()).append("]邀请你技术协单").append("[").append(use.getUserNames()).append("]。");
				PublicReleaseLog log = new PublicReleaseLog(np.getId(), TokenManager.getAdminId(), PublicReleaseLog.states.fq.getCode(), str.toString(), date);
				sendNoticeAndSoucket(np.getAid(),np.getStatus(),str.toString());
				publicReleaseLogMapper.insertSelective(log);
			}
		}
	}

	private void updatePublicReleaseDtails(PublicRelease use, Integer id) {
		List<OutPublicReleaseDetails> list = publicReleaseDetailsMapper.selectByPCid(use.getId());
		List<OutPublicReleaseDetails> list2 = publicReleaseDetailsMapper.selectByPCid(id);
		//查找新增的
		for (OutPublicReleaseDetails out : list) {
			boolean flag=true;
			for (OutPublicReleaseDetails out2 : list2) {
				if (out.getUid().equals(out2.getUid())){
					flag=false;
				}
			}
			if (flag){
				OutPublicReleaseDetails prd=new OutPublicReleaseDetails();
				BeanUtils.copyProperties(out,prd);
				prd.setPrid(id);
				prd.setClockIn(0);
				prd.setClockInTime(null);
				prd.setClockInRemarks(null);
				prd.setUfid(null);
				publicReleaseDetailsMapper.insertSelective(prd);
			}
		}

		for (OutPublicReleaseDetails out2 : list2) {
			boolean flag=true;
			for (OutPublicReleaseDetails out : list) {
				if (out2.getUid().equals(out.getUid())){
					flag=false;
				}
			}
			if (flag){
				publicReleaseDetailsMapper.deleteByPrimaryKey(out2.getId());
			}
		}

	}

	private void addpublicReleaseDtails(PublicRelease use, Integer id) {
		List<OutPublicReleaseDetails> list = publicReleaseDetailsMapper.selectByPCid(use.getId());
		for (OutPublicReleaseDetails out : list) {
			OutPublicReleaseDetails prd=new OutPublicReleaseDetails();
			BeanUtils.copyProperties(out,prd);
			prd.setPrid(id);
			prd.setClockIn(0);
			prd.setClockInTime(null);
			prd.setMainStatus(0);
			publicReleaseDetailsMapper.insertSelective(prd);
		}
	}

	/**
	 * 处理技术助手
	 * @param use
	 */
	private void updatepushAssistant(PublicRelease use,Admin a) {
		List<PublicRelease> uselist = publicReleaseMapper.selectByMainId(use.getId(),4,null);
		for (PublicRelease p : uselist) {
					if(!use.getReleaseStart().equals(p.getReleaseStart()))p.setReleaseStart(use.getReleaseStart());
					if (!use.getReleaseEnd().equals(p.getReleaseEnd()))p.setReleaseEnd(use.getReleaseEnd());
					p.setStatus(2);
					p.setAssistantAid(use.getAssistantAid());
					p.setAssistantName(use.getAssistantName());
					p.setUserNames(use.getUserNames());
					publicReleaseMapper.updateByPrimaryKeySelective(p);
					StringBuffer str = new StringBuffer("[").append(a.getName()).append("]修改了").append("[").append(use.getUserNames()).append("]。");
					PublicReleaseLog log = new PublicReleaseLog(p.getId(), TokenManager.getAdminId(), PublicReleaseLog.states.ty.getCode(), str.toString(), new Date());
					sendNoticeAndSoucket(p.getAid(),p.getStatus(),str.toString());
					publicReleaseLogMapper.insertSelective(log);
		}
	}

	@Override
	public List<outPublicReleaseLog> listPublicReleaseLog(Integer id,String ufid) {
		List<outPublicReleaseLog> list=publicReleaseLogMapper.listPublicReleaseLog(id,ufid);
		return list;
	}


	@Override
	public int pushPublicReleaseClockIn(Integer id,String photoUrl,Integer clockIn ,String clockInRemarks ,String uid) {
		if (clockIn == null) clockIn = 1;
		PublicRelease use = publicReleaseMapper.selectByPrimaryKey(id);
		if (use.getPublicType()==1||use.getPublicType()==3){
			return -1;
		}
		List<OutPublicReleaseDetails> prdList = publicReleaseDetailsMapper.selectByPCid(id);
		String str = "";
		boolean flag=false;
		Integer clockCount=0;
		for (OutPublicReleaseDetails prd : prdList) {
			if (prd.getUid().equals(uid)){
				String aid = TokenManager.getAdminId();
				prd.setClockInRemarks(clockInRemarks);
				prd.setPhotoUrl(photoUrl);
				prd.setClockInTime(new Date());
				if (prd.getClockIn() == 0) {
					prd.setClockIn(clockIn);
					//获取列表
					FollowBusinessBo fbb = new FollowBusinessBo();
					fbb.setUid(prd.getUid());
					fbb.setContactType("5");
					fbb.setResult(use.getRemarks());
					OrganizationContactBook ub = organizationContactBookMapper.getMajor(prd.getUid(), aid);
					if (ub != null) {
						fbb.setOcbId(ub.getId());
					}
					fbb.setFollowTime(DateUtils.formatDate(prd.getClockInTime(), AFTConstants.YYYYMMDDHHMMSS));
					String ufid = UUID.randomUUID().toString();
					prd.setUfid(ufid);
					customerService.addFollow(fbb, ufid, prd.getMainStatus());
					str = "公出人员打卡";
				}else if (clockIn == 2){
					str = "公出人员异常打卡";
				}else {
					str = "刷新打卡";
				}
				PublicReleaseLog log = new PublicReleaseLog(id, aid, PublicReleaseLog.states.dk.getCode(), str, new Date());
				log.setPhotoUrl(photoUrl);
				publicReleaseLogMapper.insertSelective(log);
				publicReleaseDetailsMapper.updateByPrimaryKeySelective(prd);
				flag=true;
				clockCount++;
			}else if (prd.getClockIn()==1){
				clockCount++;
			}
		}
		if (prdList.size()==clockCount){
			PublicRelease newp=new PublicRelease();
			newp.setId(id);
			newp.setClockIn(1);
			publicReleaseMapper.updateByPrimaryKeySelective(newp);
		}
		if (!flag){
			return 0;
		}
		return 1;
	}

	@Override
	public OutPublicRelease dtails(Integer id) {
		String aid=TokenManager.getAdminId();
		//如果不是本人和审核人员则不返回信息
		OutPublicRelease out=publicReleaseMapper.selectDtails(id);
		List<PublicExamine> ps = publicExamineMapper.selectByPrid(out.getId());
		out.setPeList(ps);
		if(out!=null){
			boolean flag=false;
			//自己、审核人员与部门负责人可以查看
			AdminListBo ab=adminMapper.getDeptNameByAid(out.getAid());
			if (!aid.equals( out.getAid())&&
					!aid.equals(out.getReviewer())&&
					!aid.equals(ab.getDepManager())&&
					!TokenManager.hasRole(AFTConstants.TECH_FINANCE_DIRECTOR)){
				flag=true;
			}
			//是否可以查看
			if (!ps.isEmpty()){
				for (PublicExamine p : ps) {
					if (p.getAid().equals(aid)){
						if (p.getStatus()==1)out.setMyExamine(1);
						else out.setMyExamine(0);
						flag=false;
						break;
					}
				}
			}
			if(flag){
				out=null;
				return out;
			}else {
				if (out.getPublicType()==1){
					if (aid.equals(out.getAid())){
						out.setPermission(0);
					}else {
						out.setPermission(1);
					}
				}else {
					if(aid.equals(out.getAid())) {
						out.setPermission(0);
					}else {
						out.setPermission(1);
					}
				}
			}
		}
		out.setPrdList(publicReleaseDetailsMapper.selectByPCid(out.getId()));
		return out;
	}



	@Override
	public OutPublicReleaseAndDetails followDtails(String id) {
		OutPublicReleaseAndDetails out = publicReleaseMapper.selectDtailsByFid( id);
		return out;
	}

	@SuppressWarnings("unchecked")
	@Override
//	@Cacheable(value = "publicReleaseStatistics#300", key = "'publicReleaseStatistics:" +
//			"aid:'+#in.aid+'depId:'+#in.depId+'clockStart:'+#in.clockStart+" +
//			"'clockEnd:'+#in.clockEnd+'createStart:'+#in.createStart+'createEnd'+#in.createEnd+" +
//			"'pageNo:'+#in.pageNo+'pageSzie:'+#in.pageSize")
	public Object publicReleaseStatistics(InputPublicStatistics in) {
		Map<String,Object> map =new HashMap<String, Object>();
		if(in.getAid()!=null)map.put("aid", in.getAid());
		if(in.getDepId()!=null)map.put("depId", in.getDepId());
		if(in.getClockStart()!=null)map.put("clockStart", in.getClockStart());
		if(in.getClockEnd()!=null)map.put("clockEnd", in.getClockEnd()+" 23:59:59");
		if(in.getCreateStart()!=null)map.put("createStart", in.getCreateStart());
		if(in.getCreateEnd()!=null)map.put("createEnd", in.getCreateEnd()+" 23:59:59");
		return (Pagination<OutPublicStatistics>) findPage("listPublicStatistics", "countPublicStatistics", map, in.getPageNo(), in.getPageSize());
	}



	@SuppressWarnings("unchecked")
	@Override
	public List<OutPublicStatistics> publicReleaseStatisticsList(InputPublicStatistics in) {
		Map<String,Object> map =new HashMap<String, Object>();
		if(in.getAid()!=null)map.put("aid", in.getAid());
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)|| TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||
				TokenManager.hasRole(AFTConstants.CED)|| TokenManager.hasRole(AFTConstants.CED_ASSISTANT)){
			if(in.getDepId()!=null)map.put("depId", in.getDepId());
		}else if (TokenManager.hasRole(AFTConstants.COMPANY_MANAGER)||TokenManager.hasRole(AFTConstants.PERSONNEL_AUDITOR)){
		}
		if(in.getClockStart()!=null)map.put("clockStart", in.getClockStart());
		if(in.getClockEnd()!=null)map.put("clockEnd", in.getClockEnd()+" 23:59:59");
		if(in.getCreateStart()!=null)map.put("createStart", in.getCreateStart());
		if(in.getCreateEnd()!=null)map.put("createEnd", in.getCreateEnd()+" 23:59:59");
		return (List<OutPublicStatistics>) findList("listPublicStatistics",map, in.getPageNo(), 99999);
	}





	@SuppressWarnings("unchecked")
	@Override
	public Object publicReleaseListDtails(InputPublicDtails in) {
		Map<String,Object> map =new HashMap<String, Object>();
		addParams(in, map);
		Pagination<OutPublicDtails> page = (Pagination<OutPublicDtails>) findPage("listPublicDtails", "countPublicDtails", map, in.getPageNo(), in.getPageSize());
		return page;
	}

	private void addParams(InputPublicDtails in, Map<String, Object> map) {
		if(in.getAid()!=null) map.put("aid", in.getAid());
		if(in.getSid()!=null) map.put("sid", in.getSid());
		if(in.getReleaseStart()!=null) map.put("releaseStart", in.getReleaseStart());
		if(in.getReleaseEnd()!=null) map.put("releaseEnd", in.getReleaseEnd()+" 23:59:59");
		if(in.getCreateStart()!=null) map.put("createStart", in.getCreateStart());
		if(in.getCreateEnd()!=null) map.put("createEnd", in.getCreateEnd()+" 23:59:59");
		if(in.getUid()!=null) map.put("uid", in.getUid());
		if(in.getContractNo()!=null) map.put("contractNo", in.getContractNo());
		if(in.getStatus()!=null) map.put("status", in.getStatus());
		if(in.getClockIn()!=null) map.put("clockIn", in.getClockIn());
		if(in.getPublicType()!=null)map.put("publicType",in.getPublicType());
		//type 0私有 1管理权限 2所有权限
		if(TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)
				||TokenManager.hasRole(AFTConstants.CED_ASSISTANT )||TokenManager.hasRole(AFTConstants.PERSONNEL_AUDITOR)
					||TokenManager.hasRole(AFTConstants.FINANCE_ADMIN)
					||TokenManager.hasRole(AFTConstants.FINANCE)||TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)){
			//添加财务和财务经理。查看客户所有公出
			in.setType(2);
			if(in.getDeps()!=null){
				map.put("deps", departmentService.parseArray(in.getDeps()));
			}
		}else if(TokenManager.hasRole(AFTConstants.COMPANY_MANAGER)||TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)||TokenManager.hasRole(AFTConstants.OPERATION_MANAGER)){
			in.setType(1);
			if (in.getDeps()!=null){
				List<String> list = departmentService.selectSubDeps(in.getDeps());
				if (list.isEmpty()) throw new BusinessException("无权查看此部门信息");
				map.put("deps", list);
			}else {
				map.put("deps",departmentService.selectMyDeps());
			}
		}else{
			in.setType(0);
			if (in.getAid()==null) map.put("aid",TokenManager.getAdminId());
			if(in.getDeps()!=null){
				map.put("deps", departmentService.parseArray(in.getDeps()));
			}
		}
		map.put("type", in.getType());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OutPublicDtails> publicReleaseListDtailsList(InputPublicDtails in) {
		Map<String,Object> map =new HashMap<String, Object>();
		addParams(in, map);
		return (List<OutPublicDtails>) findList("listPublicDtails", map, in.getPageNo(), 99999);
	}

	@Override
	public int addSupplement(Integer id, String supplement, String nextPlan) {
		PublicRelease pr=new PublicRelease();
		pr.setId(id);
		pr.setSupplement(supplement);
		pr.setNextPlan(nextPlan);
		return publicReleaseMapper.updateByPrimaryKeySelective(pr);
	}




	@Override
	public boolean checkTime(InputPublicRelease in) {
		try {
			in.setReleaseStart(DateUtils.parseDate(in.getReleaseStarts(), AFTConstants.YYYYMMDDHHMMSS));
			in.setReleaseEnd(DateUtils.parseDate(in.getReleaseEnds(), AFTConstants.YYYYMMDDHHMMSS));
		} catch (ParseException e) {
			e.printStackTrace();
			throw new BusinessException("转换异常");
		}
		List<Integer> is=publicReleaseMapper.checkTime(TokenManager.getAdminId(),in.getReleaseStart(),in.getReleaseEnd());
		if (is.size()>1) {
			return true;
		}else  if(is.size()==1){
			//如果id为新增那么直接不允许时间重复
			if (in.getId()==null){
				return true;
			}else {
				//如果有id，与获取id一直，则为当前修改可以
				if (in.getId().equals(is.get(0))){
					return false;

				}else {
					return true;
				}
			}

		}
		return false;
	}


	@Override
	public List<Map<String, Object>> selectOrderByUid(String uid) {
		return tOrderNewMapper.selectOrderByuid(uid);
	}

	@Override
	public List<OutPublicRelease> publicByOrder(String orderNo) {
		return publicReleaseMapper.publicByOrder(orderNo);
	}

	@Override
	public Object getMyNewPublic() {
		List<OutPublicReleaseList> myPublic = getMyPublic(0,1);
		if (myPublic.isEmpty()){
			List<OutPublicReleaseList> myPublic2 = getMyPublic(0,0);
			if (!myPublic2.isEmpty()){
				return myPublic2.get(0);
			}
		}else {
			return myPublic.get(0);
		}
		return null;
	}




	/**
	 *
	 * @param type 查看类型 0我的公出 1公出审核 2管理员 3协单（技术财税总监看全部）
	 * @param dateType 是否含打卡时间  0否 1是
	 * @return
	 */
	public List<OutPublicReleaseList>getMyPublic(Integer type ,Integer dateType){
		Map<String, Object> map = new HashMap<>();
		if (type==null)type=0;
		map.put("type",type);
		//statusType=1情况下
		map.put("statusType",1);
		if (dateType==1){
			Date date = new Date();
			String clockTime=DateUtils.formatDate(date,AFTConstants.YYYYMMDDHHMMSS);
			map.put("clockTime",clockTime);
		}
		map.put("aid",TokenManager.getAdminId());
		List<OutPublicReleaseList> list = (List<OutPublicReleaseList>) findList("listPublicRelease",map,1,1);
		for (OutPublicReleaseList out : list) {
			out.setPrdList(publicReleaseDetailsMapper.selectByPCid(out.getId()));

		}
		return list;
	}

	@Override
	public int addAssistant(Integer id,String aid) {
		PublicRelease p = publicReleaseMapper.selectByPrimaryKey(id);
		List<String> list=new ArrayList<>();
		if (StringUtils.isNotEmpty(p.getAssistantAid())){
			list =new ArrayList<>(Arrays.asList(p.getAssistantAid().split(",")));
		}
		String sname = pushAssistant(aid, list,0);
		String said =String.join(",",list);
		p.setAssistantAid(said);
		p.setAssistantName(sname);
		addAssistantPublicRelease(p,aid);
		return updateAssistant(p, said, sname);
	}

	private void addAssistantPublicRelease(PublicRelease p, String aid) {
		List<PublicRelease> list = publicReleaseMapper.selectByMainId(p.getMainId(), 4, null);
		PublicRelease newP= new PublicRelease();
		if(list.isEmpty()){
			BeanUtils.copyProperties(p,newP);
			newP.setId(null);
			newP.setAid(aid);
			newP.setAssist(3);
			newP.setType(4);
			publicReleaseMapper.insertSelective(newP);
			addpublicReleaseDtails(p,newP.getId());
			StringBuffer str=new StringBuffer();
			str=str.append("公出").append("[").append(p.getUserNames()).append("]").append("邀请你协助!");
			addWeChatNotice( aid,1,str.toString(),newP.getId());
		}else {
			for (PublicRelease pr : list) {
					newP.setId(pr.getId());
					newP.setAssistantAid(p.getAssistantAid());
					newP.setAssistantName(p.getAssistantName());
					publicReleaseMapper.updateByPrimaryKeySelective(newP);
					updatePublicReleaseDtails(p,newP.getId());
			}
		}
	}

	/**
	 *	添加微信提示和站内消息
	 * @param aid 接受者
	 * @param type 状态 0驳回 1发起 2同意 3撤销
	 * @param str 备注
	 * @param prid 公出编号
	 */
	private void addWeChatNotice(String aid,Integer type,String str,Integer prid){
		Admin recipient = adminMapper.selectByPrimaryKey(aid);
		addWeChatNotice(  recipient, type, str, prid);
	}

	/**
	 *	添加微信提示和站内消息
	 * @param recipient 接受者
	 * @param type 状态 0驳回 1发起 2同意 3撤销
	 * @param str
	 */
	private Integer addWeChatNotice(Admin recipient,Integer type,String str,Integer prid){
			AdminListBo my = adminMapper.getDeptNameByAid(TokenManager.getAdminId());
			String openid=recipient.getOpenId();
			str=new StringBuffer("[").append(my.getName()).append("]").append(str).toString();
			if(type==3){
				addpublicLog(prid,4,str);
			}else {
				addpublicLog(prid,type,str);
			}
			sendNoticeAndSoucket(recipient.getId(),type,str);
			if (type==0||type==2){
				if (openid!=null) {
					Integer res= weChatUtils.addNotice(openid, type,prid,new Date(),my.getName(),str);
					return res;
				}else {
					sendEmail(my, recipient,type);
				}
			}

			return 0;
	}

	private int updateAssistant(PublicRelease p, String said, String sname) {
		PublicRelease newPr=new PublicRelease();
		newPr.setId(p.getId());
		newPr.setAssistantAid(said);
		newPr.setAssistantName(sname);
		if (p.getMainId()!=null){
			PublicRelease mianPr=new PublicRelease();
			mianPr.setId(p.getMainId());
			mianPr.setAssistantAid(said);
			mianPr.setAssistantName(sname);
			publicReleaseMapper.updateByPrimaryKeySelective(mianPr);
		}
		return publicReleaseMapper.updateByPrimaryKeySelective(newPr);
	}

	/**
	 *
	 * @param aid  元素
	 * @param list 集合
	 * @param type 0新增 1删除
	 * @return
	 */
	private String pushAssistant(String aid, List<String> list,Integer type) {
		StringBuffer sb=new StringBuffer();
		if(type==0){
			list.add(aid);
		}else if (type==1){
			Iterator<String > it =list.iterator();
			while (it.hasNext()){
				if (it.next().equals(aid))
					it.remove();
			}
		}
		for (String s : list) {
			sb.append(adminMapper.selectByPrimaryKey(s).getName()).append(",");
		}
		return sb.length()>0?sb.substring(0,sb.length()-1):sb.toString();
	}



	@Override
	public int deleteAssistant(Integer id, String aid) {
		PublicRelease p = publicReleaseMapper.selectByPrimaryKey(id);
		if (p.getAssistantAid()==null){
			throw new BusinessException("人员不存在");
		}
		List<String> list=new ArrayList<>(Arrays.asList(p.getAssistantAid().split(",")));
		if (!list.contains(aid)){
			throw new BusinessException("人员不存在");
		}
		String sname = pushAssistant(aid, list,1);
		String said =String.join(",",list);
		p.setAssistantAid(said);
		p.setAssistantName(sname);
		deleteAssistantPulicRelease(p,aid);
		return updateAssistant(p, said, sname);
	}



	private void deleteAssistantPulicRelease(PublicRelease p, String aid) {
		publicReleaseMapper.updateStatusByMainId(3,4,p.getMainId(),aid);
		List<PublicRelease> list = publicReleaseMapper.selectByMainId(p.getMainId(), 4, null);
		StringBuffer str=new StringBuffer();
		str=str.append("公出").append("[").append(p.getUserNames()).append("]").append("撤销了你的协助!");
		for (PublicRelease pr : list) {
			if (pr.getAid().equals(aid)){
				addWeChatNotice( pr.getAid(),3,str.toString(),pr.getId());
			}else {
				PublicRelease newPr=new PublicRelease();
				newPr.setId(pr.getId());
				newPr.setAssistantAid(p.getAssistantAid());
				newPr.setAssistantName(p.getAssistantName());
				publicReleaseMapper.updateByPrimaryKeySelective(newPr);
			}
		}
	}

	@Override
	public boolean checkdeleteAssistant(Integer id, String aid) {
		PublicRelease p = publicReleaseMapper.selectByPrimaryKey(id);
		List<PublicRelease> list = publicReleaseMapper.selectByMainId(p.getMainId(), 4, aid);
		for (PublicRelease use : list) {
//			if (use.getClockIn()==1){
//				return true;
//			}
		}
		return false;
	}

	@Override
	public boolean checkaddAssistant(Integer id, String aid) {
		PublicRelease p = publicReleaseMapper.selectByPrimaryKey(id);
		List<PublicRelease> list = publicReleaseMapper.selectByMainId(p.getMainId(), 4, aid);
		for (PublicRelease use : list) {
			if (use.getAid().equals(aid)&&use.getStatus()!=3){
				return true;
			}
		}
		return false;
	}

	@Override
	public int updateLocation(InputPublicRelease in) {
		PublicReleaseDetails prd=publicReleaseDetailsMapper.selectBypridAndUid(in);
		if (prd==null){
			throw  new BusinessException("公出企业不存在");
		}
		PublicReleaseDetails updateprd=new PublicReleaseDetails();
		updateprd.setId(prd.getId());
		updateprd.setLatitude(in.getLatitude());
		updateprd.setLongitude(in.getLongitude());
		updateprd.setDistrictName(in.getDistrictName());
		updateprd.setClockIn(0);
		addpublicLog(in.getId(),5,"发起公出地点修改");
		return publicReleaseDetailsMapper.updateByPrimaryKeySelective(updateprd);
	}


}
