package com.lerx.handlers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.lerx.annotation.Token;
import com.lerx.aop.args.CutTags;
import com.lerx.dao.iface.IArticleAttaDao;
import com.lerx.dao.iface.IArticleDao;
import com.lerx.dao.iface.ICommentBridgeDao;
import com.lerx.dao.iface.IGroupDao;
import com.lerx.dao.iface.IHtmlFileStaticDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IRoleDao;
import com.lerx.dao.iface.IUploadedFileDao;
import com.lerx.dao.iface.IUserArtsCountDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Article;
import com.lerx.entities.ArticleGroup;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.HtmlFileStatic;
import com.lerx.entities.Poll;
import com.lerx.entities.Portal;
import com.lerx.entities.Role;
import com.lerx.entities.SearchTotalModel;
import com.lerx.entities.UploadedFile;
import com.lerx.entities.User;
import com.lerx.entities.VisitorsBook;
import com.lerx.hql.entities.Rs;
import com.lerx.hql.util.RsUtil;
import com.lerx.login.util.LoginUtil;
import com.lerx.portal.obj.ArticleGroupMapCreateArgs;
import com.lerx.portal.obj.FileEl;
import com.lerx.portal.obj.ReciveUserModular;
import com.lerx.portal.obj.SimpleArticle;
import com.lerx.portal.obj.SimpleReciveArticle;
import com.lerx.portal.obj.SimpleReciveArticleGroup;
import com.lerx.portal.obj.SimpleReciveUser;
import com.lerx.portal.obj.UploadArgs;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.MavUtil;
import com.lerx.sys.util.ObjUtil;
import com.lerx.sys.util.SecurityUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.sys.util.TimeUtil;
import com.lerx.v6.util.ArtAttaUtil;
import com.lerx.v6.util.ArticleUtil;
import com.lerx.v6.util.GroupUtil;
import com.lerx.v6.util.ReciveUtil;
import com.lerx.v6.util.UploadUtil;
import com.lerx.v6.util.UserUtil;

@RequestMapping("/action_article")
@Controller
public class ArticleHandler {
	
	/*private static final String SUCCESS = "jsp/result/success";
	private static final String FAILED = "jsp/result/failed";*/
	
	private static final String ARTICLELIST = "jsp/article/list";
	private static final String ARTICLEEDIT = "jsp/article/add";
	private static final String LOGINPAGE = "jsp/user/login";
	private static final String FORBIDU = "jsp/result/forbidu";
	private static final String ADMINFAILRETURN = "_admin.login.redirect_";
	private static final String FAILED = "jsp/result/failed";
	
	@Value("${context.path}")
	private String contextPath;
	
	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IUploadedFileDao uploadedFileDaoImpl;
	
	@Autowired
	private IGroupDao groupDaoImpl;
	
	@Autowired
	private IArticleDao articleDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	@Autowired
	private IRoleDao roleDaoImpl;
	
	@Autowired
	private IUserArtsCountDao userArtsCountDaoImp;
	
	@Autowired
	private IArticleAttaDao articleAttaDaoImpl;
	
	@Autowired
	private IHtmlFileStaticDao htmlFileStaticDaoImpl;
	
	@Autowired
	private ResourceBundleMessageSource messageSource;
	
	@Autowired
	private ICommentBridgeDao commentBridgeDaoImpl;
	
	@ModelAttribute
	public void getArticle(@RequestParam(value = "id", required = false) Long id, Map<String, Object> map) {
		if (id != null && id > 0) {
			map.put("article", articleDaoImpl.findByID(id));
		}
	}
	
	@RequestMapping("/beforeAdd")
	public String beforeAdd(@RequestParam(value = "gid", required = false) Long gid,Map<String, Object> map,HttpServletRequest request,HttpSession session) {
		long uid = LoginUtil.uid(messageSource, request);
		
		boolean free=false;
		String mask="";
		Role role;
		if (LoginUtil.adminChk(messageSource, session)) {
			free=true;
		}
		if (uid>0L) {
			User user=userDaoImpl.findByID(uid);
			role=user.getRole();
			if (role!=null) {
				if (role.getMask()!=null && (role.getMask().trim().equals("0") || role.getMask().trim().equals("a0"))) {
					free=true;
				}else {
					mask = role.getMask();
				}
			}
		}
		
		Article article = new Article();
		article.setStatus(true);
		if (gid==null) {
			gid=0L;
			
		}
		if (gid>0) {
			ArticleGroup ag=groupDaoImpl.findByID(gid);
			if (ag!=null) {
				article.setAgroup(ag);
			}
		}
		map.put("article", article);
		long currTime=System.currentTimeMillis();
		map.put("currTime", currTime);
		String rootTitle=messageSource.getMessage("root.select.title", null, "Select channel", null);
		ArticleGroupMapCreateArgs agmca = new ArticleGroupMapCreateArgs();
		agmca.setCurrRoleMask(mask);
		agmca.setCurrRoot(null);
		agmca.setFree(free);
		agmca.setGroupDaoImpl(groupDaoImpl);
		agmca.setMap(map);
		agmca.setRootTitle(rootTitle);
		agmca.setStatus(1);
		agmca.setMessageSource(messageSource);
		agmca.setRequest(request);
		
//		GroupUtil.mapCreate(agmca,rootTitle);
		
		List<ArticleGroup> gmap=GroupUtil.readFromCache(agmca,rootTitle);
		List<ArticleGroup> aonroot = new ArrayList<ArticleGroup>();
		for (ArticleGroup g:gmap) {
			mask=","+mask+",";
			if (!free && mask.indexOf(",a"+g.getId()+",") == -1 && mask.indexOf(",p"+g.getId()+",") == -1) {
				g.setClogging(false);
			}
			aonroot.add(g);
		}
		
		map.put("preListAll", aonroot);
		
		return ARTICLEEDIT;
	}
	
	@RequestMapping("/add")
	@Token(ajax=false,token = true,contrast = true,csrf = true,loginOrAdmin=true,log=true,mark="article--<add>",failedPage=LOGINPAGE)
	public ModelAndView add(Article article, Errors result,String attasStr,@CookieValue(value="uid_lerx",required=false) String uid_lerx, HttpServletRequest request,HttpSession session,Map<String, Object> map, CutTags tags, String token) {
		Portal portal = portalDaoImpl.query_update();
		if (!portal.isReleasePortal()) {
			return MavUtil.mav1(FORBIDU, messageSource.getMessage("fail.disable.system", null, "The operation is forbidden by the system!", null)) ;
		}
		article=ArticleUtil.validate(messageSource, article);
		User user=null;
		Boolean admin=false;
		boolean passed=false;
		if (uid_lerx!=null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid=Long.valueOf(uid_lerx);
			user=userDaoImpl.findByID(uid);
			
			
			Role role=null;
			if (user!=null) {
				role=user.getRole();
			}
			
			String mask="";
			if (role!=null) {
				mask = role.getMask();
			}
			if (GroupUtil.auditMaskChk(article.getAgroup(), mask)) {
				admin=true;
			}
		}
		
		
		if (!admin && LoginUtil.adminChk(messageSource, session)) {
			admin=true;
		}
		
		if (!admin && (user==null || user.isGag() || user.getRole().isGag())) {
			return MavUtil.mav1("jsp/result/failed", messageSource.getMessage("fail.gag", null, "You may be banned from speaking!", null)) ;
		}
		
		
		if (article.getId()==0) {
			
			CommentBridge cb=new CommentBridge();
			cb.setObjType(2);
			cb.setObjTitle(article.getSubject());
			Poll poll=new Poll();
			poll.setObjType(2);
			poll.setStatus(portal.isPoll());
			poll.setObjTitle(article.getSubject());
			ArticleGroup agroup=article.getAgroup();
			if (agroup==null) {
				return MavUtil.mav1("jsp/result/failed", messageSource.getMessage("fail.nav.null", null, "You do not have a choice of columns!", null)) ;
			}
			agroup=groupDaoImpl.findByID(article.getAgroup().getId());
			poll.setStatus(agroup.isPoll());
			cb.setStatus(agroup.isComm());
			
			if (portal.isArtPassAuto() || admin) {
				article.setPasser(user);
				article.setStatus(true);
			}else {
				article.setStatus(false);
			}
			
			article.setCreationTime(System.currentTimeMillis());
			article.setLastModifyTime(System.currentTimeMillis());
			article.setCb(cb);
			article.setPoll(poll);
			if (user!=null) {
				
				article.setUser(user);
				cb.setUser(user);
				
				if (admin) {
					article.setStatus(true);
				}
				
				UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 0, 1);
				user.setArtsTotal(user.getArtsTotal() + 1);
				
				if (article.isStatus()) {
					user.setArtsPassed(user.getArtsPassed() + 1);
					UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 1, 1);
				}
				
				userDaoImpl.modify(user);
				
			}
			VisitorsBook vbook = new VisitorsBook();
			vbook.setObjType(2);
			vbook.setObjTitle(article.getSubject());
			article.setVbook(vbook);
			
			HtmlFileStatic hfs = new HtmlFileStatic();
			article.setHfs(hfs);
			
			//生成全站搜索模型
			SearchTotalModel srt = new SearchTotalModel();
			article.setSrt(srt);
			article=articleDaoImpl.add(article);
			groupDaoImpl.modifyChanged(article.getAgroup());
			FileEl fe=ArticleUtil.feBuild(messageSource, request, article,false);
			hfs=article.getHfs();
			hfs.setRealPath(fe.getRealPath());
			hfs.setUrl(fe.getUrl());
			hfs.setFilename(FileUtil.getFileFromPath(fe.getRealPath()));
			htmlFileStaticDaoImpl.modify(hfs);
			
			//生成全站搜索模型url
			article = ArticleUtil.srtUpdate(article);
			
			article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
			articleDaoImpl.modify(article);
			
			article.getCb().setHosturl(ArticleUtil.getHref(messageSource, request, article));
			commentBridgeDaoImpl.modify(article.getCb());
			if (article.isStatus()) {
				
				boolean jump=false;
				if (article.getJumpUrl()!=null && !article.getJumpUrl().trim().equals("")) {
	  				jump=true;
	  			}
				if (!jump) {
					ArticleUtil.htmlCreate(request, messageSource, contextPath,article);
					article.getHfs().setStatus(true);
					htmlFileStaticDaoImpl.modify(article.getHfs());
				}
			}
			ArtAttaUtil.refresh(article, attasStr, articleAttaDaoImpl);
			passed=article.isStatus();
			map.put("passed", passed);
			return MavUtil.mav2("jsp/article/continue", messageSource.getMessage("success.article.add", null, "The article is published successfully!", null),article.getAgroup().getId()) ;
		}else{
			if (article.isStatus() && admin) {
				article.setStatus(true);
			}else if(!portal.isArtPassAuto()) {
				article.setStatus(false);
			}
			article.setLastModifyTime(System.currentTimeMillis());
			articleDaoImpl.modify(article);
			if (article.isStatus()) {
				ArticleUtil.htmlCreate(request, messageSource,contextPath, article);
				article.getHfs().setStatus(true);
				htmlFileStaticDaoImpl.modify(article.getHfs());
				
				if (article.getCb().getHosturl()==null || article.getCb().getHosturl().trim().equals("")) {
					article.getCb().setHosturl(ArticleUtil.getHref(messageSource, request, article));
					commentBridgeDaoImpl.modify(article.getCb());
				}
				
				
			}else {
				FileUtil.delete(FileUtil.appPath() + File.separator + article.getHfs().getRealPath());
			}
			article = ArticleUtil.srtUpdate(article);
			article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
			articleDaoImpl.modify(article);
			
			ArtAttaUtil.refresh(article, attasStr, articleAttaDaoImpl);
			passed=article.isStatus();
			map.put("passed", passed);
			return MavUtil.mav1("jsp/article/success", messageSource.getMessage("success.article.add", null, "The article is published successfully!", null)) ;
		}
		
		//mapCreate(map,groupDaoImpl,group);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/loginer/{id}")
	@Token(ajax=true,csrf=true)
	public int auditloginer(@PathVariable("id") Long id, Map<String, Object> map,HttpServletRequest request,HttpSession session) {
		
		Role role;
		long uid = LoginUtil.uid(messageSource, request);
		if (uid>0){
			
			User user=userDaoImpl.findByID(uid);
			if (user==null) {
				return -201;
			}
			role=user.getRole();
			if (role!=null) {
				String mask = role.getMask();
				
				if (id==0) {
					return 1;
				}else {
					Article article = articleDaoImpl.findByID(id);
					if (role.getMask()!=null && (role.getMask().trim().equals("0") ||GroupUtil.auditMaskChk(article.getAgroup(), mask) )) {
						return 1;
					}else {
						return -200;
					}
				}
				
				
			}else {
				return -201;
			}
			
		}else{
			return -201;
		}
		
	}
	
	
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@Token(ajax=false,csrf=true,contrast = true)
	public String edit(@PathVariable("id") Long id, Map<String, Object> map,HttpServletRequest request,HttpSession session) {
		
		long uid = LoginUtil.uid(messageSource, request);
		boolean free=false;
		String mask="";
		Role role;
		if (LoginUtil.adminChk(messageSource, session)) {
			free=true;
		}
		if (uid>0L) {
			User user=userDaoImpl.findByID(uid);
			role=user.getRole();
			if (role!=null) {
				mask = role.getMask();
				if (role.getMask()!=null && (role.getMask().trim().equals("0") || role.getMask().trim().equals("a0"))) {
					free=true;
				}
			}
		}
		
		Article article = articleDaoImpl.findByID(id);
		boolean admin=LoginUtil.adminChk(messageSource, session);
		
		
		if (article!=null && (admin || article.getUser().getId() - uid==0 || GroupUtil.editMaskChk(article.getAgroup(), mask))) {	//如果有权限可以编辑
			map.put("article", article);
		}else {
			return FORBIDU;
		}
		
		if (admin || (mask!=null && mask.trim().equals("0"))) {
			map.put("admin", true);
		}
		
		
		long currTime=System.currentTimeMillis();
		map.put("currTime", currTime);
		String rootTitle=messageSource.getMessage("root.title", null, "Root", null);
		
		ArticleGroupMapCreateArgs agmca = new ArticleGroupMapCreateArgs();
		agmca.setCurrRoleMask(mask);
		agmca.setCurrRoot(null);
		agmca.setFree(free);
		agmca.setGroupDaoImpl(groupDaoImpl);
		agmca.setMap(map);
		agmca.setRootTitle(rootTitle);
		agmca.setStatus(1);
		agmca.setMessageSource(messageSource);
		agmca.setRequest(request);
		
		GroupUtil.mapCreate(agmca,rootTitle);
		return ARTICLEEDIT;
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/delete/{id}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<delete>")
	public int delOnFg(@PathVariable(value = "id", required = true) Long id, HttpServletRequest request,HttpSession session,@CookieValue(value="uid_lerx",required=false) String uid_lerx) {
		boolean result;
		
		Article article=articleDaoImpl.findByID(id);
		User loger;
		boolean admin=false;
		if (uid_lerx!=null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid=Long.valueOf(uid_lerx);
			loger=userDaoImpl.findByID(uid);
			
			if (loger==null) {
				return -201;
			}
			
			Role role=null;
			if (loger!=null) {
				role=loger.getRole();
			}
			
			String mask="";
			if (role!=null) {
				mask = role.getMask();
			}
			if (GroupUtil.auditMaskChk(article.getAgroup(), mask)) {
				
				admin=true;
			}
		}else {
			return -201;
		}
		if (!admin) {
			return -200;
		}
		
		ArticleGroup g = article.getAgroup();
		User user=article.getUser();
		if (user!=null) {
			
			UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 0, -1);
			if (user.getArtsTotal()>0) {
				user.setArtsTotal(user.getArtsTotal() - 1);
			}
			if (article.isStatus()) {
				if (user.getArtsPassed()>0) {
					user.setArtsPassed(user.getArtsPassed() - 1);
				}
				UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 1, -1);
			}
			userDaoImpl.modify(user);
		}
		
		FileUtil.delete(FileUtil.appPath() + File.separator + article.getHfs().getRealPath());
		
//		result=articleDaoImpl.delByID(id);
		long aid=article.getId();
		article=ArticleUtil.srtUpdate(article);
		article.setDeled(true);
		article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
		articleDaoImpl.modify(article);
		if (articleDaoImpl.findByID(aid)==null) {
			result=true;
		}else {
			result=false;
		}
		
		
		article=ArticleUtil.srtUpdate(article);
		article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
		articleDaoImpl.modify(article);
		
		if (result) {
			
			groupDaoImpl.modifyChanged(g);
			return 0;
		}else {
			return -1;
		}
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/del/{id}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<del>",admin=true,failedPage=FAILED)
	public int del(@PathVariable(value = "id", required = true) Long id, HttpServletRequest request,HttpSession session) {
		boolean result;
		
		Article article=articleDaoImpl.findByID(id);
		if (article==null) {
			return -404;
		}
		ArticleGroup g = article.getAgroup();
		User user=article.getUser();
		if (user!=null) {
			
			UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 0, -1);
			if (user.getArtsTotal()>0) {
				user.setArtsTotal(user.getArtsTotal() - 1);
			}
			if (article.isStatus()) {
				if (user.getArtsPassed()>0) {
					user.setArtsPassed(user.getArtsPassed() - 1);
				}
				UserUtil.uacUpdate(user, article, userArtsCountDaoImp, 1, -1);
			}
			userDaoImpl.modify(user);
		}
		
		FileUtil.delete(FileUtil.appPath() + File.separator + article.getHfs().getRealPath());
		long aid=article.getId();
		article=ArticleUtil.srtUpdate(article);
		article.setDeled(true);
		article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
		articleDaoImpl.modify(article);
		if (articleDaoImpl.findByID(aid)==null) {
			result=true;
		}else {
			result=false;
		}
		
		if (result) {
			
			groupDaoImpl.modifyChanged(g);
			return 0;
		}else {
			return -1;
		}
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/addtime/{id}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<addtime>",loginOrAdmin=true,failedPage=LOGINPAGE)
	public int modifyAddTime(@PathVariable(value = "id", required = true) Long id,String addtimeStr, HttpServletRequest request,HttpSession session) {
		if (addtimeStr==null || addtimeStr.trim().equals("") || !TimeUtil.isValidDatetime(addtimeStr)) {
			return -400;
		}
		boolean admin=false;
		
		Article article=articleDaoImpl.findByID(id);
		
		if (article==null) {
			return -404;
		}
		
		if (LoginUtil.adminChk(messageSource, session)) {
			admin=true;
		}
		if (!admin) {
			long uid = LoginUtil.uid(messageSource, request);
			if (uid<=0) {
				return -201;
			}
			User user = userDaoImpl.findByID(uid);
			
			if (UserUtil.isadmin(user)) {
				admin=true;
			}else {
				if (user.getRole()==null) {
					return -200;
				}
				if (GroupUtil.auditMaskChk(article.getAgroup(), user.getRole().getMask())){
					admin=true;
				}
			}
			
		}
		
		if (!admin) {
			return -200;
		}
		
		boolean htmlBuild=false;
		
		
		article.setCreationTime(TimeUtil.coverStrToLong(addtimeStr));
		articleDaoImpl.modify(article);
		
		FileEl fe=ArticleUtil.feBuild(messageSource, request, article,true);
		HtmlFileStatic hfs;
		hfs=article.getHfs();
		htmlBuild=hfs.isStatus();
		FileUtil.delete(FileUtil.appPath() + File.separator + hfs.getRealPath());
		
		hfs.setRealPath(fe.getRealPath());
		hfs.setUrl(fe.getUrl());
		hfs.setFilename(FileUtil.getFileFromPath(fe.getRealPath()));
		htmlFileStaticDaoImpl.modify(hfs);
		
		if (article.isStatus() && htmlBuild) {
			ArticleUtil.htmlCreate(request, messageSource,contextPath, article);
		}
		article=ArticleUtil.srtUpdate(article);
		article.getSrt().setHref(ArticleUtil.getHref(messageSource, request, article));
		articleDaoImpl.modify(article);
		
		article.getCb().setHosturl(ArticleUtil.getHref(messageSource, request, article));
		commentBridgeDaoImpl.modify(article.getCb());
		
		return 0;
	}
		
	
	
	@ResponseBody
	@RequestMapping(value = "/top/{id}/{status}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<top>",role0=true,failedPage=LOGINPAGE)
	public int modifyTopOne(@PathVariable(value = "id", required = true) Long id,@PathVariable(value = "status", required = true) Integer status) {
		
		Article article=articleDaoImpl.findByID(id);
		boolean sta;
		if (status==0) {
			sta=false;
		}else {
			sta=true;
		}
		if (article!=null) {
			articleDaoImpl.modifyTopOne(id, sta);
		}else {
			return -404;
		}
		
		return 0;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/soul/{id}/{status}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<top>",role0=true,failedPage=LOGINPAGE)
	public int modifySoul(@PathVariable(value = "id", required = true) Long id,@PathVariable(value = "status", required = true) Integer status) {
		
		Article article=articleDaoImpl.findByID(id);
		if (article==null) {
			return -404;
		}
		if (status==0) {
			article.setSoul(false);
		}else {
			article.setSoul(true);
		}
		articleDaoImpl.modify(article);
		
		return 0;
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/pass/{id}/{status}")
	@Token(ajax=true,csrf=true,contrast = true,log=true,mark="article--<pass>",loginOrAdmin=true,failedPage=LOGINPAGE)
	public int modifyPass(@PathVariable(value = "id", required = true) Long id,@PathVariable(value = "status", required = true) Integer status,HttpServletRequest request,HttpSession session) {
		boolean admin=LoginUtil.adminChk(messageSource, session);
		boolean con=false;
		if (admin) {
			con=true;
		}
		Article art = articleDaoImpl.findByID(id);
		
		long uid = LoginUtil.uid(messageSource, request);
		
		User user=userDaoImpl.findByID(uid);
		Role role=null;
		if (user!=null) {
			role=user.getRole();
		}
		
		String mask="";
		if (role!=null) {
			mask = role.getMask();
		}
		if (!admin && GroupUtil.auditMaskChk(art.getAgroup(), mask)) {
			con=true;
		}
		
		if (con) {
			if (status==1) {
				art.setPasser(user);
				art.setStatus(true);
			}else {
				art.setPasser(null);
				art.setStatus(false);
			}
			art=ArticleUtil.srtUpdate(art);
			art.getSrt().setHref(ArticleUtil.getHref(messageSource, request, art));
			
			articleDaoImpl.modify(art);
			
			if (art.isStatus() && GroupUtil.openChk(art.getAgroup())) {
				boolean jump=false;
				if (art.getJumpUrl()!=null && !art.getJumpUrl().trim().equals("")) {
	  				jump=true;
	  			}
				if (!jump) {
					ArticleUtil.htmlCreate(request, messageSource,contextPath, art);
					art.getHfs().setStatus(true);
				}
				if (art.getUser()!=null) {
					UserUtil.uacUpdate(art.getUser(), art, userArtsCountDaoImp, 1, 1);
					art.getUser().setArtsPassed(art.getUser().getArtsPassed()+1);
					userDaoImpl.modify(art.getUser());
				}
				
			}else {
				
				
				if (art.getUser()!=null) {
					UserUtil.uacUpdate(art.getUser(), art, userArtsCountDaoImp, 1, -1);
					if (art.getUser().getArtsPassed()>0) {
						art.getUser().setArtsPassed(art.getUser().getArtsPassed() - 1);
						userDaoImpl.modify(art.getUser());
					}
				}
				
				FileUtil.delete(FileUtil.appPath() + File.separator + art.getHfs().getRealPath());
				art.getHfs().setStatus(false);
				
			}
			//更新目录的状态
			groupDaoImpl.modifyChanged(art.getAgroup());
			htmlFileStaticDaoImpl.modify(art.getHfs());
			return 0;
		}
		
		return -200;
		
	}
	
	@RequestMapping("/inventory")
	@Token(ajax=false)
	public String inventory(@RequestParam(value = "gid", required = false) Long gid,@RequestParam(value = "status", required = false) Integer status,@RequestParam(value = "page", required = false) Integer page,@RequestParam(value = "pageSize", required = false) Integer pageSize,HttpServletRequest request,Map<String, Object> map) {
		Portal portal=portalDaoImpl.query_update();
		boolean asc=false;
		if (gid==null) {
			gid=0L;
		}
		if (page == null) {
			page = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		
		
		long uid = LoginUtil.uid(messageSource, request);
		
		User user=userDaoImpl.findByID(uid);
		Role role=null;
		if (status==null) {
			status=1;
		}
		boolean admin=false;
		ArticleGroup agroup=groupDaoImpl.findByID(gid);
		if (user!=null) {
			role=user.getRole();
			if (role!=null && role.getMask()!=null) {
				if (GroupUtil.auditMaskChk(groupDaoImpl.findByID(gid), role.getMask())) {
					admin=true;
				}
			}
		}
		Rs rs;
		if (!admin) {
			switch (status) {
			case 1:
				rs=articleDaoImpl.queryByGid(gid,0,0,0, page, pageSize, asc,1,0,0,0);
				break;
			case 0:
				rs=articleDaoImpl.queryByGid(gid,0,0,0, page, pageSize, asc,1,0,0,0);
				break;
			default:
				rs=RsUtil.init(page, pageSize, 0);
				rs.setList(null);
			}
			
		}else {
			rs=articleDaoImpl.queryByGid(gid,0,0,0, page, pageSize, asc,status,0,0,0);
		}
		map.put("rs", rs);
		map.put("pageUrl", "/action_article/inventory?gid="+gid+"&status="+status);
		map.put("portal", portal);
		map.put("agroup", agroup);
		map.put("status", status);
		
		return "jsp/article/inventory";
	}
	
	@RequestMapping("/list")
	@Token(ajax=false,admin=true,failedPage=FAILED,failedReturnUrl = ADMINFAILRETURN)
	public String list(@RequestParam(value = "gid", required = false) Long gid,@RequestParam(value = "page", required = false) Integer page,@RequestParam(value = "pageSize", required = false) Integer pageSize,HttpServletRequest request,Map<String, Object> map) {
		if (gid==null) {
			gid=0L;
		}
		if (page == null) {
			page = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		ArticleGroup agCur;
		if (gid>0L) {
			agCur=groupDaoImpl.findByID(gid);
		}else {
			agCur=null;
			
		}
		
		if (agCur==null) {
			gid=0L;
		}
		
		map.put("gid", gid);
		
		String rootTitle=messageSource.getMessage("nav.all.select.title", null, "All navs", null);
		ArticleGroupMapCreateArgs agmca = new ArticleGroupMapCreateArgs();
		agmca.setCurrRoleMask("0");
		agmca.setCurrRoot(agCur);
		agmca.setFree(true);
		agmca.setGroupDaoImpl(groupDaoImpl);
		agmca.setMap(map);
		agmca.setRootTitle(rootTitle);
		agmca.setStatus(0);
		agmca.setMessageSource(messageSource);
		agmca.setRequest(request);
		
		GroupUtil.mapCreate(agmca,rootTitle);
		
		Rs rs=articleDaoImpl.queryByGid(gid,0,0,0, page, pageSize, false,0,0,0,0);
		map.put("rs", rs);
		/*List<?> ltmp=rs.getList();
		for (Object o:ltmp) {
			System.out.println("o.toString():"+o.toString());
		}
		List<Article> la=(List<Article>) rs.getList();
		for (Article a:la) {
			System.out.println("未查 id:"+a.getId() + "  "+a.getSubject() +" status:" +a.isStatus() + "  soul:" + a.isSoul() + "  topOne:" + a.isTopOne());
			a = articleDaoImpl.findByID(a.getId());
			System.out.println("查了 id:"+a.getId() + "  "+a.getSubject() +" status:" +a.isStatus() + "  soul:" + a.isSoul() + "  topOne:" + a.isTopOne());
		}*/
		map.put("pageUrl", "action_article/list?gid="+gid);
		map.put("rootUrl", "action_article/list");
		
		return ARTICLELIST;
	}
	
	@RequestMapping("/search")
	@Token(ajax=false,csrf=true)
	public String search(String keywords,@RequestParam(value = "page", required = false) Integer page,@RequestParam(value = "pageSize", required = false) Integer pageSize,HttpServletRequest request,Map<String, Object> map) {
		if (HttpUtil.referer(request)==null) {
			return "Error! Code :-408";
		}
		Portal portal =portalDaoImpl.query_update();
		map.put("portal", portal);
		if (keywords!=null) {
			keywords=StringUtil.htmlFilter(keywords);
		}
		if (keywords==null || keywords.trim().equals("")) {
			map.put("keywords", null);
			return "jsp/article/search";
		}
		if (page == null) {
			page = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		Rs rs  = articleDaoImpl.search(0, keywords, true, 0, page, pageSize);
		map.put("keywords", keywords);
		map.put("rs", rs);
		map.put("pageUrl", "/action_article/search?keywords="+keywords);
		
		return "jsp/article/search";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/neighbour/{id}/{gid}/{mod}")
	@Token(ajax=true,csrf=true,contrast = true)
	public SimpleArticle neighbour(@PathVariable(value = "id", required = true) Long id,@PathVariable(value = "gid", required = true) Long gid,@PathVariable(value = "mod", required = true) Integer mod) {
		Article art=articleDaoImpl.findByID(id);
		ArticleGroup ag = null;
		if (gid>0L) {
			ag=groupDaoImpl.findByID(gid);
		}else {
			gid=0L;
		}
		
		if (ag==null) {
			gid=0L;
		}
		art=articleDaoImpl.findNeighbour(id, mod, gid);
		SimpleArticle sart=new SimpleArticle();
		if (art==null) {
			sart.setId(0);
		}else {
			
			sart.setAuthor(art.getAuthor());
			sart.setHref(art.getHfs().getUrl());
			sart.setId(art.getId());
			sart.setSubject(art.getSubject());
			if (art.getSubjectShort()!=null && !art.getSubjectShort().trim().equals("")) {
				sart.setSubjectShort(art.getSubjectShort());
			}else {
				sart.setSubjectShort(sart.getSubject());
			}
			sart.setSynopsis(art.getSynopsis());
			sart.setThumbnail(art.getThumbnail());
			if (art.getUser()!=null) {
				sart.setUid(art.getUser().getId());
				sart.setUsername(art.getUser().getUsername());
			}else {
				sart.setUid(0);
				sart.setUsername("admin");
			}
			
		}
		return sart;
	}
	
	
	//接收文章
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ResponseBody
	@RequestMapping(value = "/recive" , method = RequestMethod.POST)
	@Token(ajax=true)
	public int recive(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception {
		String path = FileUtil.appPath();
		String receiveFolder=path+File.separator+"recives"+File.separator;
		receiveFolder=FileUtil.repairFilePath(receiveFolder);
		File filePath = new File(receiveFolder);
		if (!filePath.exists()) {
			filePath.mkdirs();
			FileUtil.erable(filePath);
		}
		
		String pathfilename="recives"+File.separator + file.getOriginalFilename();
//		FileInf fi = 
		FileUtil.upload(file, pathfilename);
		String fullFileName = receiveFolder + File.separator + file.getOriginalFilename();
		fullFileName=FileUtil.repairFilePath(fullFileName);
		File f = new File(fullFileName);
		SimpleReciveArticle sarticle = (SimpleReciveArticle) ObjUtil.objectXmlDecoder(f.toString()).get(0);
		String webinf=FileUtil.webinfPath()+File.separator;
		if (sarticle==null || sarticle.getAgroup()==null ) {
			ReciveUtil.logw(webinf, "recive.log", "-416   获得文章   文件：" + pathfilename);
			return -416;
		}
		SimpleReciveArticleGroup sagroup = sarticle.getAgroup();
		SimpleReciveUser suser = sarticle.getUser();
		if (sarticle.getUuid()==null || sarticle.getUuid().trim().equals("")) {
			ReciveUtil.logw(webinf, "recive.log", "-4161  获得文章   标题："+sarticle.getSubject());
			return -4161;
		}
		if (sagroup.getUuid()==null || sagroup.getUuid().trim().equals("")) {
			ReciveUtil.logw(webinf, "recive.log", "-4162  获得文章   标题："+sarticle.getSubject());
			return -4162;
		}
		if (suser!=null && (suser.getUuid()==null || suser.getUuid().trim().equals(""))) {
			ReciveUtil.logw(webinf, "recive.log", "-4164  获得文章   标题："+sarticle.getSubject());
			return -4164;
		}
		String securityStr = SecurityUtil.readWords("recivekey");
		if (securityStr==null || securityStr.trim().equals("")) {
			ReciveUtil.logw(webinf, "recive.log", "-403  获得文章   标题："+sarticle.getSubject());
			return -403;
		}
		if (sarticle.getExtrakey()==null || !sarticle.getExtrakey().trim().equals(securityStr)) {
			ReciveUtil.logw(webinf, "recive.log", "-401  获得文章   标题："+sarticle.getSubject());
			return -401;
		}
		UploadArgs ua = new UploadArgs();
		ua.setCh(0);
		ua.setCw(0);
		
		ua.setIntact(true);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(null);
		ua.setTitle(null);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		
		ReciveUserModular rum =UserUtil.reviceUser(suser, userDaoImpl, roleDaoImpl, ua, request, response);
		User user = rum.getUser();
		ua=rum.getUa();
		/*
		 * User user = userDaoImpl.findByUuid(suser.getUuid()); if (user==null) { user =
		 * new User(); if (userDaoImpl.findByUsername(suser.getUsername())==null) {
		 * user.setUsername(suser.getUsername()); }else {
		 * user.setUsername(suser.getUsername()+"_"+TimeUtil.coverLongToStr(System.
		 * currentTimeMillis(), "yyyyMMdd")); } user.setUuid(suser.getUuid());
		 * user.setTruename(suser.getTruename()); user.setNickname(suser.getNickname());
		 * if (suser.getEmail()!=null && !suser.getEmail().trim().equals("")) {
		 * user.setEmail(suser.getEmail()); } if (suser.getMobile()!=null &&
		 * !suser.getMobile().trim().equals("")) { user.setMobile(suser.getMobile()); }
		 * 
		 * user.setCreateTime(suser.getCreateTime());
		 * user.setCreateIP(suser.getCreateIP()); user.setState(suser.isState());
		 * user.setDept(suser.getDept());
		 * user.setPassword(StringUtil.md5(""+System.currentTimeMillis()));
		 * user.setRole(roleDaoImpl.findDef()); user.setSalt(suser.getSalt());
		 * user.setPassword(suser.getPassword()); user=userDaoImpl.addAndUuid(user);
		 * ua.setUid(user.getId()); if (suser.getAvatarUrl()!=null &&
		 * !suser.getAvatarUrl().trim().equals("")) { UploadedFile
		 * uf=UploadUtil.downUrlFile(ua, suser.getAvatarUrl(),request, response);
		 * user.setAvatarUrl(uf.getUrl()); } userDaoImpl.modify(user);
		 * 
		 * } ua.setUid(user.getId());
		 */
		ArticleGroup group=groupDaoImpl.findByUuid(sagroup.getUuid());
		if (group == null) {
			group = new ArticleGroup();
			group.setUuid(sagroup.getUuid());
			group.setComm(true);
			group.setOpen(sagroup.isOpen());
			group.setPoll(true);
			group.setStatus(sagroup.isStatus());
			group.setClogging(true);
			group.setGather(false);
			group.setStaticPage(true);
			group.setChanged(true);
			group.setIpVisitAllow(sagroup.getIpVisitAllow());
			if (sagroup.getName()==null || sagroup.getName().trim().equals("")) {
				group.setName("<none name>");
			}else {
				group.setName(sagroup.getName());
			}
			
			/*
			 * VisitorsBook vbook = new VisitorsBook(); vbook.setObjType(1);
			 * vbook.setObjTitle(sagroup.getName()); group.setVbook(vbook);
			 */
			
			groupDaoImpl.add(group);
		}
		
		Article newarticle=articleDaoImpl.findByUuid(sarticle.getUuid());
		
		
		if (newarticle==null) {
			newarticle= new Article();
			newarticle.setUuid(sarticle.getUuid());
			newarticle.setAgroup(group);
			
			newarticle.setCreationTime(sarticle.getCreationTime());
			newarticle.setSoul(sarticle.isSoul());
			newarticle.setStatus(sarticle.isStatus());
			newarticle.setAuthor(sarticle.getAuthor());
			
			newarticle.setUser(user);
			
			newarticle.setAuthorDept(sarticle.getAuthorDept());
			
			newarticle.setExtra(sarticle.getExtra());
			newarticle.setLastModifyTime(sarticle.getLastModifyTime());
			newarticle.setCreationTime(sarticle.getCreationTime());
			newarticle.setJumpUrl(sarticle.getJumpUrl());
			newarticle.setMediaUrl(sarticle.getMediaUrl());
			if (sarticle.getSubject()==null || sarticle.getSubject().trim().equals("")) {
				newarticle.setSubject("article at "+TimeUtil.coverLongToStr(sarticle.getCreationTime(), "yyyyMMdd"));
			}else {
				newarticle.setSubject(sarticle.getSubject());
			}
			
			newarticle.setSubjectShort(sarticle.getSubjectShort());
			newarticle.setSynopsis(sarticle.getSynopsis());
			
			newarticle.setTitleImgTxt(sarticle.getTitleImgTxt());
			newarticle.setToppic(sarticle.getToppic());
			
			/*
			 * 图片处理
			 */
			if (sarticle.getThumbnail()!=null && !sarticle.getThumbnail().trim().equals("")) {
				UploadedFile uf=UploadUtil.downUrlFile(ua, sarticle.getThumbnail(),request, response);
				if (uf!=null) {
					newarticle.setThumbnail(uf.getUrl());
				}
				
			}
			
			if (sarticle.getTitleImg()!=null && !sarticle.getTitleImg().trim().equals("")) {
				UploadedFile uf=UploadUtil.downUrlFile(ua, sarticle.getTitleImg(), request,response);
				if (uf!=null) {
					newarticle.setTitleImg(uf.getUrl());
				}
				
			}
			newarticle.setContent(ReciveUtil.contentImgDown(ua,sarticle.getContent(),request,response));
			/*
			 * content.setThumbnail(article.getThumbnail());
			 * content.setTitleImg(article.getTitleImg());
			 */
			
			CommentBridge cb = new CommentBridge();
			cb.setUser(user);
			cb.setStatus(true);
			Poll poll = new Poll();
			poll.setStatus(true);
			poll.setObjTitle(newarticle.getSubject());
			poll.setAgrees(sarticle.getPollAgree());

			newarticle.setCb(cb);
			newarticle.setPoll(poll);

			VisitorsBook vbook = new VisitorsBook();
			vbook.setObjType(0);
			vbook.setObjTitle(newarticle.getSubject());
			vbook.setIpTotal(sarticle.getViews());
			newarticle.setVbook(vbook);

			HtmlFileStatic hfs = new HtmlFileStatic();
			newarticle.setHfs(hfs);
			
			articleDaoImpl.add(newarticle);
			newarticle = articleDaoImpl.findByID(newarticle.getId());
			
			hfs = newarticle.getHfs();
			FileEl fe = ArticleUtil.feBuild(messageSource, request, newarticle, false);
			hfs.setRealPath(fe.getRealPath());
			hfs.setUrl(fe.getUrl());
			hfs.setFilename(FileUtil.getFileFromPath(fe.getRealPath()));
			newarticle.setHfs(hfs);
			newarticle.getCb().setHosturl(ArticleUtil.getHref( messageSource, request,newarticle));
			articleDaoImpl.modify(newarticle);
			
			
			newarticle = ArticleUtil.srtUpdate(newarticle);
			newarticle.getSrt().setHref(ArticleUtil.getHref(messageSource, request, newarticle));
			articleDaoImpl.modify(newarticle);

			if (newarticle.isStatus() && newarticle.getAgroup().isOpen() && newarticle.getAgroup().isStatus()) {
				ArticleUtil.htmlCreate(request, messageSource, contextPath,newarticle);
				newarticle.getHfs().setStatus(true);
				htmlFileStaticDaoImpl.modify(newarticle.getHfs());
			}
			
			
			ReciveUtil.logw(webinf, "recive.log", "0000  获得文章   标题："+sarticle.getSubject());
			f.delete();
			return 0;
		}else {
			ReciveUtil.logw(webinf, "recive.log", "-502  获得文章   标题："+sarticle.getSubject());
			return -502;
		}
		
		
	}
	
	
}
