package com.lerx.handlers;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lerx.annotation.Token;
import com.lerx.dao.iface.IAlbgenreDao;
import com.lerx.dao.iface.IAlbgenreMangerDao;
import com.lerx.dao.iface.IAlbumArticleClassifyDao;
import com.lerx.dao.iface.IAlbumDao;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IRoleDao;
import com.lerx.dao.iface.ITempletAlbgenreMainDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Albgenre;
import com.lerx.entities.AlbgenreManger;
import com.lerx.entities.Portal;
import com.lerx.entities.Role;
import com.lerx.entities.TempletAlbgenreMain;
import com.lerx.entities.User;
import com.lerx.hql.entities.Rs;
import com.lerx.login.util.LoginUtil;
import com.lerx.portal.obj.LayuiTransferData;
import com.lerx.portal.obj.ReturnCodeAtAlbumCheck;
import com.lerx.portal.obj.TempletSimple;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.MavUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.v6.util.AlbgenreUtil;
import com.lerx.v6.util.TempletAlbgenreUtil;

import net.sf.json.JSONArray;


@RequestMapping("/action_albgenre")
@Controller
public class AlbgenreHandler {

	private static final String SUCCESS = "jsp/result/success";
	private static final String FAILED = "jsp/result/failed";
	private static final String ADMINFAILRETURN = "_admin.login.redirect_";

	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IAlbgenreDao albgenreDaoImpl;
	
	@Autowired
	private IAlbumDao albumDaoImpl;
	
	@Autowired
	private IRoleDao roleDaoImpl;
	
	
	@Autowired
	private IAlbumArticleClassifyDao albumArticleClassifyDaoImpl;
	
	@Autowired
	private IAlbgenreMangerDao albgenreMangerDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	@Autowired
	private ITempletAlbgenreMainDao templetalbgenreMainDaoImpl;
	
	@Autowired
	private ResourceBundleMessageSource messageSource;

	@ModelAttribute
	public void getalbgenre(@RequestParam(value = "id", required = false) Long id, Map<String, Object> map) {
		if (id != null && id > 0) {
			map.put("albgenre", albgenreDaoImpl.findByID(id));
		}
	}
	
	@RequestMapping("/beforeAdd")
	public ModelAndView beforeAdd(HttpServletRequest request, Map<String, Object> map) {
		List<TempletSimple> list=TempletAlbgenreUtil.queryAllSimple(templetalbgenreMainDaoImpl);
		map.put("templets", list);
		Albgenre albgenre = new Albgenre();
		map.put("albgenre", albgenre);
		return MavUtil.mav1("jsp/album/genre/add", "");
	}

	@RequestMapping("/add")
	@Token(ajax = false,csrf=true,contrast = true, log = true, mark = "album_genre--<add>", admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public String add(@Valid Albgenre albgenre, Errors result, Map<String, Object> map, HttpServletRequest request,
			HttpSession session) {
		if (albgenre.getId() == 0) {
			albgenre.setComm(true);
			albgenre.setStatus(true);
			albgenre.setPoll(true);
			albgenre.setCreateTime(System.currentTimeMillis());
			albgenre.setOpen(true);
			albgenre.setFree(true);
			albgenre.setRelease(true);
			
			TempletAlbgenreMain templet=templetalbgenreMainDaoImpl.findDef();
			albgenre.setTemplet(templet);
			if (albgenreDaoImpl.add(albgenre) == null) {
				return FAILED;
			} else {
				return SUCCESS;
			}
		} else {
			if (albgenre.isOpen()) {
				albgenre.setAllowedGidStr(null);
			}
			albgenreDaoImpl.modify(albgenre);
			return SUCCESS;
		}
	}

	// 进入修改页面
	@RequestMapping("/edit")
	@Token(ajax = false,csrf=true, admin = true, failedPage = FAILED, msgKey = "fail.nologin",failedReturnUrl = ADMINFAILRETURN)
	public ModelAndView edit(Map<String, Object> map, HttpSession session, Long id) {

		Albgenre albgenre = albgenreDaoImpl.findByID(id);
		map.put("albgenre", albgenre);
		
		List<TempletSimple> list=TempletAlbgenreUtil.queryAllSimple(templetalbgenreMainDaoImpl);
		map.put("templets", list);
		return MavUtil.mav1("jsp/album/genre/add", "");

	}

	@ResponseBody
	@RequestMapping("/del")
	@Token(ajax = false,csrf=true,contrast = true, log = true, mark = "album_genre--<delete>", admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public int del(Long id, HttpSession session) {
		boolean result = false;
		result = albgenreDaoImpl.delByID(id);
		if (result) {
			return 0;
		} else {
			return -500;
		}

	}

	@RequestMapping(value = { "/list/{page}/{pagesize}", "/list" })
	@Token(ajax = false, admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public ModelAndView list(@PathVariable(value = "page", required = false) Integer page,
			@PathVariable(value = "pagesize", required = false) Integer pagesize, HttpServletRequest request, HttpSession session,
			Map<String, Object> map) {
		if (page == null) {
			page = 1;
		}
		if (pagesize == null) {
			pagesize = 10;
		}
		Rs rs = albgenreDaoImpl.query(page, pagesize, 0, 0);
		@SuppressWarnings("unchecked")
		List<Albgenre> list=(List<Albgenre>) rs.getList();
//		List<Albgenre> list2 = new ArrayList<Albgenre>();
		for (Albgenre genre:list) {
			genre.setUrl(AlbgenreUtil.getHref(messageSource, request, genre, false));
			genre.setAacs(albumArticleClassifyDaoImpl.findByGID(genre.getId()).size());
			genre.setCountAllowedGid(countUnitForListStr(genre.getAllowedGidStr()));
			genre.setTotalAlbums(albumDaoImpl.countByUidAndGid(0, genre.getId()));
//			list2.add(genre);
			
		}
//		rs.setList(list2);
		map.put("pageUrl", "/action_albgenre/list");
		map.put("rs", rs);

		return MavUtil.mav1("jsp/album/genre/list", "");

	}
	
	@ResponseBody
	@RequestMapping(value = "/agree/{gid}")
	public String agree(@PathVariable(value = "gid", required = true) Long gid, HttpSession session) {
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		if (ag==null) {
			return "Error:-404";
		}
		String agreeTxt=ag.getAgreement();
		if (agreeTxt==null ||agreeTxt.trim().equals("")) {
			agreeTxt=FileUtil.readLargeFile4(FileUtil.repairFilePath(FileUtil.appPath()+File.separator+"album_agreement.txt"), null, System.getProperty("file.encoding"));
		}
		if (agreeTxt==null ||agreeTxt.trim().equals("")) {
			agreeTxt=FileUtil.readLargeFile4(FileUtil.repairFilePath(FileUtil.appPath()+File.separator+"agreement.txt"), null, System.getProperty("file.encoding"));
		}
		if (agreeTxt==null) {
			return "Null:-410";
		} else if (agreeTxt.trim().equals("")) {
			return "Null:-302";
		}else {
			agreeTxt = StringUtil.strReplace(agreeTxt, "${genrename}", ag.getName());
			return agreeTxt.trim();
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/addManger/{gid}/{uid}")
	@Token(ajax = true,csrf=true,contrast = true, admin = true, failedPage = FAILED,log=true, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public int addManger(@PathVariable(value = "gid", required = true) Long gid,@PathVariable(value = "uid", required = true) Long uid, HttpSession session) {
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		if (ag==null) {
			return -404;
		}
		User user=userDaoImpl.findByID(uid);
		if (user==null) {
			return -405;
		}
		if (albgenreMangerDaoImpl.findByUID(gid, uid)!=null) {
			return -502;
		}
		AlbgenreManger manger=new AlbgenreManger();
		manger.setAlbgenre(ag);
		manger.setUser(user);
		albgenreMangerDaoImpl.add(manger);
		return 0;

	}
	
	
	@ResponseBody
	@RequestMapping(value = "/delManger/{id}")
	@Token(ajax = true,csrf=true,contrast = true, admin = true, failedPage = FAILED,log=true, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public int delManger(@PathVariable(value = "id", required = true) Long id, HttpSession session) {
		albgenreMangerDaoImpl.delByID(id);
		return 0;
	}
	
	@RequestMapping("/mangerList/{id}")
	@Token(ajax = false,csrf=true, admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public String mangerList(@PathVariable(value = "id", required = true) Long id,HttpSession session,
			Map<String, Object> map) {
		List<AlbgenreManger> list=albgenreMangerDaoImpl.queryByAlbgenrID(id);
		map.put("list", list);
		map.put("gid", id);
		return "jsp/album/genre/manger";

	}
	
	@RequestMapping("/release/{gid}")
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true)
	public int release(@PathVariable(value = "gid", required = true) Long gid,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;
		}
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		if (!ag.isRelease()) {
			return -1;
		}
		return 1;
		
	}
	
	@RequestMapping("/selectroles/{gid}")
	@Token(ajax = false,csrf=true,contrast = true, log = true, mark = "album_genre--<add>", admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public String selectroles(@PathVariable(value = "gid", required = true) Long gid,HttpServletRequest request, Map<String, Object> map) {
		
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		
		List<Role> allRoles=roleDaoImpl.queryAll();
		List<LayuiTransferData> roles=new ArrayList<LayuiTransferData>();
		String currSelects="";
		String gstr=ag.getAllowedGidStr();
		if (gstr!=null && !gstr.trim().equals("")) {
			gstr+=",";
		}else {
			gstr="";
		}
		
		for (Role role:allRoles) {
			LayuiTransferData  ltd= new LayuiTransferData();
			ltd.setValue(""+role.getId());
			ltd.setChecked("");
			ltd.setDisabled("");
			ltd.setTitle(role.getName());
			roles.add(ltd);
			
			if (gstr.indexOf(role.getId()+",")!= -1) {
				currSelects+="'"+ltd.getValue()+"',";
			}
			
		}
		
		JSONArray jsonroles = JSONArray.fromObject(roles);
		
		if (currSelects!=null && currSelects.endsWith(",")) {
			currSelects=currSelects.substring(0, currSelects.length()-1);
			currSelects="["+currSelects+"]";
		}else {
			currSelects="[]";
		}
		
		map.put("rolesLeft", jsonroles.toString());
		map.put("currSelects", currSelects);
		map.put("gid", gid);
		return "jsp/album/genre/selectRoles";
		
	}
	
	
	@RequestMapping("/saveroles/{gid}")
	@ResponseBody
	@Token(ajax = false,csrf=true,contrast = true, log = true, mark = "album_genre--<add>", admin = true, failedPage = FAILED, msgKey = "fail.permission",failedReturnUrl = ADMINFAILRETURN)
	public int saveroles(@PathVariable(value = "gid", required = true) Long gid,String roleids,HttpServletRequest request) {
		Albgenre ag = albgenreDaoImpl.findByID(gid);
		
		if (roleids!=null && roleids.endsWith(",")) {
			roleids=roleids.substring(0, roleids.length()-1);
		}
		ag.setAllowedGidStr(roleids);
		albgenreDaoImpl.modify(ag);
		return 0;
		
	}
	
	private int countUnitForListStr(String str) {
		if (str==null || str.trim().equals("")) {
			return 0;
		}
		String[] array = str.trim().split(",");
		String tmp;
		int r=0;
		for (int i = 0; i < array.length; i++) {
			
			tmp = array[i];
			if (tmp!=null && !tmp.trim().equals("")) {
				r++;
			}
		}
		return r;
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/powerchk/{gid}")
	@Token(ajax = true, csrf = true,contrast = true)
	public ReturnCodeAtAlbumCheck powerchk(@PathVariable(value = "gid", required = true) Long gid,
			HttpServletRequest request) {
		ReturnCodeAtAlbumCheck rcaac = new ReturnCodeAtAlbumCheck();
		long uid = LoginUtil.uid(messageSource, request);
		User user=userDaoImpl.findByID(uid);
		Albgenre genre = albgenreDaoImpl.findByID(gid);
		if (user==null || genre==null) {
			rcaac.setStatusCurr(-404);
			rcaac.setStatusNew(-1);
			return rcaac;
		}
		if (genre.getQuota() == 0) {
			rcaac.setStatusNew(0);
		} else {
			long count = albumDaoImpl.countByUidAndGid(uid, gid); // 在本类已有专辑数
			if (count >= genre.getQuota()) {
				rcaac.setStatusNew(-1);
			} else {
				rcaac.setStatusNew(0);
			}
		}
		return rcaac;
		
	}
	
	

}
