package com.lerx.handlers;

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

import javax.servlet.http.HttpServletRequest;
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.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.servlet.ModelAndView;

import com.lerx.annotation.Token;
import com.lerx.aop.args.CutTags;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.IAlbgenreDao;
import com.lerx.dao.iface.IAlbgenreMangerDao;
import com.lerx.dao.iface.IAlbumPartnerDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.ITempletAlbumMainDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Album;
import com.lerx.entities.CommentBridge;
import com.lerx.entities.Albgenre;
import com.lerx.entities.Poll;
import com.lerx.entities.Portal;
import com.lerx.entities.Role;
import com.lerx.entities.Team;
import com.lerx.entities.TempletAlbumMain;
import com.lerx.entities.User;
import com.lerx.entities.VisitorsBook;
import com.lerx.hql.entities.Rs;
import com.lerx.login.util.LoginUtil;
import com.lerx.portal.obj.ReturnCodeAtAlbumCheck;
import com.lerx.portal.obj.SimpleAlbum;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.MavUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.v6.util.AlbgenreUtil;
import com.lerx.v6.util.AlbumUtil;
import com.lerx.v6.util.ConfigUtil;
import com.lerx.v6.util.PartnerUtil;

@RequestMapping("/action_album")
@Controller
public class AlbumHandler {

	private static final String ALBUMEDIT = "jsp/album/control/add";
	private static final String ALBUMLIST = "jsp/album/list";
	private static final String FORBIDU = "jsp/result/forbidu";
	private static final String LOGINPAGE = "jsp/user/login";
	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 IAlbgenreDao albgenreDaoImpl;

	@Autowired
	private IAlbumDao albumDaoImpl;

	@Autowired
	private IAlbumPartnerDao albumPartnerDaoImpl;

	@Autowired
	private ITempletAlbumMainDao templetAlbumMainDaoImpl;

	@Autowired
	private IAlbgenreMangerDao albgenreMangerDaoImpl;

	@Autowired
	private IUserDao userDaoImpl;

	@Autowired
	private ResourceBundleMessageSource messageSource;

	@ModelAttribute
	public void getAlbum(@RequestParam(value = "id", required = false) Long id, Map<String, Object> map) {
		if (id != null && id > 0) {
			map.put("album", albumDaoImpl.findByID(id));
		}
	}

	@RequestMapping("/modify")
	@Token(ajax = false, log = true, mark = "album--<modify>", login = true,contrast = true, failedPage = FORBIDU)
	public String modify(Album album, Errors result, HttpServletRequest request, HttpSession session,
			Map<String, Object> map, CutTags tags) {
		if (album.getId() <= 0) {
			map.put("error", messageSource.getMessage("error.args", null, "error.args", null));
			return "jsp/result/error";
		} else {
			long uid = LoginUtil.uid(messageSource, request);

			if (album.getLeader().getId() == uid) {
				album = AlbumUtil.validate(messageSource, album);
				albumDaoImpl.modify(album);
				AlbumUtil.htmlCreate(album, messageSource, contextPath,true);

				return "jsp/result/success";
			} else {
				return FORBIDU;
			}

		}

		// mapCreate(map,groupDaoImpl,group);

	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@Token(ajax = false, login = true, failedPage = FORBIDU)
	public String edit(@PathVariable("id") Long id, HttpServletRequest request, Map<String, Object> map) {
		Album album = albumDaoImpl.findByID(id);
		if (album==null  || album.isDeled() || !album.isStatus()) {
			return FORBIDU;
		}
		long uid = LoginUtil.uid(messageSource, request);
		if (PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			map.put("album", album);
			User leader = album.getLeader();

			map.put("mailchk", StringUtil.positionStatus(leader.getContactsVerifyed(), 1));
			map.put("namelock", album.getGenre().isLockAlbName());
			
			return ALBUMEDIT;
		} else {
			return FORBIDU;
		}

	}

	@RequestMapping(value = { "/list/{gid}/{page}/{pagesize}", "/list/{gid}", "/list" })
	@Token(ajax = false, admin = true, failedPage = FAILED,msgKey="fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public String list(@PathVariable(value = "gid", required = false) Long gid,
			@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(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;
		}
		Albgenre albgenre;
		if (gid > 0L) {
			albgenre = albgenreDaoImpl.findByID(gid);
		} else {
			albgenre = null;

		}

		if (albgenre == null) {
			gid = 0L;
		}

		map.put("gid", gid);

		Rs rs = albumDaoImpl.query(gid, page, pagesize, 0, 0, 0, 0);
		@SuppressWarnings("unchecked")
		List<Album> list = (List<Album>) rs.getList();
		for (Album album : list) {
			album.setUrl(AlbumUtil.getHref(messageSource, request, album, false));
		}
		map.put("rs", rs);
		map.put("pageUrl", "/action_album/list/" + gid);
		map.put("rootUrl", "/action_album/list");

		return ALBUMLIST;
	}

	/*
	 * 申请
	 */
	@ResponseBody
	@RequestMapping("/apply")
	@Token(ajax = true,csrf = true,contrast = true)
	public int apply(String name, long gid, @CookieValue(value = "uid_lerx", required = false) String uid_lerx,
			HttpServletRequest request, HttpSession session) {
		if (name != null) {
			name = name.trim();
			name = ConfigUtil.strFilter(messageSource, name);

			if (name.trim().equals("")) {
				return -410;
			}
			if (name.indexOf("*") > -1) {
				return -418;
			}
		} else {
			return -410;
		}
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		if (ag == null) {
			return -400;
		}
		Album album = albumDaoImpl.findByName(name);
		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);

			Role role = null;
			if (user != null) {
				role = user.getRole();
			} else {
				return -201;
			}

			String mask = "";
			if (role != null) {
				mask = role.getMask();
			}
			/*
			 * if (mask.equals("0")) { return 0; }
			 */
			mask = "," + mask + ",";
			if (!mask.equals(",0,") && mask.indexOf(",b0,") < 0 && mask.indexOf(",b" + gid + ",") < 0) {
				return -200;
			}
			String allowedGidStr=ag.getAllowedGidStr();
			if (allowedGidStr!=null && !allowedGidStr.trim().equals("")) {
				allowedGidStr+=",";
				if (user.getRole()==null) {
					return -200;
				}else {
					if (allowedGidStr.indexOf(user.getRole().getId()+",") == -1) {
						return -200;
					}
				}
				
			}
		} else {
			return -201;
		}
		if (album == null) {
			album = new Album();
			
			

			if (!ag.isStatus() || !ag.isFree()) {
				return -403;
			}

			/*
			 * 查查该用户是否已经有记录
			 */
			long count = albumDaoImpl.countByUidAndGid(user.getId(), gid);
			if (ag.getQuota() > 0 && count >= ag.getQuota()) {
				return -413;
			}

			/*
			 * List<Album> la = albumDaoImpl.findByLeaderID(user.getId(), gid, 0); if
			 * (la!=null && !la.isEmpty() && la.size()>0) { if (la.size() >= ag.getQuota())
			 * { return -413; } }
			 */

			album.setGenre(ag);
			album.setName(name);
			album.setLeader(user);
			album.setStatus(true);
			album.setOpen(true);
			album.setComm(true);

			Poll poll = new Poll();
			poll.setStatus(true);
			album.setPoll(poll);
			
			CommentBridge cb = new CommentBridge();
			cb.setUser(user);
			cb.setStatus(true);
			cb.setObjTitle(album.getName());
			cb.setObjType(3);

			VisitorsBook vbook = new VisitorsBook();
			vbook.setObjType(3);
			vbook.setObjTitle(album.getName());
			
			Team team=new Team();
			cb.setObjTeam(team);
			album.setCb(cb);
			album.setVbook(vbook);
			album.setCreateTime(System.currentTimeMillis());
			album = albumDaoImpl.add(album);

			AlbumUtil.htmlCreate(album, messageSource, contextPath,true);

			if (album == null) {
				return -1;
			} else {
				return 0;
			}

		} else {
			return -410;
		}

	}

	@ResponseBody
	@RequestMapping("/findByName")
	public boolean agree(String name, HttpSession session) {
		Album album = albumDaoImpl.findByName(name);
		if (album == null) {
			return false;
		} else {
			return true;
		}
	}

	// 专辑管理后台
	@RequestMapping(value = "/control/{albid}")
	@Token(ajax = false, login = true,contrast = true, failedPage = FORBIDU)
	public ModelAndView control(@PathVariable(value = "albid", required = false) Long albid, HttpServletRequest request,
			HttpSession session, Map<String, Object> map) {
		if (albid == null) {
			return MavUtil.mav1("jsp/result/error", null);
		}
		Album album = albumDaoImpl.findByID(albid);
		if (!album.isStatus() || album.isDeled()) {
			return MavUtil.mav1("jsp/result/error", null);
		}
		long uid = LoginUtil.uid(messageSource, request);

		if (PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			map.put("album", album);
			map.put("albid", albid);
			map.put("startPage", AlbumUtil.getHref(messageSource, request, album, false));
			map.put("framePage", request.getContextPath()+"/action_album/control/"+albid);
			return MavUtil.mav1("jsp/album/control/frame", null);
		} else {
			map.put("referer", HttpUtil.curUrl(request));
			return MavUtil.mav1("jsp/user/login", null);
		}

	}

	// 个人美工
	@RequestMapping(value = "/cstyle/{albid}")
	@Token(ajax = false, login = true, failedPage = FORBIDU)
	public ModelAndView cstyle(@PathVariable(value = "albid", required = false) Long albid, HttpServletRequest request,
			HttpSession session, Map<String, Object> map) {
		if (albid == null) {
			return MavUtil.mav1("jsp/result/error", null);
		}
		Album album = albumDaoImpl.findByID(albid);
		if (!album.isStatus() || album.isDeled()) {
			return MavUtil.mav1("jsp/result/error", null);
		}
		long uid = LoginUtil.uid(messageSource, request);

		if (PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			map.put("album", album);
			map.put("albid", albid);
			map.put("startPage", AlbumUtil.getHref(messageSource, request, album, false));
			return MavUtil.mav1("jsp/album/control/cstyle", null);
		} else {
			map.put("referer", HttpUtil.curUrl(request));
			return MavUtil.mav1("jsp/user/login", null);
		}

	}
	
	@RequestMapping(value = "/cstyle/update")
	@Token(ajax = false, login = true,contrast = true, failedPage = FORBIDU)
	public ModelAndView cstyleUpdate(Album album, HttpServletRequest request,
			HttpSession session, Map<String, Object> map) {
		long albid=album.getId();
		if (albid == 0) {
			return MavUtil.mav1("jsp/result/error", null);
		}
//		Album alb = albumDaoImpl.findByID(albid);
		if (!album.isStatus() || album.isDeled()) {
			return MavUtil.mav1("jsp/result/error", null);
		}
		long uid = LoginUtil.uid(messageSource, request);

		if (PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			albumDaoImpl.modify(album);
			/*
			 * map.put("album", album); map.put("albid", albid); map.put("startPage",
			 * AlbumUtil.getHref(messageSource, request, album, false));
			 */
			return MavUtil.mav1("jsp/result/success", null);
		} else {
			map.put("referer", HttpUtil.curUrl(request));
			return MavUtil.mav1("jsp/user/login", null);
		}

	}

	/*
	 * 选择模板
	 */
	@ResponseBody
	@RequestMapping("/templet/{aid}/{tid}")
	@Token(ajax = true, csrf = true,contrast = true, login = true, failedPage = LOGINPAGE)
	public int apply(@PathVariable(value = "aid", required = true) Long aid,
			@PathVariable(value = "tid", required = true) Long tid,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session) {
		long uid = 0L;
		if (uid_lerx != null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			uid = Long.valueOf(uid_lerx);
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null  || !album.isStatus() || album.isDeled()) {
			return -400;
		}
		if (!PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			return -200;
		} else {
			TempletAlbumMain templetcurr = templetAlbumMainDaoImpl.findByID(tid);
			album.setTemplet(templetcurr);
			albumDaoImpl.modify(album);

			AlbumUtil.htmlCreate(album, messageSource, contextPath,true);

			return 0;
		}

	}

	@ResponseBody
	@RequestMapping(value = "/powerchk/{aid}")
	@Token(ajax = true, csrf = true,contrast = true)
	public ReturnCodeAtAlbumCheck powerchk(@PathVariable(value = "aid", required = true) Long aid,
			HttpServletRequest request) {
		ReturnCodeAtAlbumCheck rcaac = new ReturnCodeAtAlbumCheck();
		long uid = LoginUtil.uid(messageSource, request);
		Album album = albumDaoImpl.findByID(aid);
		if (album == null || !album.isStatus() || album.isDeled()) {
			rcaac.setStatusCurr(-404);
			return rcaac;
		}


		boolean manager=PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl);
		if (!manager) {
			rcaac.setStatusCurr(-200);
		} else {
			rcaac.setStatusCurr(0);
		}
		
		Albgenre genre = album.getGenre();
		if (genre.getQuota() == 0) {
			rcaac.setStatusNew(0);
		} else {
			long count = albumDaoImpl.countByUidAndGid(uid, genre.getId()); // 在本类已有专辑数
			if (count >= genre.getQuota()) {
				rcaac.setStatusNew(-1);
			} else {
				rcaac.setStatusNew(0);
			}
		}
		return rcaac;

	}

	@ResponseBody
	@RequestMapping(value = "rand/{gid}")
	@Token(ajax = true, csrf = true,contrast = true)
	public SimpleAlbum findByRand(@PathVariable(value = "gid", required = true) Long gid, HttpServletRequest request) {
		List<Album> list = albumDaoImpl.rand(gid, 1);
		if (list.size() > 0) {
			Album album = list.get(0);
			SimpleAlbum salb = AlbumUtil.cover(messageSource, request, album, false);
			if (salb.getAvatar() == null || salb.getAvatar().trim().equals("")) {
				String nullAvatar = ConfigUtil.getAvatarNullFile(messageSource, request);
				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);
				}
				salb.setAvatar(nullAvatar);
			}
			return salb;
		} else {
			return null;
		}
	}

	/*
	 * 修改状态
	 */
	@ResponseBody
	@RequestMapping(value = "/able/{aid}")
	@Token(ajax = true, csrf = true,contrast = true, loginOrAdmin = true, failedPage = LOGINPAGE)
	public int able(@PathVariable(value = "aid", required = true) Long aid,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session) {
		long uid = 0L;
		if (uid_lerx != null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			uid = Long.valueOf(uid_lerx);
		}
		User user = userDaoImpl.findByID(uid);
		Album album = albumDaoImpl.findByID(aid);
		if (album == null  || album.isDeled()) {
			return -400;
		}
		if (!AlbgenreUtil.adminChk(user, album.getGenre(), albgenreMangerDaoImpl)) {
			return -200;
		}
		album.setStatus(!album.isStatus());
		albumDaoImpl.modify(album);
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value = "/clear/logo/{aid}/{target}")
	@Token(ajax = true, csrf = true,contrast = true, loginOrAdmin = true, failedPage = LOGINPAGE)
	public int clearLogo(@PathVariable(value = "aid", required = true) Long aid,@PathVariable(value = "target", required = true) Integer target,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session) {
		long uid = 0L;
		if (uid_lerx != null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			uid = Long.valueOf(uid_lerx);
		}
		User user = userDaoImpl.findByID(uid);
		Album album = albumDaoImpl.findByID(aid);
		if (album == null  || album.isDeled() || !album.isStatus()) {
			return -400;
		}
		if (!AlbgenreUtil.adminChk(user, album.getGenre(), albgenreMangerDaoImpl)) {
			return -200;
		}
		if (target==0) {
			album.setLogo(null);
		}else {
			album.setBanner(null);
		}
		albumDaoImpl.modify(album);
		
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value = "/clear/style/{aid}")
	@Token(ajax = true, csrf = true,contrast = true, loginOrAdmin = true, failedPage = LOGINPAGE)
	public int clearStyle(@PathVariable(value = "aid", required = true) Long aid,
			@CookieValue(value = "uid_lerx", required = false) String uid_lerx, HttpServletRequest request,
			HttpSession session) {
		long uid = 0L;
		if (uid_lerx != null && !uid_lerx.trim().equals("") && StringUtil.isNumber(uid_lerx)) {
			uid = Long.valueOf(uid_lerx);
		}
		User user = userDaoImpl.findByID(uid);
		Album album = albumDaoImpl.findByID(aid);
		if (album == null  || album.isDeled() || !album.isStatus()) {
			return -400;
		}
		if (!AlbgenreUtil.adminChk(user, album.getGenre(), albgenreMangerDaoImpl)) {
			return -200;
		}
		album.setColor1(null);
		album.setColor2(null);
		album.setColor3(null);
		album.setCss(null);
		albumDaoImpl.modify(album);
		
		return 0;
	}
	
	@RequestMapping("/release/{aid}")
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true)
	public int release(@PathVariable(value = "aid", required = true) Long aid,HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user=userDaoImpl.findByID(uid);
		if (user.isGag() || user.getRole().isGag()) {
			return -1;
		}
		Portal portal = portalDaoImpl.query_update();
		if (!portal.isReleaseAlbum()) {
			return -1;
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null || album.getGenre()==null || album.isDeled() || !album.isStatus()) {
			return -1;
		}
		
		Albgenre ag = album.getGenre();
		if (!ag.isRelease()) {
			return -1;
		}
		return 1;
		
	}

}
