package com.iamberry.wechat.handles.news;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.stereotype.Controller;
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.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.autiXSS.XSSHandler;
import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.banner.ActionBannerImage;
import com.iamberry.wechat.core.entity.news.News;
import com.iamberry.wechat.face.banner.AdminBannerService;
import com.iamberry.wechat.face.news.NewsService;
import com.iamberry.wechat.tools.ValidatorUtil;
import com.iamberry.wechat.utils.StaticCacheMemory;

/**
 * @author 何秀刚
 * @description ： 新闻内容的后台、前台
 * @createDate : 2016年6月13日
 */
@Controller
public class AdminNewsHandler {
	
	@Autowired
	private NewsService newsService;

	@Autowired
	private AdminUtils adminUtils;

	@Autowired
	private ValidatorUtil validatorUtil;

	@Autowired
	private AdminBannerService adminBannerService;
	
	private MD5 md5 = new MD5("newsmd55");
	
	// --------------------------------------------   后台
	@RequestMapping("/admin/www/news/listUI")
	public ModelAndView listUI() {
		ModelAndView mv = new ModelAndView("admin/www/news/list");
		mv.addObject("news", newsService.listAll());
		return mv;
	}
	
	@RequestMapping("/admin/www/news/addUI")
	public ModelAndView addUI(HttpSession session) {
		ModelAndView mv = new ModelAndView("admin/www/news/add");
		mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", session));
		return mv;
	}

	@RequestMapping("/admin/www/news/add")
	public ModelAndView add(News news, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		ModelAndView mv = new ModelAndView("admin/www/news/list");
		
		String token = request.getParameter("addNewsToken");
		if (!adminUtils.checkToken(token, "addNewsToken", request.getSession())) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}

		if (!validatorUtil.validatorObject(news)) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}
		
		// 富文本XSS过滤
		news.setNewsContexts(StaticCacheMemory.XSS.antiXSS(news.getNewsContexts()));
		
		// 检查图片
		if (!news.getNewsImage().startsWith("http")) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}
		newsService.addNews(news);
		
		mv.addObject("news", newsService.listAll());
		return mv;
	}
	
	@RequestMapping("/admin/www/news/updateUI/{id}")
	public ModelAndView updateUI(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("admin/www/news/add");
		mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
		
		// XSS
		News obj = newsService.getOne(id);
		obj.setNewsAuthor(XSSHandler.handle(obj.getNewsAuthor(), true, false, false));
		obj.setNewsDesc(XSSHandler.handle(obj.getNewsDesc(), true, false, false));
		obj.setNewsSource(XSSHandler.handle(obj.getNewsSource(), true, false, false));
		obj.setNewsSourceUrl(XSSHandler.handle(obj.getNewsSourceUrl(), true, false, false));
		obj.setNewsTitle(XSSHandler.handle(obj.getNewsTitle(), true, false, false));
		obj.setNewsImage(XSSHandler.handle(obj.getNewsImage(), true, false, false));
		mv.addObject("obj", obj);
		return mv;
	}
	

	@RequestMapping("/admin/www/news/update")
	public ModelAndView update(News news, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		ModelAndView mv = new ModelAndView("admin/www/news/list");
		
		String token = request.getParameter("addNewsToken");
		if (!adminUtils.checkToken(token, "addNewsToken", request.getSession())) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}

		if (!validatorUtil.validatorObject(news)) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}
		
		// 富文本XSS过滤
		news.setNewsContexts(StaticCacheMemory.XSS.antiXSS(news.getNewsContexts()));
		
		// 检查图片
		if (!news.getNewsImage().startsWith("http")) {
			mv.addObject("token", adminUtils.saveTokenToSession("addNewsToken", request.getSession()));
			mv.setViewName("admin/www/news/add");
			return mv;
		}
		newsService.updateOne(news);
		
		mv.addObject("news", newsService.listAll());
		return mv;
	}
	
	// --------------------------------------------   前台
	@RequestMapping("/www/news/desc/{id}")
	@ResponseBody
	public Map<String, Object> desc(@PathVariable("id") String sn) {
		
		if (sn == null) return null;
		Integer id = 0;
		try {
			id = Integer.parseInt(md5.decrypt(sn));
		} catch (Exception e) {return null;}
		
		// XSS
		Map<String, Object> map = new HashMap<String, Object>();
		News obj = newsService.getOne(id);
		obj.setNewsAuthor(XSSHandler.handle(obj.getNewsAuthor(), true, false, false));
		obj.setNewsDesc(XSSHandler.handle(obj.getNewsDesc(), true, false, false));
		obj.setNewsSource(XSSHandler.handle(obj.getNewsSource(), true, false, false));
		obj.setNewsTitle(XSSHandler.handle(obj.getNewsTitle(), true, false, false));
		obj.setNewsImage(XSSHandler.handle(obj.getNewsImage(), true, false, false));
		obj.setNewsId(null);
		
		map.put("news", obj);
		map.put("sn", sn);
		
		return map;
	}
	
	@RequestMapping("/www/news/list")
	@ResponseBody
	public List<Map<String, Object>> list() throws Exception {
		
		List<Map<String, Object>> news = new ArrayList<Map<String,Object>>();
		
		List<News> list = newsService.listAll(true);
		for (News obj : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sn", md5.encrypt(obj.getNewsId().toString()));
			
			obj.setNewsContexts(null);
			obj.setNewsId(null);
			
			map.put("news", obj);
			news.add(map);
		}
		return news;
	}
	
	@RequestMapping("/www/news/access/{sn}")
	@ResponseBody
	public String access(
			@PathVariable("sn") String sn, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 每个IP每天可以贡献 5 个阅读数,连续 5 次打开文章，也没问题，阅读数增加，超过五次就不算了。过晚上12点后，打开文章又可以增加 5 个阅读数。
		
		try {
			newsService.updateAccess(Integer.parseInt(md5.decrypt(sn)));
			return "{'status':'true', 'statusMsg':'success'}";
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "{'status':'false', 'statusMsg':'error'}";
 	}

	@RequestMapping("/www/news/share/{sn}")
	@ResponseBody
	public String share(
			@PathVariable("sn") String sn, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 每个IP每天可以贡献 5 个阅读数,连续 5 次打开文章，也没问题，阅读数增加，超过五次就不算了。过晚上12点后，打开文章又可以增加 5 个阅读数。
		
		try {
			newsService.updateShare(Integer.parseInt(md5.decrypt(sn)));
			return "{'status':'true', 'statusMsg':'success'}";
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "{'status':'false', 'statusMsg':'error'}";
 	}
	
	@ResponseBody
	@RequestMapping("/www/news/{type}/{sn}")
	public Map<String, Object> next(
			@PathVariable("type") Integer type,
			@PathVariable("sn") String sn
			) {
		try {
			int id = Integer.parseInt(md5.decrypt(sn));
			Map<String, Object> map = new HashMap<String, Object>();
			if (type == 1) {
				// 下一篇
				id = id + 1;
			} else {
				// 上一篇
				id = id - 1;
			}
			News obj = newsService.getOne(id);
			
			if (obj == null) {
				map.put("news", "");
				map.put("sn", "");
				return map;
			}
			
			// XSS
			obj.setNewsAuthor(XSSHandler.handle(obj.getNewsAuthor(), true, false, false));
			obj.setNewsDesc(XSSHandler.handle(obj.getNewsDesc(), true, false, false));
			obj.setNewsSource(XSSHandler.handle(obj.getNewsSource(), true, false, false));
			obj.setNewsTitle(XSSHandler.handle(obj.getNewsTitle(), true, false, false));
			obj.setNewsImage(XSSHandler.handle(obj.getNewsImage(), true, false, false));
			obj.setNewsId(null);
			
			map.put("news", obj);
			map.put("sn", md5.encrypt(id+""));
			
			return map;
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return null;
	}
	
	@RequestMapping("/www/banner/list")
	@ResponseBody
	public List<ActionBannerImage> bannerList(@RequestParam("sn") Integer sn) {
		// sn生成规则，最后一位为字母，然后char 转 十进制，然后 % 运算
		List<ActionBannerImage> images = adminBannerService.selectBannerImgByBannerId(sn);
		return images;
	}
}
