package com.lerx.handlers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lerx.annotation.Token;
import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.IAlbumFansDao;
import com.lerx.dao.iface.IAlbumPartnerDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Album;
import com.lerx.entities.AlbumFans;
import com.lerx.entities.User;
import com.lerx.hql.entities.Rs;
import com.lerx.login.util.LoginUtil;
import com.lerx.v6.util.PartnerUtil;

@RequestMapping("/action_fans")
@Controller
public class AlbumFansHandler {

	@Autowired
	private ResourceBundleMessageSource messageSource;

	@Autowired
	private IUserDao userDaoImpl;

	@Autowired
	private IAlbumDao albumDaoImpl;

	@Autowired
	private IAlbumArticleDao albumArticleDaoImpl;

	@Autowired
	private IAlbumFansDao albumFansDaoImpl;

	@Autowired
	private IAlbumPartnerDao albumPartnerDaoImpl;
	
	private static final String LOGINPAGE = "jsp/user/login";
	private static final String FORBIDU = "jsp/result/forbidu";

	@ResponseBody
	@RequestMapping(value = "/followon/{aid}")
	@Token(ajax = true,csrf=true,contrast = true, log = true, mark = "album-fans--<add>", login = true, failedPage = LOGINPAGE)
	public int followon(@PathVariable(value = "aid", required = true) Long aid, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -201;
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null) {
			return -404;
		}
		if (album.isDeled() || !album.isStatus()) {
			return 400;
		}
		if (albumFansDaoImpl.findByUidAndAid(uid, aid) == null) {
			AlbumFans fans = new AlbumFans();
			fans.setCreateTime(System.currentTimeMillis());
			fans.setUser(user);
			fans.setTagAlb(album);
			fans.setLastVisitTime(System.currentTimeMillis());
			albumFansDaoImpl.add(fans);
			return 0;
		} else {
			return -502;
		}

	}

	@ResponseBody
	@RequestMapping(value = "/followout/{aid}")
	@Token(ajax = true,csrf=true,contrast = true, log = true, mark = "album-fans--<del>", login = true, failedPage = LOGINPAGE)
	public int followout(@PathVariable(value = "aid", required = true) Long aid, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -201;
		}
		AlbumFans fans = albumFansDaoImpl.findByUidAndAid(uid, aid);
		if (fans.getUser().getId() == uid) {
			albumFansDaoImpl.delByID(fans.getId());
			return 0;
		} else {
			return -200;
		}

	}

	@ResponseBody
	@RequestMapping(value = "/del/{id}")
	@Token(ajax = true,csrf=true,contrast = true, log = true, mark = "album-fans--<del>", login = true, failedPage = LOGINPAGE)
	public int del(@PathVariable(value = "id", required = true) Long id, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -201;
		}

		AlbumFans fans = albumFansDaoImpl.findByID(id);
		if (fans.getUser().getId() == uid) {
			albumFansDaoImpl.delByID(id);
			return 0;
		} else {
			return -200;
		}

	}

	@ResponseBody
	@RequestMapping(value = "/query/{aid}")
	@Token(ajax = true,csrf=true, login = true, failedPage = LOGINPAGE)
	public int query(@PathVariable(value = "aid", required = true) Long aid, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -1;
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null) {
			return -1;
		}
		if (album.isDeled() || !album.isStatus()) {
			return -400;
		}
		
		if (album.getLeader().getId() == uid) {
			return -1;
		}
		if (albumFansDaoImpl.findByUidAndAid(uid, aid) == null) {
			return 1;

		} else {
			return -502;
		}
	}

	@RequestMapping(value = { "/list/{aid}", "/list/{aid}/{page}/{pagesize}" })
	@Token(ajax = false,csrf=true, login = true, failedPage = FORBIDU)
	public String list(@PathVariable(value = "aid", required = true) Long aid,
			@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(value = "pagesize", required = false) Integer pagesize, HttpServletRequest request,
			Map<String, Object> map) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return "jsp/result/error";
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null) {
			return "jsp/result/error";
		}
		if (album.isDeled() || !album.isStatus()) {
			return FORBIDU;
		}
		

		if (!PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
//			System.out.println("HttpUtil.curUrl(request):"+HttpUtil.curUrl(request));
			return FORBIDU;
		}

		if (page == null) {
			page = 1;
		}
		if (pagesize == null) {
			pagesize = 10;
		}

		Rs rs = albumFansDaoImpl.queryByAid(aid, 0, page, pagesize);
		map.put("pageUrl", "action_fans/list/" + aid);
		map.put("rs", rs);
		map.put("aid", aid);
		return "jsp/album/control/fans";

	}

	@RequestMapping(value = { "/idols/{aid}", "/idols/{aid}/{page}/{pagesize}" })
	@Token(ajax = false,csrf=true, login = true, failedPage = FORBIDU)
	public String idols(@PathVariable(value = "aid", required = true) Long aid,
			@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(value = "pagesize", required = false) Integer pagesize, HttpServletRequest request,
			Map<String, Object> map) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return "jsp/result/error";
		}
		Album album = albumDaoImpl.findByID(aid);
		if (album == null) {
			return "jsp/result/error";
		}
		
		if (album.isDeled() || !album.isStatus()) {
			return FORBIDU;
		}

		if (!PartnerUtil.basicPowerChk(uid, album, albumPartnerDaoImpl)) {
			return FORBIDU;
		}

		if (page == null) {
			page = 1;
		}
		if (pagesize == null) {
			pagesize = 10;
		}

		Rs rs = albumFansDaoImpl.queryByUid(uid, 0, page, pagesize);
		map.put("pageUrl", "action_fans/idols/" + aid);
		map.put("rs", rs);
		map.put("aid", aid);
		return "jsp/album/control/idols";

	}
	
	/*
	 * 同步更新
	 * 当浏览某专辑时，将更新该专辑的最新文章ID至粉线的最后浏览文章ID 
	 */
	@ResponseBody
	@RequestMapping(value = "/synchronous/{aid}")
	@Token(ajax = true,csrf=true, login = true, failedPage = LOGINPAGE)
	public int synchronous(@PathVariable(value = "aid", required = true) Long aid, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -201;
		}
		Album album=albumDaoImpl.findByID(aid);
		if (album==null) {
			return -404;
		}
		if (album.isDeled() || !album.isStatus()) {
			return -400;
		}
		AlbumFans fans=albumFansDaoImpl.findByUidAndAid(uid, aid);
		if (fans==null) {
			return -302;
		}
		long maxArtID=albumArticleDaoImpl.findMaxArtID(aid);
		fans.setLastViewedID(maxArtID);
		albumFansDaoImpl.modify(fans);
		return 0;
	}

	/*
	 * 检查fans的所有专注的转辑是否有更新
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUpdates/{sta}")
	@Token(ajax = true,csrf=true, login = true, failedPage = LOGINPAGE)
	public int checkUpdates(@PathVariable(value = "sta", required = false) Integer sta, HttpServletRequest request) {
		long uid = LoginUtil.uid(messageSource, request);
		User user = userDaoImpl.findByID(uid);
		if (user == null) {
			return -201; //未登录
		}
		List<AlbumFans> list = albumFansDaoImpl.findByUid(uid);
		int rn = 0;
		boolean forcon = true;
		for (AlbumFans fans : list) {
			long newids = albumArticleDaoImpl.countAfterArticleID(fans.getLastViewedID());
			
			switch (sta) {
			case 1:			//每个关注的更新，只有更新+1，最终返回的是有多少个有更新的专辑
				if (newids>0) {
					rn++;
				}
				break;
			case 2:
				if (newids>0) {		//每个关心的更新的文章数，最终返回的是所有更新的专辑更新的文章总数
					rn += newids;
				}
				break;
			default:		//默认，只要有更新就退出，返回1
				if (newids>0) {
					forcon=false;
					rn=1;
				}

			}
			if (!forcon) {
				break;
			}
		}
		
		return rn;

	}

}
