package com.lerx.handlers;

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.annotation.Token;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.IAlbumExternalLinkDao;
import com.lerx.dao.iface.ICommentBridgeDao;
import com.lerx.dao.iface.ICommentThreadDao;
import com.lerx.dao.iface.IAlbgenreDao;
import com.lerx.dao.iface.IAlbumArticleClassifyDao;
import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.dao.iface.IHtmlFileStaticDao;
import com.lerx.dao.iface.IPollDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IRoleDao;
import com.lerx.dao.iface.ITempletAlbgenreMainDao;
import com.lerx.dao.iface.ITempletPortalMainDao;
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.AlbumArticleClassify;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.CommentThread;
import com.lerx.entities.Poll;
import com.lerx.entities.Portal;
import com.lerx.entities.Albgenre;
import com.lerx.entities.TempletAlbgenreMain;
import com.lerx.entities.TempletComment;
import com.lerx.entities.TempletPortalMain;
import com.lerx.entities.TempletSubElement;
import com.lerx.entities.User;
import com.lerx.hql.entities.Rs;
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.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.AlbumUtil;
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.TempletAlbgenreUtil;
import com.lerx.v6.util.TempletPortalUtil;
import com.lerx.v6.util.TempletUtil;
import com.lerx.v6.util.UserUtil;

@RequestMapping("/show_albgenre")
@Controller
public class HttpShowAlbgenreHandler {
	
	
	@Autowired
	private ResourceBundleMessageSource messageSource;
	
	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IAlbgenreDao albgenreDaoImpl;
	
	@Autowired
	private IAlbumArticleDao albumArticleDaoImpl;
	
	@Autowired
	private IAlbumDao albumDaoImpl;
	
	@Autowired
	private IAlbumArticleClassifyDao albumArticleClassifyDaoImpl;
	
	@Autowired
	private IAlbumExternalLinkDao albumExternalLinkDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	@Autowired
	private IRoleDao roleDaoImpl;
	
	@Autowired
	private ITempletAlbgenreMainDao templetAlbgenreMainDaoImpl;
	
	@Autowired
	private ITempletPortalMainDao templetPortalMainDaoImpl;
	
	@Autowired
	private IVisitorIPRecordDao visitorIPRecordDaoImpl;

	@Autowired
	private IVisitorsBookDao visitorsBookDaoImpl;

	@Autowired
	private IVisitArchivesDao visitArchivesDaoImpl;

	@Autowired
	private IVisitorCountInPeriodDao visitorCountInPeriodDaoImpl;

	@Autowired
	private IHtmlFileStaticDao htmlFileStaticDaoImpl;
	
	@Autowired
	private IPollDao pollDaoImpl;
	
	@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.setUserDaoImpl(userDaoImpl);
		es.setRoleDaoImpl(roleDaoImpl);
		es.setVisitorIPRecordDaoImpl(visitorIPRecordDaoImpl);
		es.setVisitorsBookDaoImpl(visitorsBookDaoImpl);
		es.setVisitArchivesDaoImpl(visitArchivesDaoImpl);
		es.setVisitorCountInPeriodDaoImpl(visitorCountInPeriodDaoImpl);
		es.setHtmlFileStaticDaoImpl(htmlFileStaticDaoImpl);

		return es;
	}
	
	/*
	 * 用户面板
	 */
	@ResponseBody
	@RequestMapping("/panel")
	@Token(ajax = true,csrf=true)
	public UserPanelCodeArgs panel(Long gid, 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 (gid == null) {
			gid = 0L;
		}
		EnvirSet es = envirInit(gid, 0, request, response);
		Albgenre ag=albgenreDaoImpl.findByID(gid);
		TempletAlbgenreMain template;
		if (ag!=null) {
			template = ag.getTemplet();
		}else
			template = null;
		
		if (template == null) {
			template = templetAlbgenreMainDaoImpl.findDef();
		}
		long uid = UserUtil.loginRefresh(es, username_lerx, password_lerx);
		TempletSubElement el = TempletAlbgenreUtil.elInitByTagStr(template, currEl);
		String panelCode;
		if (uid > 0L) {
			panelCode = el.getUserPanelCodeLogin();
			User user = userDaoImpl.findByID(uid);
			if (user != null) {
				String imgHtmlTemplet = TempletAlbgenreUtil.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 = TempletAlbgenreUtil.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());
					String href=AlbumUtil.getHref(messageSource, request, alb, false);
					tmp = AnalyzeUtil.replace(tmp, "tag", "href", href);
					tmpAll += tmp;
				}
				myAlbums=tmpAll;
			}
			
			panelCode = AnalyzeUtil.replace(panelCode, "tag", "myAlbums", myAlbums);

		} else {
			panelCode = el.getUserPanelCodeLogout();
			String token = TokenUtil.buildToken();
			if (panelCode == null) {
				panelCode = "";
			}
			panelCode = AnalyzeUtil.replace(panelCode, "tag", "token", token);
		}
		
		panelCode = TempletUtil.tagToEnvir(panelCode, es);
		panelCode = TempletAlbgenreUtil.tagForResFolder(messageSource, panelCode, template);
		panelCode = AnalyzeUtil.replace(panelCode, "tag", "gid", ""+gid);
		upca.setHtml(panelCode);
		return upca;
	}
	
	/*
	 * 首页
	 */
	@ResponseBody
	@RequestMapping(value = "/index/{id}")
	public String index(@PathVariable(value = "id", required = false) Long id,HttpServletRequest request) {
		if (id == null) {
			id = 0L;
		}
		
		EnvirSet es = envirInit(id, 0, request, null);
		Albgenre albgenre = albgenreDaoImpl.findByID(id);
		if (albgenre==null) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		String html;
		
		
		TempletAlbgenreMain templet=albgenre.getTemplet();
		if (templet==null) {
			templet=templetAlbgenreMainDaoImpl.findDef();
		}
		if (templet==null) {
			return ErrorUtil.occur(messageSource, es, "err.null.templet", "The album does not specify a template to use!");
		}
		
		if (!albgenre.isStatus()) {
			html = TempletUtil.tagToEnvir(FileUtil.readRes(messageSource, "template_res404"), es);
			html = TempletAlbgenreUtil.tagForResFolder(messageSource, html, templet);
			return html;
		}
		albgenre.setTemplet(templet);
		GlobalTagsAnalyzeReturn gtar = HttpShowUtil.albgenreGlobalTagsAnalyze(albgenre,es, "index");
		es = gtar.getEs();
		es.setGid(id);
		
		html = gtar.getHtml();
		html = TempletUtil.tagToEnvir(html, es);
		html = TempletAlbgenreUtil.tagForResFolder(messageSource, html, es.getTempletAlbgenreMainDaoImpl().findDef());
		html = AnalyzeUtil.replace(html, "tag", "gid", ""+id);
		return html;
	}
	
	
	/*
	 * 分类
	 */
	@ResponseBody
	@RequestMapping(value = { "/classify/{id}/{page}/{pagesize}", "/classify/{id}" })
	public String classify(@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=1;
		}
		if (pagesize==null) {
			pagesize=10;
		}
		
		EnvirSet es = envirInit(id, 0, request, null);
		es.setPage(page);
		es.setPageSize(pagesize);
		AlbumArticleClassify aac = albumArticleClassifyDaoImpl.findByID(id);
		if (aac==null) {
			return ErrorUtil.occur(messageSource, es, "error.args", "Parameter error!");
		}
		es.setGid(aac.getGenre().getId());
		es.setAacid(aac.getId());
		String html;
		
		Albgenre albgenre=aac.getGenre();
		TempletAlbgenreMain templet=albgenre.getTemplet();
		if (templet==null) {
			templet=templetAlbgenreMainDaoImpl.findDef();
		}
		if (templet==null) {
			return ErrorUtil.occur(messageSource, es, "err.null.templet", "The album does not specify a template to use!");
		}
		
		albgenre.setTemplet(templet);
		GlobalTagsAnalyzeReturn gtar = HttpShowUtil.albgenreGlobalTagsAnalyze(albgenre,es, "nav");
		es = gtar.getEs();
		es.setGid(id);
		
		html = gtar.getHtml();
		html = TempletUtil.tagToEnvir(html, es);
		html = TempletAlbgenreUtil.tagForResFolder(messageSource, html, es.getTempletAlbgenreMainDaoImpl().findDef());
		html = AnalyzeUtil.replace(html, "tag", "gid", ""+id);
		
		html = AnalyzeUtil.replace(html, "tag", "cname", aac.getName());
		
		html = AnalyzeUtil.replace(html, "tag", "mappCurr",
				es.getRequest().getContextPath() + "/show_albgenre/classify/" + id);
		return html;
		
	}
	
	
	/*
	 * 调查投票区域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) {
		if (titleLen == null) {
			titleLen = 0;
		}
		if (overMark == null) {
			overMark=1;
		}
		TempletPortalMain template = templetPortalMainDaoImpl.findDef();
		String html = TempletPortalUtil.sundriesTag(messageSource, template, "htmlTemplet_poll");

		html = TempletUtil.tagToEnvir(html, request,messageSource);
		Poll poll=pollDaoImpl.findByID(id);
		html = AnalyzeUtil.replace(html, "tag", "pollID", "" + poll.getId());
		html = AnalyzeUtil.replace(html, "tag", "poll_id", "" + poll.getId());
		html = AnalyzeUtil.replace(html, "tag", "poll_agrees", "" + poll.getAgrees());
		html = AnalyzeUtil.replace(html, "tag", "poll_antis", "" + poll.getAntis());
		html = AnalyzeUtil.replace(html, "tag", "poll_passbys", "" + poll.getPassbys());
		html = AnalyzeUtil.replace(html, "tag", "pollAgrees", "" + poll.getAgrees());
		html = AnalyzeUtil.replace(html, "tag", "pollAntis", "" + poll.getAntis());
		html = AnalyzeUtil.replace(html, "tag", "pollPassbys", "" + poll.getPassbys());

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

	@ResponseBody
	@RequestMapping(value = "/commform/{bid}")
	@Token(ajax = true,csrf=true)
	public String commForm(@PathVariable(value = "bid", required = true) Long bid,
			@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 (bid == null) {
			return "";
		}

		CommentBridge cb = commentBridgeDaoImpl.findByID(bid);

		if (!cb.isStatus()) {
			return "";
		}

		TempletPortalMain template = templetPortalMainDaoImpl.findDef();
		TempletComment templatec = template.getElComment();
		String html = templatec.getFormCode();

		html = AnalyzeUtil.replace(html, "tag", "bid", "" + cb.getId());
		html = TempletUtil.tagToEnvir(html, request,messageSource);
		html = TempletPortalUtil.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 = "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;
		}

		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);
		TempletPortalMain template = templetPortalMainDaoImpl.findDef();
		TempletComment templatec = template.getElComment();
		String lf =templatec.getItemLoopCode();
		if (lf==null || lf.trim().equals("")) {
			lf = TempletPortalUtil.sundriesTag(messageSource, template, "htmlTemplet_comm_loop");
		}
		String tmp, tmpAll = "";
		String imgHtmlTemplet = TempletPortalUtil.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 = TempletPortalUtil.sundriesTag(messageSource, template, "anonymity");
		String headDef = TempletPortalUtil.sundriesTag(messageSource, template, "headDef");
		DatetimeSpanSuffixTxt dsst = TempletPortalUtil.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;

	}
	

}
