/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2016.03.12
 * 描述               :                  公告信息
 * 注意事项      :                   无
 * 遗留BUG :                    无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/

package market.Slm.Notice.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.pb.PbMethod;
import market.Com.pb.SpeOptBaseService;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.CustomerInformation.vo.SlmCustomerPersonInfo;
import market.Slm.Notice.mapper.SlmNoticeAnnexMapper;
import market.Slm.Notice.mapper.SlmNoticeMapper;
import market.Slm.Notice.mapper.SlmNoticeReaderMapper;
import market.Slm.Notice.mapper.SlmNoticeScaleMapper;
import market.Slm.Notice.service.SlmNoticeService;
import market.Slm.Notice.vo.SlmNotice;
import market.Slm.Notice.vo.SlmNoticeAnnex;
import market.Slm.Notice.vo.SlmNoticeApp;
import market.Slm.Notice.vo.SlmNoticeReader;
import market.Slm.Notice.vo.SlmNoticeScale;

import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.service.impl.UserRoleServiceImpl;
import com.hnshituo.core.auth.service.impl.UserServiceImpl;
import com.hnshituo.core.auth.vo.User;
import com.hnshituo.core.auth.vo.UserRole;

@RemoteService(path = "SlmNoticeService")
public class SlmNoticeServiceImpl extends BaseServiceImpl<SlmNotice, Object> implements SlmNoticeService, Runnable {

	public ResultModel markAllRead(){
		ResultModel rm = new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		SlmNotice notice = new SlmNotice();
		notice.setValid_flag("0");
		try {
			List<SlmNotice> notices = doQueryApp(notice, null, null, 0, 2147483647);
			if(notices != null) {
				for (int i = 0; i < notices.size(); i++) {
					// 修改登录人的阅读状态
					SlmNotice oaNotice = notices.get(i);
					SlmNoticeReader read = new SlmNoticeReader();
					read.setNotice_no(oaNotice.getNotice_no());
					read.setPerson_no(userId);
					// read.setValid_flag("0");
					List<SlmNoticeReader> readList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(read);
					if (readList.size() > 0) {
						if ("0".equals(readList.get(0).getValid_flag().trim())) {
							read.setValid_flag("1"); // 已读
							this.getMapper(SlmNoticeReaderMapper.class).doUpdate(read);
						}
					}else {
						// 新增一条数据
						SlmNoticeReader reader = new SlmNoticeReader();
						reader.setNotice_no(oaNotice.getNotice_no());
						reader.setValid_flag("1");
						reader.setPerson_no(userId);
						reader.setPerson_name((String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
						reader.setRead_time(new Date());
						this.getMapper(SlmNoticeReaderMapper.class).doAddReaded(reader);
					}
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("数据异常"+e.getMessage());
			return rm;
		}
		rm.setState("200");
		return rm;
	}


	/***************************************** APP **********************************************/
	/**
	 * 数据查询
	 * 
	 * @throws ParseException
	 */
	public List<SlmNotice> doQueryApp(SlmNotice wn, Date startTime, Date endTime,	int PageIndex, int PageSize) throws ParseException {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		List<SlmNotice> lwn = new ArrayList<SlmNotice>();

		if (startTime != null && endTime != null) {
			String s_time = new SimpleDateFormat("yyyy-MM-dd").format(startTime);
			String e_time = new SimpleDateFormat("yyyy-MM-dd").format(endTime);
			s_time += " 00:00:00";
			e_time += " 23:59:59";
			startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s_time);
			endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(e_time);
		}
		// 得到公告信息
		lwn = this.getMapper(SlmNoticeMapper.class).doQueryApp(wn, userId,startTime, endTime, PageIndex, PageSize);

		// 赋予附件标识
		
		String notice_no="";
		for (SlmNotice notice : lwn) {
			notice.setHave_annex("0");
			SlmNoticeAnnex annex = new SlmNoticeAnnex();
			annex.setNotice_no(notice.getNotice_no());
			int count = this.getMapper(SlmNoticeAnnexMapper.class).count(annex);
			if (count> 0) {
				notice.setHave_annex("1");
			}
			notice_no+=notice.getNotice_no()+",";
		}
		if(lwn.size()>0){
			lwn.get(0).setNotice_no_list(notice_no);
		}
		return lwn;
	}

	public List<Integer> showReaderCount(String  notice_list){
		List<Integer> int_list=new ArrayList<Integer>();
		try{
			if(notice_list!=null){
				String[] notice_no_list=notice_list.split(",");
				SlmNoticeReader reader = new SlmNoticeReader();
				reader.setValid_flag("1");
				for(String notice_no:notice_no_list){
					int count=0;
					reader.setNotice_no(notice_no);
					count = this.getMapper(SlmNoticeReaderMapper.class).countWithCondition(reader," person_no!='admin'" );
					int_list.add(count);
				}
			}
		}catch(Exception e){
		}
		return int_list;
	}

	
	/**
	 * 新增公告&收文、发文进行发布（type_no）
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doInsertApp(SlmNoticeApp wna) throws Exception {
		ResultModel rm = new ResultModel();
		try {
			String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			String deptId = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
			String deptName = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
			
			String notice_no = wna.getList().getNotice_no();
			String NoticeNo = "";
			wna.getList().setRelease_person_no(userId);
			wna.getList().setRelease_person_name(userName);
			wna.getList().setDepartment_no(deptId);
			wna.getList().setDepartment_name(deptName);
			wna.getList().setRelease_time(new Date());
			wna.getList().setIs_del("1");
			NoticeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS")
			.format(new Date());
			NoticeNo += PbMethod.RandomCreate(3);
			wna.getList().setNotice_no(NoticeNo);

			// 公告表新增
			this.getMapper(SlmNoticeMapper.class).insert(wna.getList());

			List<SlmNoticeScale> lons = new ArrayList<SlmNoticeScale>();
			if (wna.getScaledpt() != null && wna.getScaledpt().size() > 0) {
				for (SlmNoticeScale ons : wna.getScaledpt()) {
					ons.setNotice_no(NoticeNo);
					ons.setDb_type("1");
					lons.add(ons);
				}
			}
			if (wna.getScalerole() != null && wna.getScalerole().size() > 0) {
				for (SlmNoticeScale ons : wna.getScalerole()) {
					ons.setNotice_no(NoticeNo);
					ons.setDb_type("2");
					lons.add(ons);
				}
			}
			// ----------------------------------------------------------------------------
			
			if (lons.size() > 0) {
				List<SlmCustomerPersonInfo> toMan = this.getBean(SlmNoticeScaleServiceImpl.class).doAdd(lons);
			}
			
			// 附件表新增
			int i = 0;
			if (wna.getAnnex() != null) {
				for (SlmNoticeAnnex wnac : wna.getAnnex()) {
					wnac.setNotice_no(wna.getList().getNotice_no());
					wnac.setAnnex_no(wna.getList().getNotice_no().substring(0, 17)+ String.format("%03d", i));
					if (wnac.getAnnex_path()!=null&&!"".equals(wnac.getAnnex_path())){
						String path = wnac.getAnnex_path();
						if (path.contains("group1/M00")) {
							wnac.setAnnex_path(path);
						} else {
							wnac.setAnnex_path(this.getBean(SpeOptBaseService.class).doAdd(path));
						}
					}
					
					//-------若无附件type----2018.06.12-------
					if(wnac.getAnnex_type()==null||"".equals(wnac.getAnnex_type())){
						if(wnac.getAnnex_name()!=null){
							int point=wnac.getAnnex_name().lastIndexOf('.');
							String type=wnac.getAnnex_name().substring(point);
							wnac.setAnnex_type(type);
						}
					}
					
					this.getMapper(SlmNoticeAnnexMapper.class).insert(wnac);
					i++;
				}
			}
			// ----------------根据范围得到范围下所有人员信息，插入到SlmNoticeReader中------------------//
			if (wna.getNoticeReader() != null) {
				for (SlmNoticeReader noticeReader : wna.getNoticeReader()) {
					if (!noticeReader.getPerson_no().equals(userId)) {
						SlmNoticeReader wnr = new SlmNoticeReader();
						wnr.setNotice_no(wna.getList().getNotice_no());
						wnr.setPerson_no(noticeReader.getPerson_no());
						wnr.setPerson_name(noticeReader.getPerson_name());
						wnr.setValid_flag("0");
						wnr.setIs_notify("1");
						this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);
					}
				}
			}
			//新建admin查看权限
			SlmNoticeReader admin = new SlmNoticeReader();
			admin.setNotice_no(wna.getList().getNotice_no());
			admin.setPerson_no("admin");
			admin.setPerson_name("admin");
			admin.setValid_flag("0");
			admin.setIs_notify("1");
			this.getMapper(SlmNoticeReaderMapper.class).doAdd(admin);
			// 新增创建人信息
			SlmNoticeReader wnr = new SlmNoticeReader();
			wnr.setNotice_no(wna.getList().getNotice_no());
			wnr.setPerson_no(userId);
			wnr.setPerson_name(userName);
			wnr.setValid_flag("0");
			this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);

			/*dept_name=wna.getList().getDepartment_name();
			title=wna.getList().getNotice_title();
			no=wna.getList().getNotice_no();
			for(String man:toMan){
				User user=this.getMapper(UserMapper.class).findById(man);
				if(user!=null)
					user_list.add(user);
			}*/
			//Thread thread = new Thread(this);  
			//thread.start();


			//			// 给用户发一条文本消息
			//			PbMethod.SendMsg("公告通知", toMan, "{\"name\":\""
			//					+ wna.getList().getDepartment_name() + "\",\"content\":\""
			//					+ wna.getList().getNotice_title() + "\",\"no\":\""
			//					+ wna.getList().getNotice_no() + "\"}", "txt", "users",
			//					"发送公告推送信息失败：时间:" + (new Date()) + ",notice_no:" + NoticeNo);
			//			this.getBean(HomeServiceImpl.class).sendMsg(toMan, "");
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			throw new Exception(e.getMessage());
		}
		return rm;
	}

	@Override
	public void run() {
		// 给用户发一条文本消息
		/*
		PbMethod.SendMsg("公告通知", toMan, "{\"name\":\""
				+ dept_name + "\",\"content\":\""
				+ title + "\",\"no\":\""
				+ no+ "\"}", "txt", "users",
				"发送公告推送信息失败：时间:" + (new Date()) + ",notice_no:" + no);
		try {
			this.getBean(HomeServiceImpl.class).sendMsg(user_list,"");
		} catch (Exception e) {
		}
		//*/
	}
	
	/**
	 * 修改通知公共
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateApp(SlmNoticeApp wna) throws Exception {
		ResultModel rm = new ResultModel();

		String NoticeNo = wna.getList().getNotice_no();
		this.getMapper(SlmNoticeMapper.class).update(wna.getList());

		SlmNoticeScale onc = new SlmNoticeScale();
		onc.setNotice_no(NoticeNo);
		this.getMapper(SlmNoticeScaleMapper.class).doDelete(onc);

		if (wna.getScaledpt() != null && wna.getScaledpt().size() > 0) {
			for (SlmNoticeScale ons : wna.getScaledpt()) {
				ons.setNotice_no(NoticeNo);
				ons.setDb_type("1");
				this.getMapper(SlmNoticeScaleMapper.class).doAdd(ons);
			}
		}
		if (wna.getScalerole() != null && wna.getScalerole().size() > 0) {
			for (SlmNoticeScale ons : wna.getScalerole()) {
				ons.setNotice_no(NoticeNo);
				ons.setDb_type("2");
				this.getMapper(SlmNoticeScaleMapper.class).doAdd(ons);
			}
		}

		// ----------------根据范围得到范围下所有人员信息，与已有信息进行匹配，若无则入到SlmNoticeReader中------------------//
		if (wna.getNoticeReader() != null) {
			SlmNoticeReader onr = new SlmNoticeReader();
			onr.setNotice_no(NoticeNo);
			List<SlmNoticeReader> lonr = this.getMapper(SlmNoticeReaderMapper.class).find(onr, 0, 0);

			for (SlmNoticeReader noticeReader : wna.getNoticeReader()) {
				boolean flag = true;// 是否通知表中无该通知人
				if (lonr != null && lonr.size() > 0) {
					for (SlmNoticeReader o : lonr) {
						if (noticeReader.getPerson_no().equals(o.getPerson_no())) {
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					SlmNoticeReader wnr = new SlmNoticeReader();
					wnr.setNotice_no(wna.getList().getNotice_no());
					wnr.setPerson_no(noticeReader.getPerson_no());
					wnr.setPerson_name(noticeReader.getPerson_name());
					wnr.setValid_flag("0");
					wnr.setIs_notify("1");
					this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);
				}
			}
		}

		rm.setState("200");

		return rm;
	}

	/**
	 * 详情
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public SlmNoticeApp doQueryOne(SlmNotice notice) {
		SlmNoticeApp sum = new SlmNoticeApp();
		Boolean isAdmin = (Boolean) this.getSession().getAttribute(HomeService.SESSION_ISADMIN);
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);

		List<SlmNoticeScale> deptList =new ArrayList<SlmNoticeScale>();
		List<SlmNoticeScale> roleList =new ArrayList<SlmNoticeScale>();
		List<SlmNoticeReader> noticeReaderList=new ArrayList<SlmNoticeReader>();
		// 公告信息
		String noticeNo = notice.getNotice_no();
		SlmNotice notices = this.getMapper(SlmNoticeMapper.class).findById(noticeNo);
		if (notices==null||"2".equals(notices.getIs_del())) // 已删除
			return new SlmNoticeApp();

		notices.setIs_show_person("0");
		notices.setIs_show_scale("0");
		if(isAdmin||userId.equals(notices.getRelease_person_no())){
			notices.setIs_show_person("1");
			notices.setIs_show_scale("1");
		}else{
			UserRole userRole=new UserRole();
			userRole.setUserId(userId);
			List<UserRole> urList=this.getBean(UserRoleServiceImpl.class).doQuery(userRole);
			for(UserRole ur:urList){
				if(ur.getRoleId()==1){
					notices.setIs_show_person("1");
					break;
				}
			}
		}

		// 部门范围
		SlmNoticeScale scale = new SlmNoticeScale();
		scale.setNotice_no(noticeNo);
		scale.setDb_type("1");
		deptList = this.getBean(	SlmNoticeScaleServiceImpl.class).doQuery(scale);

		// 角色范围
		scale.setDb_type("2");
		roleList = this.getBean(SlmNoticeScaleServiceImpl.class).doQuery(scale);

		// 得到该公告的阅读人范围信息
		SlmNoticeReader noticeReader = new SlmNoticeReader();
		noticeReader.setNotice_no(noticeNo);
		noticeReader.setIs_notify("1");
		noticeReaderList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(noticeReader);
		// 得到该公告的附件信息
		SlmNoticeAnnex annex = new SlmNoticeAnnex();
		annex.setNotice_no(noticeNo);
		List<SlmNoticeAnnex> annexList = this.getMapper(SlmNoticeAnnexMapper.class).doQuery(annex);

		// 修改登录人的阅读状态
		SlmNoticeReader read = new SlmNoticeReader();
		read.setNotice_no(noticeNo);
		read.setPerson_no(userId);
		// read.setValid_flag("0");
		List<SlmNoticeReader> readList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(read);
		if (readList.size() > 0) {
			if ("0".equals(readList.get(0).getValid_flag().trim())) {
				read.setValid_flag("1"); // 已读
				this.getMapper(SlmNoticeReaderMapper.class).doUpdate(read);
			}
		}
		// ---------------------eason 2017-09-21 add--------------------------
		else {
			// 新增一条数据
			SlmNoticeReader reader = new SlmNoticeReader();
			reader.setNotice_no(notice.getNotice_no());
			reader.setValid_flag("1");
			reader.setPerson_no(userId);
			reader.setPerson_name((String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
			reader.setRead_time(new Date());
			this.getMapper(SlmNoticeReaderMapper.class).doAddReaded(reader);
		}

		// 获得已阅读的人的集合
		SlmNoticeReader reader = new SlmNoticeReader();
		reader.setNotice_no(notice.getNotice_no());
		reader.setValid_flag("1");
//		List<SlmNoticeReader> readerList = this.getMapper(SlmNoticeReaderMapper.class).findWithCondition(reader," person_no!='admin'"," read_time desc ",0,0);
		long reader_count= this.getMapper(SlmNoticeReaderMapper.class).countWithCondition(reader," person_no!='admin'" );
		notices.setReader_number(reader_count);

		//去除admin
		if(noticeReaderList!=null){
			List<SlmNoticeReader> newReaderList=new ArrayList<SlmNoticeReader>();
			for( SlmNoticeReader readers:noticeReaderList){
				if(!"admin".equals(readers.getPerson_no())){
					newReaderList.add(readers);
				}
			}
			noticeReaderList=newReaderList;
		}

		sum.setList(notices);
		sum.setNoticeReader(noticeReaderList);
		sum.setAnnex(annexList);
//		sum.setUserList(readerList);
		sum.setScaledpt(deptList);
		sum.setScalerole(roleList);
		return sum;
	}
	
	public List<SlmNoticeReader> findReader(String notice_no){
		// 获得已阅读的人的集合
		SlmNoticeReader reader = new SlmNoticeReader();
		reader.setNotice_no(notice_no);
		reader.setValid_flag("1");
		List<SlmNoticeReader> readerList = this.getMapper(SlmNoticeReaderMapper.class).findWithCondition(reader," person_no!='admin'"," read_time desc ",0,0);
		return readerList;
	}

	/**
	 * 删除公告APP
	 * */
	public ResultModel doDeleteApp(SlmNotice notice) {
		ResultModel rm = new ResultModel();
		try {
			notice.setIs_del("2");
			this.getMapper(SlmNoticeMapper.class).update(notice);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("删除失败");
		}
		return rm;
	}

	/***************************************** APP **********************************************/

	/***************************************** WEB **********************************************/
	/**
	 * Web端通知公告数据查询
	 * 
	 * @throws ParseException
	 */
	public ResultModel doQueryWeb(CommonPage<SlmNotice> sum)	throws ParseException {
		ResultModel rm = new ResultModel();
		SlmNotice wn = sum.getObject();
		String startTime = sum.getStartTime();
		String endTime = sum.getEndTime();
		int PageIndex = sum.getPageIndex();
		int PageSize = sum.getPageSize();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		PageModel<SlmNoticeApp> pm = new PageModel<SlmNoticeApp>(PageIndex,PageSize);
		List<SlmNotice> lwn = new ArrayList<SlmNotice>();
		List<SlmNoticeApp> list = new ArrayList<SlmNoticeApp>();
		Date s_time = null;
		Date e_time = null;
		if (startTime != null && endTime != null) {
			startTime += " 00:00:00";
			endTime += " 23:59:59";
			s_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
			e_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
		}

		// 得到公告信息
		lwn = this.getMapper(SlmNoticeMapper.class).doQueryWeb(wn, userId,s_time, e_time, (PageIndex - 1) * PageSize, PageSize);
		int count = this.getMapper(SlmNoticeMapper.class).doQueryWebCount(wn,userId, s_time, e_time);
		// 赋予附件标识

		for (SlmNotice notice : lwn) {
			SlmNoticeApp noticeApp = new SlmNoticeApp();
			noticeApp.setList(notice);
			notice.setHave_annex("0");
			SlmNoticeAnnex annex = new SlmNoticeAnnex();
			annex.setNotice_no(notice.getNotice_no());
			List<SlmNoticeAnnex> annexlist = this.getBean(SlmNoticeAnnexServiceImpl.class).doQuery(annex);
			if (annexlist.size() > 0) {
				notice.setHave_annex("1");
				noticeApp.setAnnex(annexlist);
			}
			//			SlmNoticeReader reader = new SlmNoticeReader();
			//			reader.setNotice_no(notice.getNotice_no());
			//			reader.setValid_flag("1");
			//			List<SlmNoticeReader> readerList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(reader);
			//			notice.setReader_number((long) readerList.size());
			list.add(noticeApp);
		}
		pm.setRows(list);
		pm.setTotal(count);
		rm.setState("200");
		rm.setData(pm);
		return rm;
	}

	/**
	 * Web端新增公告&收文、发文进行发布（type_no）
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doInsertWeb(SlmNoticeApp wna) throws Exception {
		ResultModel rm = new ResultModel();
		try {
			String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			String deptId = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
			String deptName = (String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
			
			User users = this.getMapper(UserMapper.class).findById(userId);
			String notice_no = wna.getList().getNotice_no();
			String NoticeNo = "";
			wna.getList().setRelease_person_no(userId);
			wna.getList().setRelease_person_name(userName);
			wna.getList().setDepartment_no(deptId);
			wna.getList().setDepartment_name(deptName);
			wna.getList().setRelease_time(new Date());
			NoticeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS")
			.format(new Date());
			NoticeNo += PbMethod.RandomCreate(3);
			wna.getList().setNotice_no(NoticeNo);
			wna.getList().setIs_del("1"); // 未删除

			// 公告表新增
			this.getMapper(SlmNoticeMapper.class).insert(wna.getList());
			
			List<SlmNoticeScale> lons = new ArrayList<SlmNoticeScale>();
			if (wna.getScaledpt() != null && wna.getScaledpt().size() > 0) {
				for (SlmNoticeScale ons : wna.getScaledpt()) {
					ons.setNotice_no(NoticeNo);
					ons.setDb_type("1");
					lons.add(ons);
				}
			}
			if (wna.getScalerole() != null && wna.getScalerole().size() > 0) {
				for (SlmNoticeScale ons : wna.getScalerole()) {
					ons.setNotice_no(NoticeNo);
					ons.setDb_type("2");
					lons.add(ons);
				}
			}
			List<SlmCustomerPersonInfo> toMan=new ArrayList<SlmCustomerPersonInfo>();
			if (lons.size() > 0) {
				toMan = this.getBean(SlmNoticeScaleServiceImpl.class).doAdd(lons);
			}
			// ----------------------------------------------------------------------------

			
			// 附件表新增
			int i = 0;
			if (wna.getAnnex() != null) {
				for (SlmNoticeAnnex wnac : wna.getAnnex()) {
					wnac.setNotice_no(wna.getList().getNotice_no());
					wnac.setAnnex_no(wna.getList().getNotice_no().substring(0, 17)+ String.format("%03d", i));
					if (wnac.getAnnex_path()!=null&&!"".equals(wnac.getAnnex_path())){
						String path = wnac.getAnnex_path();
						if (path.contains("group1/M00")) {
							wnac.setAnnex_path(path);
						} else {
							wnac.setAnnex_path(this.getBean(SpeOptBaseService.class).doAdd(path));
						}
					}
					
					//-------若无附件type----2018.06.12-------
					if(wnac.getAnnex_type()==null||"".equals(wnac.getAnnex_type())){
						if(wnac.getAnnex_name()!=null){
							int point=wnac.getAnnex_name().lastIndexOf('.');
							String type=wnac.getAnnex_name().substring(point);
							wnac.setAnnex_type(type);
						}
					}
					
					this.getMapper(SlmNoticeAnnexMapper.class).insert(wnac);
					i++;
				}
			}
			// ----------------根据范围得到范围下所有人员信息，插入到SlmNoticeReader中------------------//
			if (wna.getNoticeReader() != null) {
				for (SlmNoticeReader noticeReader : wna.getNoticeReader()) {
					if (!noticeReader.getPerson_no().equals(userId)) {
						SlmNoticeReader wnr = new SlmNoticeReader();
						wnr.setNotice_no(wna.getList().getNotice_no());
						wnr.setPerson_no(noticeReader.getPerson_no());
						wnr.setPerson_name(noticeReader.getPerson_name());
						wnr.setValid_flag("0");
						wnr.setIs_notify("1");
						this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);
					}
				}
			}
			
			//新建admin查看权限
			SlmNoticeReader admin = new SlmNoticeReader();
			admin.setNotice_no(wna.getList().getNotice_no());
			admin.setPerson_no("admin");
			admin.setPerson_name("admin");
			admin.setValid_flag("0");
			admin.setIs_notify("1");
			this.getMapper(SlmNoticeReaderMapper.class).doAdd(admin);
			// 新增创建人信息
			SlmNoticeReader wnr = new SlmNoticeReader();
			wnr.setNotice_no(wna.getList().getNotice_no());
			wnr.setPerson_no(userId);
			wnr.setPerson_name(userName);
			wnr.setValid_flag("0");
			this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);
			
			// 给用户发一条文本消息
			/*dept_name=wna.getList().getDepartment_name();
			title=wna.getList().getNotice_title();
			no=wna.getList().getNotice_no();
			for(String man:toMan){
				User user=this.getMapper(UserMapper.class).findById(man);
				if(user!=null)
					user_list.add(user);
			}*/
			
			//Thread thread = new Thread(this);  
			//thread.start();

			//			PbMethod.SendMsg("公告通知", toMan, "{\"name\":\""
			//					+ wna.getList().getDepartment_name() + "\",\"content\":\""
			//					+ wna.getList().getNotice_title() + "\",\"no\":\""
			//					+ wna.getList().getNotice_no() + "\"}", "txt", "users",
			//					"发送公告推送信息失败：时间:" + (new Date()) + ",notice_no:" + NoticeNo);
			//			this.getBean(HomeServiceImpl.class).sendMsg(toMan, "");
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			throw new Exception(e.getMessage());
		}
		return rm;
	}

	/**
	 * 修改通知公共
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateWeb(SlmNoticeApp wna) throws Exception {
		ResultModel rm = new ResultModel();

		String NoticeNo = wna.getList().getNotice_no();
		this.getMapper(SlmNoticeMapper.class).update(wna.getList());

		SlmNoticeScale onc = new SlmNoticeScale();
		onc.setNotice_no(NoticeNo);
		this.getMapper(SlmNoticeScaleMapper.class).doDelete(onc);

		if (wna.getScaledpt() != null && wna.getScaledpt().size() > 0) {
			for (SlmNoticeScale ons : wna.getScaledpt()) {
				ons.setNotice_no(NoticeNo);
				ons.setDb_type("1");
				this.getMapper(SlmNoticeScaleMapper.class).doAdd(ons);
			}
		}
		if (wna.getScalerole() != null && wna.getScalerole().size() > 0) {
			for (SlmNoticeScale ons : wna.getScalerole()) {
				ons.setNotice_no(NoticeNo);
				ons.setDb_type("2");
				this.getMapper(SlmNoticeScaleMapper.class).doAdd(ons);
			}
		}

		// -------------------------------------------------------
		// 附件表删除
		SlmNoticeAnnex ona = new SlmNoticeAnnex();
		ona.setNotice_no(wna.getList().getNotice_no());
		List<SlmNoticeAnnex> lona = this.getMapper(SlmNoticeAnnexMapper.class).find(ona, 0, 0);
		if (lona != null && lona.size() > 0) {
			for (SlmNoticeAnnex o : lona) {
				this.getMapper(SlmNoticeAnnexMapper.class).delete(o.getAnnex_no());
				//								this.getBean(SpeOptBaseService.class).doDelete(o.getAnnex_path());
			}
		}
		
		
		// 附件表新增
		int i = 0;
		for (SlmNoticeAnnex wnac : wna.getAnnex()) {
			wnac.setNotice_no(wna.getList().getNotice_no());
			wnac.setAnnex_no(wna.getList().getNotice_no().substring(0, 17)+ String.format("%03d", i));
			String path = wnac.getAnnex_path();
			if (path.contains("group1/M00")) { // 若为文件流转过来的附件
				wnac.setAnnex_path(path);
			} else {
				wnac.setAnnex_path(this.getBean(SpeOptBaseService.class).doAdd(path));
			}
			//-------若无附件type----2018.06.12-------
			if(wnac.getAnnex_type()==null||"".equals(wnac.getAnnex_type())){
				if(wnac.getAnnex_name()!=null){
					int point=wnac.getAnnex_name().lastIndexOf('.');
					String type=wnac.getAnnex_name().substring(point);
					wnac.setAnnex_type(type);
				}
			}
			//-------若无附件type----2018.06.12-------
			this.getMapper(SlmNoticeAnnexMapper.class).insert(wnac);
			i++;
		}

		// ----------------根据范围得到范围下所有人员信息，与已有信息进行匹配，若无则入到SlmNoticeReader中------------------//
		if (wna.getNoticeReader() != null) {
			SlmNoticeReader onr = new SlmNoticeReader();
			onr.setNotice_no(NoticeNo);
			List<SlmNoticeReader> lonr = this.getMapper(SlmNoticeReaderMapper.class).find(onr, 0, 0);

			for (SlmNoticeReader noticeReader : wna.getNoticeReader()) {
				boolean flag = true;// 是否通知表中无该通知人
				if (lonr != null && lonr.size() > 0) {
					for (SlmNoticeReader o : lonr) {
						if (noticeReader.getPerson_no().equals(o.getPerson_no())) {
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					SlmNoticeReader wnr = new SlmNoticeReader();
					wnr.setNotice_no(wna.getList().getNotice_no());
					wnr.setPerson_no(noticeReader.getPerson_no());
					wnr.setPerson_name(noticeReader.getPerson_name());
					wnr.setValid_flag("0");
					wnr.setIs_notify("1");
					this.getMapper(SlmNoticeReaderMapper.class).doAdd(wnr);
				}
			}
		}

		// ----------附件修改-----------
		SlmNoticeAnnex annex = new SlmNoticeAnnex();
		annex.setNotice_no(NoticeNo);
		List<SlmNoticeAnnex> annexList = this.getBean(SlmNoticeAnnexServiceImpl.class).doQuery(annex);
		for (SlmNoticeAnnex annexes : annexList) {
			this.getBean(SlmNoticeAnnexServiceImpl.class).delete(annexes.getAnnex_no()); // 删除原有
			//			this.getBean(SpeOptBaseService.class).doDelete(annexes.getAnnex_path());
		}
		for (SlmNoticeAnnex annexes : wna.getAnnex()) { // 新增
			annexes.setNotice_no(NoticeNo);
			this.getBean(SlmNoticeAnnexServiceImpl.class).doAdd(annexes);
		}
		rm.setState("200");

		return rm;
	}

	/**
	 * Web端公告详情
	 * */
	//	private static Logger log = Logger.getLogger(SlmNoticeServiceImpl.class);
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doQueryOneWeb(SlmNotice notice) {
		ResultModel rm = new ResultModel();
		SlmNoticeApp sum = new SlmNoticeApp();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		Boolean isAdmin = (Boolean) this.getSession().getAttribute(HomeService.SESSION_ISADMIN);
		// 公告信息
		String noticeNo = notice.getNotice_no();
		SlmNotice notices = this.getMapper(SlmNoticeMapper.class).findById(noticeNo);
		if ("2".equals(notices.getIs_del())) { // 已删除
			rm.setState("200");
			rm.setData(new SlmNoticeApp());
			return rm;
		}
		notices.setIs_show_scale("0");
		if(isAdmin||userId.equals(notices.getRelease_person_no())){
			notices.setIs_show_scale("1");
		}

		// 得到该公告的阅读人范围信息
		SlmNoticeReader noticeReader = new SlmNoticeReader();
		noticeReader.setNotice_no(noticeNo);
		noticeReader.setIs_notify("1");
		List<SlmNoticeReader> noticeReaderList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(noticeReader);

		// 得到该公告的附件信息
		SlmNoticeAnnex annex = new SlmNoticeAnnex();
		annex.setNotice_no(noticeNo);
		List<SlmNoticeAnnex> annexList = this.getMapper(SlmNoticeAnnexMapper.class).doQuery(annex);

		// 修改登录人的阅读状态
		SlmNoticeReader read = new SlmNoticeReader();
		read.setNotice_no(noticeNo);
		read.setPerson_no(userId);
		// read.setValid_flag("0");
		List<SlmNoticeReader> readList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(read);
		if (readList.size() > 0) {
			if ("0".equals(readList.get(0).getValid_flag().trim())) {
				read.setValid_flag("1"); // 已读
				this.getMapper(SlmNoticeReaderMapper.class).doUpdate(read);
			}
		}
		// ---------------------eason 2017-09-21 add--------------------------
		else {
			// 新增一条数据
			SlmNoticeReader reader = new SlmNoticeReader();
			reader.setNotice_no(notice.getNotice_no());
			reader.setValid_flag("1");
			reader.setPerson_no(userId);
			reader.setPerson_name((String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
			reader.setRead_time(new Date());
			this.getMapper(SlmNoticeReaderMapper.class).doAddReaded(reader);
		}
		SlmNoticeScale ons = new SlmNoticeScale();
		ons.setDb_type("1");
		ons.setNotice_no(noticeNo);
		sum.setScaledpt(this.getMapper(SlmNoticeScaleMapper.class).find(ons, 0,0));
		ons.setDb_type("2");
		sum.setScalerole(this.getMapper(SlmNoticeScaleMapper.class).find(ons, 0,	0));

		//去除admin
		if(noticeReaderList!=null){
			List<SlmNoticeReader> newReaderList=new ArrayList<SlmNoticeReader>();
			for( SlmNoticeReader readers:noticeReaderList){
				if(!"admin".equals(readers.getPerson_no())){
					newReaderList.add(readers);
				}
			}
			noticeReaderList=newReaderList;
		}
		sum.setList(notices);
		sum.setNoticeReader(noticeReaderList);
		sum.setAnnex(annexList);
		rm.setState("200");
		rm.setData(sum);

		return rm;
	}

	public ResultModel showReader(SlmNotice notice){
		ResultModel rm=new ResultModel();
		Boolean isAdmin = (Boolean) this.getSession().getAttribute(HomeService.SESSION_ISADMIN);
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		try{
			List<SlmNoticeReader> readerList=new ArrayList<SlmNoticeReader>();
			// 获得已阅读的人的集合
			if(userId.equals(notice.getRelease_person_no()) || isAdmin){
				SlmNoticeReader reader = new SlmNoticeReader();
				reader.setNotice_no(notice.getNotice_no());
				reader.setValid_flag("1");
				readerList = this.getMapper(SlmNoticeReaderMapper.class).findWithCondition(reader," person_no!='admin'"," read_time desc ",0,0);
				notice.setReader_number((long) readerList.size());
				//2018.4.12人员列表需要单独请求
				// 就web端（给您赋头像）
				for (SlmNoticeReader readers : readerList) {
					User user = this.getBean(UserServiceImpl.class).findUserById(	readers.getPerson_no());
					if (user != null)
						readers.setLogo(user.getLogo());
				}
			}
			rm.setState("200");
			rm.setData(readerList);
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}



	/**
	 * 删除公告WEB
	 * */
	public ResultModel doDeleteWeb(SlmNotice notice) {
		ResultModel rm = new ResultModel();
		try {
			notice.setIs_del("2");
			this.getMapper(SlmNoticeMapper.class).update(notice);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("删除失败");
		}
		return rm;
	}

	/**
	 * 公告设置为已读
	 */
	public ResultModel doNoticeRead(String notice_no) {
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		ResultModel rm = new ResultModel();
		// 修改登录人的阅读状态
		try {
			SlmNoticeReader read = new SlmNoticeReader();
			read.setNotice_no(notice_no);
			read.setPerson_no(userId);
			// read.setValid_flag("0");
			List<SlmNoticeReader> readList = this.getBean(SlmNoticeReaderServiceImpl.class).doQuery(read);
			if (readList.size() > 0) {
				if ("0".equals(readList.get(0).getValid_flag().trim())) {
					read.setValid_flag("1"); // 已读
					read.setRead_time(new Date());
					this.getMapper(SlmNoticeReaderMapper.class).doUpdate(read);
				}
			} else {
				// 新增一条数据
				SlmNoticeReader reader = new SlmNoticeReader();
				reader.setNotice_no(notice_no);
				reader.setValid_flag("1");
				reader.setPerson_no(userId);
				reader.setPerson_name((String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
				reader.setRead_time(new Date());
				this.getMapper(SlmNoticeReaderMapper.class).doAddReaded(reader);
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("删除失败");
		}
		return rm;
	}

	/***************************************** WEB **********************************************/

}
