package com.lerx.handlers;

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

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.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lerx.analyze.util.AnalyzeUtil;
import com.lerx.analyze.vo.DataShowParams;
import com.lerx.analyze.vo.FindedDataAnalyzeResult;
import com.lerx.annotation.Token;
import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.IAlbumExternalLinkDao;
import com.lerx.dao.iface.IAlbgenreDao;
import com.lerx.dao.iface.IAlbgenreMangerDao;
import com.lerx.dao.iface.IAlbumArticleClassifyDao;
import com.lerx.dao.iface.IAlbumPartnerDao;
import com.lerx.dao.iface.ICommentBridgeDao;
import com.lerx.dao.iface.ICommentThreadDao;
import com.lerx.dao.iface.IHtmlFileStaticDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IRoleDao;
import com.lerx.dao.iface.ITempletAlbgenreMainDao;
import com.lerx.dao.iface.ITempletAlbumMainDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.dao.iface.IVisitArchivesDao;
import com.lerx.dao.iface.IVisitorCountInPeriodDao;
import com.lerx.dao.iface.IVisitorIPRecordDao;
import com.lerx.dao.iface.IVisitorsBookDao;
import com.lerx.entities.Album;
import com.lerx.entities.AlbumArticle;
import com.lerx.entities.AlbumArticleClassify;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.CommentThread;
import com.lerx.entities.Portal;
import com.lerx.entities.Albgenre;
import com.lerx.entities.TempletAlbgenreMain;
import com.lerx.entities.TempletAlbumMain;
import com.lerx.entities.TempletComment;
import com.lerx.entities.TempletSubElement;
import com.lerx.entities.User;
import com.lerx.entities.VisitorIPRecord;
import com.lerx.entities.VisitorsBook;
import com.lerx.hql.entities.Rs;
import com.lerx.ip.util.IPUtil;
import com.lerx.login.util.LoginUtil;
import com.lerx.portal.obj.AppEnvParms;
import com.lerx.portal.obj.FlowOut;
import com.lerx.portal.obj.EnvirSet;
import com.lerx.portal.obj.GlobalTagsAnalyzeReturn;
import com.lerx.portal.obj.TempletCommentFmtRequisite;
import com.lerx.portal.obj.UserPanelCodeArgs;
import com.lerx.sys.obj.DatetimeSpanSuffixTxt;
import com.lerx.sys.obj.EnvParms;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.sys.util.TokenUtil;
import com.lerx.v6.util.AlbgenreUtil;
import com.lerx.v6.util.AlbumArticleUtil;
import com.lerx.v6.util.CommUtil;
import com.lerx.v6.util.ConfigUtil;
import com.lerx.v6.util.ErrorUtil;
import com.lerx.v6.util.HttpShowUtil;
import com.lerx.v6.util.PartnerUtil;
import com.lerx.v6.util.TempletAlbgenreUtil;
import com.lerx.v6.util.TempletAlbumUtil;
import com.lerx.v6.util.TempletUtil;
import com.lerx.v6.util.UserUtil;
import com.lerx.v6.util.VisitUtil;

@RequestMapping("/show_album")
@Controller
public class HttpShowAlbumHandler {
	
	
	@Autowired
	private ResourceBundleMessageSource messageSource;
	
	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IAlbgenreDao albgenreDaoImpl;
	
	@Autowired
	private IAlbgenreMangerDao albgenreMangerDaoImpl;
	
	@Autowired
	private IAlbumDao albumDaoImpl;
	
	@Autowired
	private IAlbumArticleDao albumArticleDaoImpl;
	
	@Autowired
	private IAlbumPartnerDao albumPartnerDaoImpl;
	
	@Autowired
	private IAlbumArticleClassifyDao albumArticleClassifyDaoImpl;
	
	@Autowired
	private IAlbumExternalLinkDao albumExternalLinkDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	@Autowired
	private IRoleDao roleDaoImpl;
	
	@Autowired
	private ITempletAlbgenreMainDao templetAlbgenreMainDaoImpl;
	
	@Autowired
	private ITempletAlbumMainDao templetAlbumMainDaoImpl;
	
	@Autowired
	private IVisitorIPRecordDao visitorIPRecordDaoImpl;

	@Autowired
	private IVisitorsBookDao visitorsBookDaoImpl;

	@Autowired
	private IVisitArchivesDao visitArchivesDaoImpl;

	@Autowired
	private IVisitorCountInPeriodDao visitorCountInPeriodDaoImpl;

	@Autowired
	private IHtmlFileStaticDao htmlFileStaticDaoImpl;
	
	@Autowired
	private ICommentBridgeDao commentBridgeDaoImpl;

	@Autowired
	private ICommentThreadDao commentThreadDaoImpl;

	
	private EnvirSet envirInit(long gid, long aid, HttpServletRequest request, HttpServletResponse response) {
		EnvirSet es = new EnvirSet();
		es.setStartTime(System.currentTimeMillis());
		if (request == null) {
			es.setRequest(HttpUtil.currRequest());
		} else {
			es.setRequest(request);
		}
		if (response == null) {
			es.setResponse(HttpUtil.currResponse());
		} else {
			es.setResponse(response);
		}
		es.setGid(gid);
		es.setAid(aid);
		es.setMessageSource(messageSource);
		es.setPortalDaoImpl(portalDaoImpl);
		es.setAlbgenreDaoImpl(albgenreDaoImpl);
		es.setAlbumDaoImpl(albumDaoImpl);
		es.setAlbumArticleDaoImpl(albumArticleDaoImpl);
		es.setAlbumArticleClassifyDaoImpl(albumArticleClassifyDaoImpl);
		es.setAlbumExternalLinkDaoImpl(albumExternalLinkDaoImpl);
		es.setTempletAlbgenreMainDaoImpl(templetAlbgenreMainDaoImpl);
		es.setTempletAlbumMainDaoImpl(templetAlbumMainDaoImpl);
		es.setUserDaoImpl(userDaoImpl);
		es.setRoleDaoImpl(roleDaoImpl);
		es.setVisitorIPRecordDaoImpl(visitorIPRecordDaoImpl);
		es.setVisitorsBookDaoImpl(visitorsBookDaoImpl);
		es.setVisitArchivesDaoImpl(visitArchivesDaoImpl);
		es.setVisitorCountInPeriodDaoImpl(visitorCountInPeriodDaoImpl);
		es.setHtmlFileStaticDaoImpl(htmlFileStaticDaoImpl);

		return es;
	}
	
	
	/*
	 * 调查投票区域ajax
	 */
	@ResponseBody
	@RequestMapping(value = "/poll/{id}")
	@Token(ajax = true,csrf=true)
	public String poll(@PathVariable(value = "id", required = true) Long id,
			@RequestParam(value = "titleLen", required = false) Integer titleLen,@RequestParam(value = "overMark", required = false) Integer overMark, HttpServletRequest request,
			HttpServletResponse response) {
		EnvParms ep = HttpUtil.epInit(request, response, null, messageSource);
		if (titleLen == null) {
			titleLen = 0;
		}
		if (overMark == null) {
			overMark=1;
		}
		AlbumArticle art = albumArticleDaoImpl.findByID(id);
		Album album = art.getAlbum();
		
		TempletAlbumMain template = album.getTemplet();
		if (template==null) {
			template=templetAlbumMainDaoImpl.findDef();
		}
				
		String html = TempletAlbumUtil.sundriesTag(messageSource, template, "htmlTemplet_poll");
		String imgHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, template, "htmlTemplet_img");
		if (art != null && album != null && art.getPoll() != null && art.getPoll().isStatus()) {
			AppEnvParms aep=TempletUtil.init(ep, template.getResFolder(), 2);
			html = AlbumArticleUtil.fmt(aep, html, art, imgHtmlTemplet, 0, 0,overMark,false);
		} else {
			html = "";
		}
		
		html = AnalyzeUtil.replace(html, "tag", "contextPath", request.getContextPath());

		return html;
	}
	
	
	/*
	 * 评论表单加载
	 */

	@ResponseBody
	@RequestMapping(value = "/commform/{aid}")
	@Token(ajax = true,csrf=true)
	public String commForm(@PathVariable(value = "aid", required = true) Long aid,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) {
		Portal portal = portalDaoImpl.query_update();
		if (!portal.isComm()) {
			return "";
		}
		if (aid == null) {
			return "";
		}
		AlbumArticle art = albumArticleDaoImpl.findByID(aid);
		Album album = art.getAlbum();
		if (!album.isComm() || !album.isStatus() || !album.getGenre().isStatus() || !album.getGenre().isComm()) {
			return "";
		}
		CommentBridge cb = art.getCb();

		cb = commentBridgeDaoImpl.findByID(cb.getId());

		if (!cb.isStatus()) {
			return "";
		}
		
		TempletAlbumMain template = album.getTemplet();
		if (template==null) {
			template = templetAlbumMainDaoImpl.findDef();
		}
		TempletComment templatec = template.getElComment();
		String html = templatec.getFormCode();
		html = AnalyzeUtil.replace(html, "tag", "bid", "" + cb.getId());
		html = AnalyzeUtil.replace(html, "tag", "aid", "" + aid);
		EnvirSet es;
		es = envirInit(album.getId(), aid, request, null);
		html = TempletUtil.tagToEnvir(html, es);
		html = TempletAlbumUtil.tagForResFolder(messageSource, html, template);
		return html;

	}
	
	
	/*
	 * 评论加载
	 */

	@ResponseBody
	@RequestMapping(value = "/commlist/{id}")
	@Token(ajax = true,csrf=true)
	public FlowOut commlist(@PathVariable(value = "id", required = true) Long id,
			@RequestParam(value = "aid", required = false) Long aid,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) {
		FlowOut co = new FlowOut();
		co.setCount(0);
		co.setPage(1);
		co.setPageCount(0);
		co.setHtml("");
		co.setPageSize(pageSize);
		Portal portal = portalDaoImpl.query_update();
		if (!portal.isComm()) {
			return co;
		}

		CommentBridge cb = null;
		if (id == null) {
			return co;
		}
		cb = commentBridgeDaoImpl.findByID(id);

		if (cb == null || !cb.isStatus()) {
			return co;
		}
		Album album;
		if (aid == null) {
			return co;
		} else {
			AlbumArticle art = albumArticleDaoImpl.findByID(aid);

			if (art == null) {
				return co;
			} else {
				album = art.getAlbum();
				if (album == null || !album.isComm()) {
					return co;
				}
			}
		}

		if (page == null) {
			page = 0;
		}

		if (pageSize == null) {
			pageSize = 10;
		}
		boolean deletedShow = false;
		User user = null;
		if (uid_lerx != null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid = Long.valueOf(uid_lerx);
			user = userDaoImpl.findByID(uid);
		}
		boolean master = false;
		/*
		 * if ((user!=null && cb.getUser()!=null && (user.getId() - cb.getUser().getId()
		 * == 0)) || LoginUtil.admin0Chk(messageSource, session)) { master=true;
		 * 
		 * }
		 */

		if (user != null && cb.getUser() != null) {
			if ((user.getId() - cb.getUser().getId() == 0)) {
				master = true;
			}
			if (UserUtil.isadmin(user)) {
				master = true;
				deletedShow = true;
			}
		}
		int showMode = 1;
		if (master) {
			showMode = 0;
		}
		if (!messageSource.getMessage("comment.thread.deleted.adminshow", null, "false", null).trim().equalsIgnoreCase("true")) {
			deletedShow=false;
		}
		

		Rs rs = commentThreadDaoImpl.queryByBid(cb.getId(), page, pageSize, false, showMode, deletedShow);
		TempletAlbumMain template =album.getTemplet();
		if (template==null) {
			template=templetAlbumMainDaoImpl.findDef();
		}
		TempletComment templatec = template.getElComment();
		String lf =templatec.getItemLoopCode();
		if (lf==null || lf.trim().equals("")) {
			lf = TempletAlbumUtil.sundriesTag(messageSource, template, "htmlTemplet_comm_loop");
		}
		String tmp, tmpAll = "";
		String imgHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, template, "htmlTemplet_img");
		String funHtmlDel = templatec.getActDelCode();
		String funHtmlPass = templatec.getActPassCode();
		String replyAdd = templatec.getActReplyCode();
		/*
		 * String funHtmlDel = TempletUtil.sundriesTag(messageSource,template,
		 * "htmlTemplet_comm_loop_act_del"); String funHtmlPass =
		 * TempletUtil.sundriesTag(messageSource,template,
		 * "htmlTemplet_comm_loop_act_pass"); String replyAdd =
		 * TempletUtil.sundriesTag(messageSource,template,
		 * "htmlTemplet_comm_loop_reply_add");
		 */
		String anonymity = TempletAlbumUtil.sundriesTag(messageSource, template, "anonymity");
		String headDef = TempletAlbumUtil.sundriesTag(messageSource, template, "headDef");
		DatetimeSpanSuffixTxt dsst = TempletAlbumUtil.sundriesTimesLostedTag(template);
		TempletCommentFmtRequisite tcfr = new TempletCommentFmtRequisite();

		tcfr.setFunHtmlPass(funHtmlPass);
		tcfr.setImgHtmlTemplet(imgHtmlTemplet);
		tcfr.setReplyAdd(replyAdd);
		tcfr.setLf(lf);
		tcfr.setMaster(master);
		tcfr.setDsst(dsst);
		tcfr.setAnonymity(anonymity);
		tcfr.setHeadDef(headDef);
		tcfr.setFunHtmlDel(funHtmlDel);
		
		String avatarNull=ConfigUtil.getAvatarNullFile(messageSource, request);
		/*if (request.getContextPath().length()>1) {
			if (!avatarNull.startsWith(request.getContextPath())) {
				avatarNull=request.getContextPath()+avatarNull;
			}
		}else {
			avatarNull="/"+avatarNull;
		}*/
		
		tcfr.setAvatarNull(avatarNull);
		for (Object o : rs.getList()) {
			CommentThread ct = (CommentThread) o;
			tcfr.setLf(lf);
			tmp = CommUtil.fmt(tcfr, ct);
			tmpAll += tmp;
		}

		tmpAll = AnalyzeUtil.replace(tmpAll, "tag", "contextPath", request.getContextPath());
		co.setHtml(tmpAll);
		co.setPageCount(rs.getPageCount());
		co.setCount(rs.getCount());
		return co;

	}
	
	
	/*
	 * 专辑被阅读信息
	 */
	@ResponseBody
	@RequestMapping(value = "/albumViewShow/{id}")
	@Token(ajax = true,csrf=true)
	public String albumVisitfun(@PathVariable(value = "id", required = true) Long id,
			@RequestParam(value = "url", required = false) String url,
			@RequestParam(value = "referer", required = false) String referer, HttpServletRequest request,
			HttpServletResponse response) {
		String html = "";
		if (id == null || id == 0) {
			return html;
		}
		int hotnOfVisit,hotnOfIP;
		hotnOfVisit=Integer.valueOf(messageSource.getMessage("vbook.new.visitor.value", null, "0", null));
		hotnOfIP=Integer.valueOf(messageSource.getMessage("vbook.new.ip.value", null, "5", null));
		Album album = albumDaoImpl.findByID(id);
		long gid = album.getId();
		EnvirSet es = envirInit(gid, 0, request, response);
		Portal portal = portalDaoImpl.query_update();
		VisitorsBook vbook = portal.getVbook();
		VisitUtil.visitorRefresh(es, vbook, "101", url, referer); // 更新浏览者信息
		vbook = album.getVbook();
		boolean newip=VisitUtil.visitorRefresh(es, vbook, "111", url, referer); // 更新浏览者信息
		HttpShowUtil.updateAgHotn(albumDaoImpl, album, newip, hotnOfVisit, hotnOfIP);
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null){
			templet=templetAlbumMainDaoImpl.findDef();
		}
		html = TempletAlbumUtil.sundriesTag(messageSource,templet, "htmlTemplet_view");
		/*
		 * ,htmlTemplet_view:浏览数：{$tag\58views$} IP数：{$tag\58ips$}
		 * 上次来访IP：{$tag\58lastip$}
		 */
		// html = TempletUtil.escape(html);
		html = AnalyzeUtil.replace(html, "tag", "views", "" + album.getVbook().getViewsTotal());
		html = AnalyzeUtil.replace(html, "tag", "ips", "" + album.getVbook().getIpTotal());
		html = AnalyzeUtil.replace(html, "tag", "vbID", album.getVbook().getId());
		VisitorIPRecord vir = es.getVisitorIPRecordDaoImpl().findLast(album.getVbook().getId());
		// IPUtil.ipFilter(vir.getIp(),messageSource.getMessage("ip.filter.mask", null,
		// "1111",null) );
		html = AnalyzeUtil.replace(html, "tag", "lastip",
				IPUtil.ipFilter(vir.getIp(), messageSource.getMessage("ip.filter.mask", null, "1111", null)));
		return html;
	}
	
	
	/*
	 * 文章被阅读信息
	 */
	@ResponseBody
	@RequestMapping(value = "/artViewShow/{id}")
	@Token(ajax = true,csrf=true)
	public String artVisitfun(@PathVariable(value = "id", required = true) Long id,
			@RequestParam(value = "url", required = false) String url,
			@RequestParam(value = "referer", required = false) String referer, HttpServletRequest request,
			HttpServletResponse response) {
		String html = "";
		if (id == null || id == 0) {
			return html;
		}
		AlbumArticle art = albumArticleDaoImpl.findByID(id);
		if (art == null || art.getAlbum() == null) {
			return html;
		}
		long gid = art.getAlbum().getId();
		EnvirSet es = envirInit(gid, 0, request, response);
		Portal portal = portalDaoImpl.query_update();
		int hotnOfVisit,hotnOfIP;
		hotnOfVisit=Integer.valueOf(messageSource.getMessage("vbook.new.visitor.value", null, "0", null));
		hotnOfIP=Integer.valueOf(messageSource.getMessage("vbook.new.ip.value", null, "5", null));
		boolean newip;
		VisitorsBook vbook = portal.getVbook();
		VisitUtil.visitorRefresh(es, vbook, "101", url, referer); // 更新浏览者信息
		vbook = art.getVbook();
		newip=VisitUtil.visitorRefresh(es, vbook, "101", url, referer); // 更新浏览者信息
		HttpShowUtil.updateArtHotn(albumArticleDaoImpl, art, newip, hotnOfVisit, hotnOfIP);
		
		Album album = albumDaoImpl.findByID(gid);
		vbook = album.getVbook();
		newip=VisitUtil.visitorRefresh(es, vbook, "111", url, referer); // 更新浏览者信息
		HttpShowUtil.updateAgHotn(albumDaoImpl, album, newip, hotnOfVisit, hotnOfIP);
		
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null){
			templet=templetAlbumMainDaoImpl.findDef();
		}
		html = TempletAlbumUtil.sundriesTag(messageSource, templet, "htmlTemplet_view");
		/*
		 * ,htmlTemplet_view:浏览数：{$tag\58views$} IP数：{$tag\58ips$}
		 * 上次来访IP：{$tag\58lastip$}
		 */
		// html = TempletUtil.escape(html);
		html = AnalyzeUtil.replace(html, "tag", "views", "" + art.getVbook().getViewsTotal());
		html = AnalyzeUtil.replace(html, "tag", "ips", "" + art.getVbook().getIpTotal());
		html = AnalyzeUtil.replace(html, "tag", "vbID", art.getVbook().getId());
		VisitorIPRecord vir = es.getVisitorIPRecordDaoImpl().findLast(art.getVbook().getId());
		// IPUtil.ipFilter(vir.getIp(),messageSource.getMessage("ip.filter.mask", null,
		// "1111",null) );
		html = AnalyzeUtil.replace(html, "tag", "lastip",
				IPUtil.ipFilter(vir.getIp(), messageSource.getMessage("ip.filter.mask", null, "1111", null)));
		return html;
	}
	
	
	/*
	 * 文章编辑功能区域
	 */
	@ResponseBody
	@RequestMapping(value = "/artfun/{id}")
	@Token(ajax = true,csrf=true)
	public String artfun(@PathVariable(value = "id", required = true) Long id, HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			@CookieValue(value = "username_lerx", required = false) String username_lerx,
			@CookieValue(value = "password_lerx", required = false) String password_lerx) {

		String areaHtml = "";

		if (id == null || id == 0) {
			return areaHtml;
		}
		AlbumArticle art = albumArticleDaoImpl.findByID(id);
		
		Album album = art.getAlbum();
		if (art == null || art.getAlbum() == null) {
			return areaHtml;
		}

		long gid = art.getAlbum().getId();

		boolean backadmin = LoginUtil.adminChk(messageSource, session);

		EnvirSet es = envirInit(gid, 0, request, response);
		long uid = UserUtil.loginRefresh(es, username_lerx, password_lerx);
		User user = userDaoImpl.findByID(uid);
		boolean forePower = false;
		

		if (!backadmin && (user == null || user.getRole() == null)) {
			return areaHtml;
		}
		
		if (PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			forePower=true;
		}
		
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null) {
			templet=templetAlbumMainDaoImpl.findDef();
		}
		boolean genreAdmin=false;	//该频道管理员？
		if (AlbgenreUtil.adminChk(user, art.getAlbum().getGenre(), albgenreMangerDaoImpl)) {
			genreAdmin=true;
		}

		if (backadmin || UserUtil.isadmin(user) || genreAdmin) {	//如果是管理员（前台或后台）
			forePower=true;
			String msg;
			String passHtmlTemplet;
			// 屏蔽与解屏蔽
			if (art.isProhibit()) {
				System.out.println("被屏敝了");
				passHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templet,
						"htmlTemplet_art_release");
				msg = messageSource.getMessage("title.prohibit", null, "Prohibit", null);
				
			}else {
				passHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templet,
						"htmlTemplet_art_prohibit");
				msg = messageSource.getMessage("title.release", null, "Release", null);
			}
			// passHtmlTemplet = TempletUtil.escape(passHtmlTemplet);

			passHtmlTemplet = AnalyzeUtil.replace(passHtmlTemplet, "tag", "status", "" + !art.isStatus());
			passHtmlTemplet = AnalyzeUtil.replace(passHtmlTemplet, "tag", "title", msg);

			passHtmlTemplet = passHtmlTemplet.replaceAll("\r|\n", "");
			areaHtml += passHtmlTemplet;
			
			//精华
			
			String soulHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templet,
					"htmlTemplet_soul");
			if (art.isSoul()) {
				msg = TempletAlbumUtil.sundriesTag(messageSource, templet, "unSoul");
			} else {
				msg = TempletAlbumUtil.sundriesTag(messageSource, templet, "soul");
			}

			soulHtmlTemplet = AnalyzeUtil.replace(soulHtmlTemplet, "tag", "status", "" + !art.isSoul());
			soulHtmlTemplet = AnalyzeUtil.replace(soulHtmlTemplet, "tag", "title", msg);

			soulHtmlTemplet = soulHtmlTemplet.replaceAll("\r|\n", "");
			areaHtml += soulHtmlTemplet;
			

		}

		

		if (forePower) {
			
			//置顶
			String msg;
			/*String topOneHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templet,
					"htmlTemplet_topOne");
			if (art.isTopOne()) {
				msg = TempletAlbumUtil.sundriesTag(messageSource, templet, "unTopOne");
			} else {
				msg = TempletAlbumUtil.sundriesTag(messageSource, templet, "topOne");
			}

			topOneHtmlTemplet = AnalyzeUtil.replace(topOneHtmlTemplet, "tag", "status", "" + !art.isTopOne());
			topOneHtmlTemplet = AnalyzeUtil.replace(topOneHtmlTemplet, "tag", "title", msg);

			topOneHtmlTemplet = topOneHtmlTemplet.replaceAll("\r|\n", "");
			areaHtml += topOneHtmlTemplet;*/
			
			// 编辑
			String editHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templet,
					"htmlTemplet_edit");
			editHtmlTemplet = TempletUtil.escape(editHtmlTemplet);
			msg = TempletAlbumUtil.sundriesTag(messageSource, templet, "edit");
			editHtmlTemplet = AnalyzeUtil.replace(editHtmlTemplet, "tag", "title", msg);
			areaHtml += editHtmlTemplet;

		}

		areaHtml = AnalyzeUtil.replace(areaHtml, "tag", "aid", "" + art.getId());
		areaHtml = AnalyzeUtil.replace(areaHtml, "tag", "subject", art.getContent().getSubject());

		return areaHtml;
	}
	
	
	//获取用户头像
	@ResponseBody
	@RequestMapping("/getAvatar/{aid}/{uid}")
	@Token(ajax = true,csrf=true)
	public String getAvatar(@PathVariable(value = "aid", required = true) Long aid,@PathVariable("uid") Long uid,HttpServletRequest request) {
		String nullAvatar=ConfigUtil.getAvatarNullFile(messageSource, request);
		/*
		 * 从专辑模板中再找
		 */
		if (aid == null) {
			aid = 0L;
		}
		Album album=albumDaoImpl.findByID(aid);
		TempletAlbumMain template = album.getTemplet();
		if (template == null) {
			template = templetAlbumMainDaoImpl.findDef();
		}
		String resFolder=template.getResFolder();
		if (resFolder == null || resFolder.trim().equals("")) {
			resFolder = "default";
		}
		String templetDir = messageSource.getMessage("templet.album.dir", null, "templates/album", null);
		resFolder=templetDir+"/"+resFolder;
		String avatarNone=resFolder+"/images/avatar-null.jpg";
		String realimg=FileUtil.appPath()+"/"+avatarNone;
		realimg=FileUtil.repairFilePath(realimg);
		File f = new File(realimg);
		
		if (f.exists()) {
			nullAvatar=HttpUtil.repairUrl(request.getContextPath()+"/"+avatarNone);
		}
		
		if (uid == null) {
			uid = 0L;
			return nullAvatar;
		}
		User user = userDaoImpl.findByID(uid);
		if (user.getAvatarUrl()!=null && !user.getAvatarUrl().equals("")) {
			return user.getAvatarUrl();
		}else {
			return nullAvatar;
		}
	}
	
	
	/*
	 * 用户面板
	 */
	@ResponseBody
	@RequestMapping(value = "/panel/{aid}")
	@Token(ajax = true,csrf=true)
	public UserPanelCodeArgs panel(@PathVariable(value = "aid", required = true) Long aid, HttpServletRequest request, HttpServletResponse response,
			@CookieValue(value = "username_lerx", required = false) String username_lerx,
			@CookieValue(value = "password_lerx", required = false) String password_lerx,
			@RequestParam(value = "currEl", required = false) String currEl) {
		UserPanelCodeArgs upca=new UserPanelCodeArgs();
		upca.setStatus(0);
		if (aid == null) {
			aid = 0L;
		}
		Album album=albumDaoImpl.findByID(aid);
		Albgenre albgenre=album.getGenre();
		long gid=albgenre.getId();
		EnvirSet es = envirInit(gid, aid, request, response);
		TempletAlbumMain template = album.getTemplet();
		
		
		if (template == null) {
			template = templetAlbumMainDaoImpl.findDef();
		}
		long uid = UserUtil.loginRefresh(es, username_lerx, password_lerx);
		TempletSubElement el = TempletAlbumUtil.elInitByTagStr(template, currEl);
		String panelCode;
		String genrePanelCodeIn,genrePanelCodeOut;
		TempletAlbgenreMain gtemplate = albgenre.getTemplet();
		if (gtemplate==null) {
			gtemplate=templetAlbgenreMainDaoImpl.findDef();
		}
		
		if (gtemplate==null) {
			genrePanelCodeIn="";
			genrePanelCodeOut="";
		}else {
			TempletSubElement gel = TempletAlbgenreUtil.elInitByTagStr(gtemplate, currEl);
			genrePanelCodeIn=gel.getUserPanelCodeLogin();
			genrePanelCodeOut=gel.getUserPanelCodeLogout();
			
		}
		
		if (uid > 0L) {
			panelCode = el.getUserPanelCodeLogin();
			if (panelCode==null || panelCode.trim().equals("")) {
				panelCode=genrePanelCodeIn;
			}
			User user = userDaoImpl.findByID(uid);
			if (user != null) {
				String imgHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, template, "htmlTemplet_img");
				panelCode = UserUtil.fmt(panelCode, user, imgHtmlTemplet);
				upca.setStatus(1);
				upca.setUid(user.getId());
				upca.setUsername(user.getUsername());
			}
			String myAlbums;
			
			List<Album> la=albumDaoImpl.findByLeaderID(uid, gid, 0);
			if (la.isEmpty()) {
				myAlbums="";
			}else {
				String myAlbumLoop = TempletAlbumUtil.sundriesTag(messageSource, template, "template_myalbum_loop");
				String tmp,tmpAll="";
				for (Album alb:la) {
					tmp=myAlbumLoop;
					tmp = AnalyzeUtil.replace(tmp, "tag", "id", ""+alb.getId());
					tmp = AnalyzeUtil.replace(tmp, "tag", "name", alb.getName());
					tmpAll += tmp;
				}
				myAlbums=tmpAll;
			}
			
			panelCode = AnalyzeUtil.replace(panelCode, "tag", "aid", ""+aid);
			
			panelCode = AnalyzeUtil.replace(panelCode, "tag", "myAlbums", myAlbums);

		} else {
			panelCode = el.getUserPanelCodeLogout();
			if (panelCode==null || panelCode.trim().equals("")) {
				panelCode=genrePanelCodeOut;
			}
			String token = TokenUtil.buildToken();
			if (panelCode == null) {
				panelCode = "";
			}
			panelCode = AnalyzeUtil.replace(panelCode, "tag", "token", token);
		}
		
		panelCode = TempletUtil.tagToEnvir(panelCode, es);
		panelCode = TempletAlbumUtil.tagForResFolder(messageSource, panelCode, template);
		panelCode = AnalyzeUtil.replace(panelCode, "tag", "gid", ""+gid);
		panelCode = AnalyzeUtil.replace(panelCode, "tag", "albid", ""+aid);
		
		upca.setHtml(panelCode);
		return upca;
	}
	
	/*
	 * 首页
	 */
	@ResponseBody
	@RequestMapping(value = { "/index/{id}/{page}/{pagesize}", "/index/{id}" })
	public String index(@PathVariable(value = "id", required = false) Long id,HttpServletRequest request,@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(value = "pagesize", required = false) Integer pagesize) {
		if (id == null) {
			id = 0L;
		}
		if (page == null) {
			page = 0;
		}

		if (pagesize == null) {
			pagesize = 10;
		}
		
		Album album=albumDaoImpl.findByID(id);
		String html;
		EnvirSet es = envirInit(id, 0, request, null);
		es.setPage(page);
		es.setPageSize(pagesize);
		if (album==null  || album.isDeled() || !album.isStatus()) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null) {
			templet=templetAlbumMainDaoImpl.findDef();
		}
		if (templet==null) {
			return ErrorUtil.occur(messageSource, es, "err.null.templet", "The album does not specify a template to use!");
		}
		
		if (!album.isStatus() || !album.getGenre().isStatus()) {
			html = TempletUtil.tagToEnvir(FileUtil.readRes(messageSource, "template_res404"), es);
			html = TempletAlbumUtil.tagForResFolder(messageSource, html, templet);
			return html;
		}
		album.setTemplet(templet);
		GlobalTagsAnalyzeReturn gtar = HttpShowUtil.albumGlobalTagsAnalyze(album,es, "index");
		html = gtar.getHtml();
		es = gtar.getEs();
		if (es == null) {
			return html;
		}
		if (album.getHtmlOwn() != null && !album.getHtmlOwn().trim().equals("")) {
			html = AnalyzeUtil.replace(html, "code", "htmlOwn", album.getHtmlOwn());
		} else {
			html = AnalyzeUtil.replace(html, "code", "htmlOwn", "");
		}
		html=TempletAlbumUtil.htmlStyleByCustom(html, album);
		html = TempletUtil.tagToEnvir(html, es);
		html = TempletAlbumUtil.tagForResFolder(messageSource, html, templet);
		html = AnalyzeUtil.replace(html, "tag", "station", album.getName());
		long totalArts=albumArticleDaoImpl.countByAlbumID(album.getId());
		html = AnalyzeUtil.replace(html, "tag", "totalArts", ""+totalArts);
		html = AnalyzeUtil.replace(html, "tag", "mappCurr",
				es.getRequest().getContextPath() + "/show_album/index/" + id);
//		html = AnalyzeUtil.replace(html, "tag", "gname", album.getGenre().getName());
		html = AnalyzeUtil.replace(html, "tag", "gurl", AlbgenreUtil.getHref(messageSource, request, album.getGenre(), false));
		return html;
	}
	
	
	/*
	 * 分类
	 */
	@ResponseBody
	@RequestMapping(value = { "/classify/{id}/{aid}/{page}/{pagesize}", "/classify/{id}{aid}" })
	public String classify(@PathVariable(value = "id", required = false) Long id,@PathVariable(value = "aid", required = false) Long aid,HttpServletRequest request,@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(value = "pagesize", required = false) Integer pagesize) {
		if (id==null) {
			id=0L;
		}
		if (aid==null) {
			aid=0L;
		}
		if (page==null) {
			page=1;
		}
		if (pagesize==null) {
			pagesize=10;
		}
		
		EnvirSet es = envirInit(id, 0, request, null);
		
		AlbumArticleClassify aac=albumArticleClassifyDaoImpl.findByID(id);
		if (aac==null) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		
		
		return null;
	}
	
	
	/*
	 * 文章页
	 */
	@ResponseBody
	@RequestMapping(value = "/art/{id}")
	public String art(@PathVariable(value = "id", required = false) Long id,HttpServletRequest request,HttpSession session) {
		if (id == null) {
			id = 0L;
		}
		
		
		EnvirSet es = envirInit(id, 0, request, null);
		
		AlbumArticle art=albumArticleDaoImpl.findByID(id);
		if (art==null) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		Album album=art.getAlbum();
		
		if (album==null  || album.isDeled() || !album.isStatus()) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		es.setGid(album.getId());
		String html;
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		boolean admin = LoginUtil.adminChk(messageSource, session);
		if (!admin) {
			
			if (UserUtil.isadmin(user)) {
				admin=true;
			}
		}
		if (!admin) {
			if (AlbgenreUtil.adminChk(user, art.getAlbum().getGenre(), albgenreMangerDaoImpl)) {
				admin=true;
			}
		}
		
		if (!art.isStatus() || art.isProhibit()) {
			if (!admin) {
				return ErrorUtil.occur(messageSource, es, "fail.prohibit", "Article does not exist or has been deleted!");
			}
		}
		
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null) {
			templet=templetAlbumMainDaoImpl.findDef();
		}
		if (templet==null) {
			return ErrorUtil.occur(messageSource, es, "err.null.templet", "The album does not specify a template to use!");
		}
		if (!album.isStatus() || !album.getGenre().isStatus()) {
			html = TempletUtil.tagToEnvir(FileUtil.readRes(messageSource, "template_res404"), es);
			html = TempletAlbumUtil.tagForResFolder(messageSource, html, templet);
			return html;
		}
		album.setTemplet(templet);
		GlobalTagsAnalyzeReturn gtar = HttpShowUtil.albumArtGlobalTagsAnalyze(art,es, "art");
		es = gtar.getEs();
		
		html = gtar.getHtml();
		String mediaUrl=art.getContent().getMediaUrl();
		if (mediaUrl != null && !mediaUrl.trim().equals("")
				&& mediaUrl.trim().length() > 3) {
			String videoHtmlTemplet = TempletAlbumUtil.sundriesTag(messageSource, templetAlbumMainDaoImpl.findDef(),
					"template_video");

			videoHtmlTemplet = AnalyzeUtil.replace(videoHtmlTemplet, "tag", "media", mediaUrl.trim());

			html = AnalyzeUtil.replace(html, "code", "mediaPlayer", videoHtmlTemplet);

		} else {
			html = AnalyzeUtil.replace(html, "code", "mediaPlayer", "");
		}
		html = AnalyzeUtil.replace(html, "tag", "station", album.getName());
		html=TempletAlbumUtil.htmlStyleByCustom(html, album);
		html = TempletUtil.tagToEnvir(html, es);
		html = TempletAlbumUtil.tagForResFolder(messageSource, html, templet);
		html = AnalyzeUtil.replace(html, "tag", "gurl", AlbgenreUtil.getHref(messageSource, request, album.getGenre(), false));
		if (es == null) {
			return html;
		}
		return html;
	}
	
	
	/*
	 * 流分页文章列表
	 */
	@ResponseBody
	@Token(ajax = true,csrf=true)
	@RequestMapping(value = {"/arts/{aid}/{formatSource}/{fid}/{img}/{firstResult}/{titleLen}/{txtLen}/{page}/{pagesize}","/arts/{aid}/{formatSource}/{fid}/{page}/{pagesize}"})
	public FlowOut artpage(@PathVariable(value = "formatSource", required = false) String formatSource,@PathVariable(value = "fid", required = false) Integer fid,@PathVariable(value = "aid", required = false) Long aid,@PathVariable(value = "img", required = false) Integer img,@PathVariable(value = "firstResult", required = false) Integer firstResult,@PathVariable(value = "page", required = false) Integer page,@PathVariable(value = "pagesize", required = false) Integer pagesize,@PathVariable(value = "titleLen", required = false) Integer titleLen,@PathVariable(value = "txtLen", required = false) Integer txtLen,HttpServletRequest request,HttpServletResponse response) {
		
		FlowOut co = new FlowOut();
		co.setCount(0);
		co.setPage(1);
		co.setPageCount(0);
		co.setHtml("");
		co.setPageSize(pagesize);
		
		Album album=albumDaoImpl.findByID(aid);
		
		if (album==null  || album.isDeled() || !album.isStatus()) {
			return co;
		}
		TempletAlbumMain templet=album.getTemplet();
		if (templet==null) {
			templet=templetAlbumMainDaoImpl.findDef();
		}
		if (templet==null) {
			return co;
		}
		
		if (firstResult==null) {
			firstResult=0;
		}
		
		if (titleLen==null) {
			titleLen=0;
		}
		
		if (img==null) {
			img=0;
		}
		
		if (txtLen==null) {
			txtLen=Integer.valueOf(messageSource.getMessage("synopsis.length.upper", null, "200", null));
		}
		
		FindedDataAnalyzeResult fdar = new FindedDataAnalyzeResult();
		DataShowParams dsp=new DataShowParams ();
		dsp.setAlbid(aid);
		
		dsp.setFid(fid);
		dsp.setFormatSource(formatSource);
		dsp.setFirstResult(firstResult);
		dsp.setCurpage(page);
		dsp.setPagesize(pagesize);
		dsp.setImg(img);
		fdar.setDsp(dsp);
		TempletSubElement el=templet.getElIndex();
		fdar = TempletAlbumUtil.lfSetup(fdar, templet, el, false);
		dsp=fdar.getDsp();
//		int statusMark=1;
//		long currUid = LoginUtil.uid(messageSource, request);
//		if (album.getLeader().getId() - currUid == 0) {
//			statusMark=0;
//		}
//		
		String imgHtmlTemplet=TempletAlbumUtil.sundriesTag(templet, "htmlTemplet_img");
		Rs rs = albumArticleDaoImpl.queryByAid(aid,1,1,0,0,dsp.getFirstResult(), page,pagesize, false,img,dsp.getSoul(),dsp.getOrderby(),ConfigUtil.wvov(messageSource));
		String lf=dsp.getLoopFormatStr();
		lf = StringUtil.clear65279(lf);
		@SuppressWarnings("unchecked")
		List<AlbumArticle> lart=(List<AlbumArticle>) rs.getList();
		EnvParms ep = HttpUtil.epInit(request, response, null, messageSource);
		AppEnvParms aep=TempletUtil.init(ep, templet.getResFolder(), 2);
		String tmpAll="";
		/*System.out.println("lart.size():"+lart.size());
		System.out.println("aid:"+aid);
		System.out.println("dsp.getFirstResult():"+dsp.getFirstResult());
		System.out.println("page:"+page);
		System.out.println("pagesize:"+pagesize);
		System.out.println("img:"+img);
		System.out.println("dsp.getSoul():"+dsp.getSoul());*/
		for (AlbumArticle article :lart) {
			String tmp=lf;
			tmp=AlbumArticleUtil.fmt(aep, tmp, article, imgHtmlTemplet, titleLen, txtLen, 1, true);
			tmpAll+=tmp;
		}
		co.setHtml(tmpAll);
		co.setCount(rs.getCount());
		co.setPage(rs.getPage());
		co.setPageCount(rs.getPageCount());
//		System.out.println(co);
		return co;
	}

}
