package com.lerx.handlers;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

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.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.CrossOrigin;
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.analyze.util.AnalyzeUtil;
import com.lerx.annotation.Token;
import com.lerx.app.util.SafeStrUtil;
import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.ICommentBridgeDao;
import com.lerx.dao.iface.ICommentThreadDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IRoleDao;
import com.lerx.dao.iface.IUploadedFileDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Album;
import com.lerx.entities.AlbumArticle;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.CommentThread;
import com.lerx.entities.Poll;
import com.lerx.entities.Portal;
import com.lerx.entities.User;
import com.lerx.ip.util.IPUtil;
import com.lerx.log.util.LogWrite;
import com.lerx.mail.obj.Mail;
import com.lerx.mail.obj.Message;
import com.lerx.mail.obj.SmtpSrv;
import com.lerx.mail.util.MailUtil;
import com.lerx.portal.obj.ReciveUserModular;
import com.lerx.portal.obj.SimpleReciveCommentThread;
import com.lerx.portal.obj.SimpleReciveUser;
import com.lerx.portal.obj.UploadArgs;
import com.lerx.sys.obj.Website;
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.PortalUtil;
import com.lerx.v6.util.ReciveUtil;
import com.lerx.v6.util.UserUtil;

@RequestMapping("/action_comm")
@Controller
public class CommentHandler {
	
	@Autowired
	private ResourceBundleMessageSource messageSource;
	
	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IUploadedFileDao uploadedFileDaoImpl;
	
	@Autowired
	private ICommentThreadDao commentThreadDaoImpl;
	
	@Autowired
	private ICommentBridgeDao commentBridgeDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	@Autowired
	private IRoleDao roleDaoImpl;
	
	@Autowired
	private IAlbumDao albumDaoImpl;

	@Autowired
	private IAlbumArticleDao albumArticleDaoImpl;
	
	private static final String SUCCESS = "jsp/result/success";
	private static final String FAILED = "jsp/result/failed";
	
	
	@Value("${mail.server.host}")
	private String srvhost;
	
	@Value("${mail.server.login.user}")
	private String mailuser;
	
	@Value("${mail.server.login.password}")
	private String mailpwd;
	
	@Value("${mail.server.sender}")
	private String mailsender;
	
	@Value("${mail.server.auth}")
	private String mailauth;
	
	@Value("${mail.charset}")
	private String mailcharset;
	
	@Value("${mail.server.config.success:false}")
	private String mailSrvConfigSuccess;
	
	
	@ResponseBody
	@RequestMapping(value = "/pass/{id}")
	@Token(ajax = true,csrf=true,contrast = true, log = true, mark = "comment--<pass>")
	public int pass(@PathVariable(value = "id", required = true) Long id,@CookieValue(value="uid_lerx",required=false) String uid_lerx) {
		CommentThread ct = commentThreadDaoImpl.findByID(id);
		if (ct==null) {
			return -400;
		}
		User user = null;
		CommentBridge cb=ct.getCb();
		
		if (cb==null) {
			return -400;
		}
		
		
		if (uid_lerx!=null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid=Long.valueOf(uid_lerx);
			user=userDaoImpl.findByID(uid);
		}
		
		if (user==null) {
			return -201;
		}
		
		if (cb.getUser().getId() - user.getId() == 0) {
			ct.setStatus(true);
			cb.setTotal(cb.getTotal()+1);
			commentBridgeDaoImpl.modify(cb);
			commentThreadDaoImpl.modify(ct);
			
			if (cb.getParent()!=null) {
				cb.getParent().setTotal(cb.getParent().getTotal()+1);
				commentBridgeDaoImpl.modify(cb.getParent());
			}
			
			return 0;
		}else {
			return -200;
		}
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/del/{id}")
	@Token(ajax = true, csrf=true,contrast = true,log = true, mark = "comment--<del>")
	public int del(@PathVariable(value = "id", required = true) Long id,@CookieValue(value="uid_lerx",required=false) String uid_lerx,HttpServletRequest request) {
		CommentThread ct = commentThreadDaoImpl.findByID(id);
		if (ct==null) {
			return -400;
		}
		User user = null;
		CommentBridge cb=ct.getCb();
		
		if (cb==null) {
			return -400;
		}
		
		
		if (uid_lerx!=null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid=Long.valueOf(uid_lerx);
			user=userDaoImpl.findByID(uid);
		}
		
		if (user==null) {
			return -201;
		}
		
		if (cb.getUser().getId() - user.getId() == 0 || UserUtil.isadmin(user)) {
			ct.setDeleted(true);
			long total=cb.getTotal();
			total --;
			if (total<0L) {
				total=0;
			}
			cb.setTotal(total);
			commentBridgeDaoImpl.modify(cb);
			
			commentThreadDaoImpl.modify(ct);
			
			if (cb.getParent()!=null) {
				long ptotal=cb.getParent().getTotal()-1;
				if (ptotal<0) {
					ptotal=0;
				}
				cb.getParent().setTotal(ptotal);
				commentBridgeDaoImpl.modify(cb.getParent());
			}
			
			//发送信
			SmtpSrv srv = new SmtpSrv();
			srv.setHost(srvhost);
			srv.setUser(mailuser);
			srv.setPassword(mailpwd);
			srv.setSender(mailsender);
			if (mailauth!=null && mailauth.trim().equalsIgnoreCase("true")) {
				srv.setAuth(true);
			}else {
				srv.setAuth(false);
			}
			
			Message mes=new Message();
			mes.setCharset(mailcharset);
			String recipients="";
			recipients += ct.getUser().getEmail()+";";
			Portal portal = portalDaoImpl.query_update();
			Website site = PortalUtil.lead(portal);
			
			mes.setRecipient(recipients);
			
			String subject = messageSource.getMessage("mail.subject.title.comment", null,
					"You have a new comment in {$tag:portalName$}.", null);
			subject = AnalyzeUtil.replace(subject, "tag", "portalName", portal.getName());
			mes.setSubject(subject);
			String mailbody = FileUtil.readRes(messageSource, "template_prohibit_albart");
			mailbody=HttpUtil.siteImplant(mailbody, site, request);
			
			mailbody=HttpUtil.siteImplant(mailbody, site, request);
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "portalName", portal.getName());
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "username", ct.getUser().getUsername());
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "subject", ct.getContent());
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "portalUrl", portal.getUrl());
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "datetime", TimeUtil.coverLongToStr(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
			mailbody = AnalyzeUtil.replace(mailbody, "tag", "albgenre", cb.getObjTitle());
			
			mes.setBody(mailbody);
			
			System.out.println("信mailbody:"+mailbody);
			Mail m = new Mail();
			m.setMessage(mes);
			m.setSmtpSrv(srv);
			m.setCharset(mailcharset);
			int r = MailUtil.send(m, messageSource,srv, true);
			if (r<0) {
				String msg="An error occurred during the mail delivery. Error code:"+r+".";
				System.out.println(msg);
				String lb= System.getProperty("line.separator");
				LogWrite.logWrite(HttpUtil.currRequest(), "info-proce-doAfterreturing "+lb+msg);
			}
			
			return 0;
		}else {
			return -200;
		}
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/env/{bid}")
	public int env(@PathVariable(value = "bid", required = true) Long bid,@CookieValue(value="uid_lerx",required=false) String uid_lerx) {
		Portal portal = portalDaoImpl.query_update();
		User user = null;
		CommentBridge cb=null;
		cb = commentBridgeDaoImpl.findByID(bid);
		if (cb==null) {
			return -400;
		}
		
		if (!cb.isStatus() || !portal.isComm()) {
			return -403;
		}
		
		if (uid_lerx!=null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			long uid=Long.valueOf(uid_lerx);
			user=userDaoImpl.findByID(uid);
		}
		
		if (!portal.isFreeComm() && user==null) {
			return -201;
		}
		return 0;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/inform/{bid}")
	public int inform(@PathVariable(value = "bid", required = true) Long bid) {
		Portal portal = portalDaoImpl.query_update();
		CommentBridge cb = commentBridgeDaoImpl.findByID(bid);
		boolean bc=portal.isCommBack();
		if (!bc) {
			return 0;
		}
		long aid=cb.getObjID();
		switch (cb.getObjType()) {
		
			case 0:
				
				break;
			case 1:
				if (aid>0L) {
					AlbumArticle art=albumArticleDaoImpl.findByID(aid);
					if (art!=null) {
						Album album=albumDaoImpl.findByID(art.getAlbum().getId());
						if (!album.isMesback()) {
							bc=false;
						}
					}
					
				}
				
				break;
			default:
		
		}
		if (bc) {
			return 1;
		}else {
			return 0;
		}
		
	}
	
	@RequestMapping("/add")
	@Token(ajax = false, log = true,contrast = true, mark = "comment--<add>", token = true,csrf=true, failedPage = FAILED, msgKey = "fail.universal")
	public ModelAndView add(HttpServletRequest request,HttpSession session,@CookieValue(value="uid_lerx",required=false) String uid_lerx,@RequestParam(value = "content", required = false) String content,@RequestParam(value = "bid", required = true) long bid,@RequestParam(value = "pid", required = false) Long pid,@RequestParam(value = "vcode", required = true) String vcode,@RequestParam(value = "inform", required = false) Integer inform, String token) {
		String msg="";
		if (pid==null) {
			pid=0L;
		}
		if (inform==null) {
			inform=0;
		}
		Portal portal = portalDaoImpl.query_update();
		if (!portal.isComm()) {
			
			return MavUtil.mav1(FAILED, messageSource.getMessage("fail.function.notopen", null, "The system does not open the function!", null));
		}
		String safeSessionStr = SafeStrUtil.getstr(messageSource, request, "comm");
		String vcodeSession = (String) session.getAttribute(safeSessionStr);
		if (((vcode == null) || (!(vcode.trim().equalsIgnoreCase(vcodeSession))))) {
			return MavUtil.mav1(FAILED, messageSource.getMessage("error.verify.code", null, "Please enter the correct verification code!", null));
		}
		if (content==null || content.trim().equals("")) {
			return MavUtil.mav1(SUCCESS, messageSource.getMessage("fail.content.empty", null, "The content can't be empty!", null));
		}
		content=StringUtil.htmlFilter(content);
		CommentBridge cb=null;
		if (bid>0L) {
			cb = commentBridgeDaoImpl.findByID(bid);
		}else {
			return MavUtil.mav1(SUCCESS, messageSource.getMessage("error.args", null, "Parameter error!", null));
		}
		if (cb==null) {
			return MavUtil.mav1(SUCCESS, messageSource.getMessage("error.args", null, "Parameter error!", null));
		}
		CommentThread parent=null;
		if (pid>0L) {
			parent=	commentThreadDaoImpl.findByID(pid);
		}
		
		CommentThread ct = new CommentThread();
		ct.setCb(cb);
		ct.setContent(content);
		ct.setOccurDatetime(System.currentTimeMillis());
		String ip = IPUtil.getRealRemotIP(request);
		ct.setIp(ip);
		Poll poll=new Poll();
		if (portal.isPoll()) {
			poll.setStatus(true);
		}
		ct.setPoll(poll);
		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);
			ct.setUser(user);
		}
		if (user!=null && (user.isGag() || user.getRole().isGag())) {
			return MavUtil.mav1(FAILED, messageSource.getMessage("fail.gag", null, "You may be banned from speaking!", null));
		}
		if (!portal.isFreeComm() && user==null) {
			return MavUtil.mav1(FAILED, messageSource.getMessage("fail.nologin", null, "Sorry, you need to log in to finish this operation.", null));
		}
		if (portal.isCommPassAuto()) {
			ct.setStatus(true);
			cb.setTotal(cb.getTotal()+1);
			commentBridgeDaoImpl.modify(cb);
			
			if (cb.getParent()!=null) {
				cb.getParent().setTotal(cb.getParent().getTotal()+1);
				commentBridgeDaoImpl.modify(cb.getParent());
			}
		}
		ct.setParent(parent);
		commentThreadDaoImpl.add(ct);
		boolean own=false;
		if (inform==1) {
			Set<User> suser=new HashSet<User>();
			if (user!=null && (user.getId() - cb.getUser().getId()==0)) {
				own=true;
			}
			if (user==null || (!own && UserUtil.mailUsable(cb.getUser())!=null)) {
				suser.add(cb.getUser());
			}
			String userteam=cb.getObjTeam().getUidstr();
			if (userteam!=null && !userteam.trim().equals("")) {
				String[] users = userteam.split(",");
				for (int i = 0; i < users.length; i++) {
					if (users[i]!=null && !users[i].trim().equals("") && StringUtil.isNumber(users[i])){
						User u=userDaoImpl.findByID(Long.valueOf(users[i]));
						if (u!=null){
							suser.add(u);
						}
					}
					
				}
			}
			
			own=false;
			if (user!=null && ct.getParent()!=null && ct.getParent().getUser()!=null && (user.getId() - ct.getParent().getUser().getId()==0)) {
				own=true;
			}
			if (user==null || (!own && ct.getParent()!=null && ct.getParent().getUser()!=null && UserUtil.mailUsable(ct.getParent().getUser())!=null)) {
				suser.add(ct.getParent().getUser());
			}
			
			if (suser.size()>0 && mailSrvConfigSuccess.trim().equalsIgnoreCase("true") ) {
				SmtpSrv srv = new SmtpSrv();
				
				srv.setHost(srvhost);
				srv.setUser(mailuser);
				srv.setPassword(mailpwd);
				srv.setSender(mailsender);
				if (mailauth!=null && mailauth.trim().equalsIgnoreCase("true")) {
					srv.setAuth(true);
				}else {
					srv.setAuth(false);
				}
				
				Message mes=new Message();
				mes.setCharset(mailcharset);
				String recipients="";
				for (User u:suser) {
					recipients += u.getEmail()+";";
				}
				
				mes.setRecipient(recipients);
				
				String subject = messageSource.getMessage("mail.subject.title.comment", null,
						"You have a new comment in {$tag:portalName$}.", null);
				subject = AnalyzeUtil.replace(subject, "tag", "portalName", portal.getName());
				mes.setSubject(subject);
				String comsay = FileUtil.readRes(messageSource, "template_comment_mail");
				if (user!=null) {
					comsay = AnalyzeUtil.replace(comsay, "tag", "username", user.getUsername());
				}else {
					comsay = AnalyzeUtil.replace(comsay, "tag", "username",  messageSource.getMessage("user.anonymous", null,
							"anonymous", null));
				}
				
				comsay = AnalyzeUtil.replace(comsay, "tag", "portalName", portal.getName());
				comsay = AnalyzeUtil.replace(comsay, "tag", "addtime", portal.getName());
				
//				String dtfmt = messageSource.getMessage("datetime.fmt.default", null, "yyyy-MM-dd HH:mm:ss", null);
				
				comsay = AnalyzeUtil.replace(comsay, "tag", "addTime", ct.getOccurDatetime());
				comsay = AnalyzeUtil.replace(comsay, "tag", "url", HttpUtil.repairUrl(HttpUtil.getSrvUrl(request, true)+"/"+cb.getHosturl()));
				comsay = AnalyzeUtil.replace(comsay, "tag", "content", ct.getContent());
				String commType;
				if (ct.getParent()==null) {
					commType=messageSource.getMessage("comment", null,
							"comment", null);
				}else {
					commType=messageSource.getMessage("reply", null,
							"reply", null);
				}
				
				comsay = AnalyzeUtil.replace(comsay, "tag", "comntype", commType);
				
				Website site = PortalUtil.lead(portal);
				comsay=HttpUtil.siteImplant(comsay, site, request);
				mes.setBody(comsay);
				Mail m = new Mail();
				m.setMessage(mes);
				m.setSmtpSrv(srv);
				m.setCharset(mailcharset);
				int r = MailUtil.send(m, messageSource,srv, true);
				if (r<0) {
					msg="An error occurred during the mail delivery. Error code:"+r+".";
				}
			}
			
			
		}
		
		return MavUtil.mav1(SUCCESS, msg);
	}
	
	
	//接收文章
		@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);

			SimpleReciveCommentThread sct = (SimpleReciveCommentThread) ObjUtil.objectXmlDecoder(f.toString()).get(0);
			String webinf=FileUtil.webinfPath()+File.separator;
			
			if (sct==null || sct.getHostUuid()==null || sct.getHostUuid().trim().equals("")) {
				ReciveUtil.logw(webinf, "recive.log", "-416   获得文章   文件：" + pathfilename);
				return -416;
			}
			String securityStr = SecurityUtil.readWords("recivekey");
			if (securityStr==null || securityStr.trim().equals("")) {
				ReciveUtil.logw(webinf, "recive.log", "-403  获得评论 内容："+sct.getContent());
				return -403;
			}
			
			if (sct.getExtrakey()==null || !sct.getExtrakey().trim().equals(securityStr)) {
				ReciveUtil.logw(webinf, "recive.log", "-401  获得评论 内容："+sct.getContent());
				return -401;
			}
			
			User user;
			SimpleReciveUser suser = sct.getUser();
			boolean nobody=false;
			if (suser==null) {
				nobody=true;
			}
			if (!nobody) {
				user = userDaoImpl.findByUuid(suser.getUuid());
				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);
				
				if (suser!=null && suser.getUuid()!=null && !suser.getUuid().trim().equals("") &&  user==null) {
					ReciveUserModular rum =UserUtil.reviceUser(suser, userDaoImpl, roleDaoImpl, ua, request, response);
					user = rum.getUser();
					ua=rum.getUa();
					
				/*
				 * 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=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);
				 */
					
				}
				if (user!=null) {
					ua.setUid(user.getId());
				}
				
			}else {
				user=null;
			}
			
			CommentThread ct= commentThreadDaoImpl.findByUuid(sct.getUuid());
			if (ct==null) {
				ct = new CommentThread();
				ct.setContent(sct.getContent());
				ct.setDeleted(sct.isDeleted());
				ct.setStatus(sct.isStatus());
				ct.setOccurDatetime(sct.getOccurDatetime());
				ct.setUser(user);
				ct.setUuid(sct.getUuid());
				if (sct.getParentUuid()!=null && !sct.getParentUuid().trim().equals("")) {
					CommentThread parent=commentThreadDaoImpl.findByUuid(sct.getParentUuid());
					ct.setParent(parent);
				}
				AlbumArticle art =	albumArticleDaoImpl.findByUuid(sct.getHostUuid());
				if (art!=null) {
					ct.setCb(art.getCb());
					Poll poll=new Poll();
					poll.setStatus(true);
					ct.setPoll(poll);
					commentThreadDaoImpl.add(ct);
					art.getCb().setTotal(art.getCb().getTotal()+1);
					if (art.getCb().getParent()!=null) {
						art.getCb().getParent().setTotal(art.getCb().getParent().getTotal()+1);
					}
					
					commentBridgeDaoImpl.modify(art.getCb());
					ReciveUtil.logw(webinf, "recive.log", "0000  获得评论 内容："+sct.getContent());
					f.delete();
					return 0;
				}else {
					ReciveUtil.logw(webinf, "recive.log", "-502  获得评论 内容："+sct.getContent());
					return -502;
				}
				
			}else {
				ReciveUtil.logw(webinf, "recive.log", "-502  获得评论 内容："+sct.getContent());
				return -502;
			}
			
		}

}
