package com.iamberry.wechat.handles.banner;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.banner.ActionBanner;
import com.iamberry.wechat.core.entity.banner.ActionBannerImage;
import com.iamberry.wechat.core.entity.banner.BannerDTO;
import com.iamberry.wechat.core.entity.banner.JSONDTO;
import com.iamberry.wechat.core.entity.banner.MessageDTO;
import com.iamberry.wechat.face.banner.AdminBannerService;
/**
 * @author 何秀刚
 * Class description: 后台Banner管理
 * Create Date:2016年4月18日
 * Update Date:2016年4月18日
 */
@RequestMapping("/admin/banner")
@Controller
public class AdminBannerHandler {
	
	@Autowired
	private AdminBannerService adminBannerService;
	public void setAdminBannerService(AdminBannerService adminBannerService) {
		this.adminBannerService = adminBannerService;
	}
	
	@Autowired
	private AdminUtils adminUtils;
	public void setAdminUtils(AdminUtils adminUtils) {
		this.adminUtils = adminUtils;
	}
	
	@RequestMapping("/listUI")
	public ModelAndView list(
			@RequestParam(value= "pageSize",defaultValue= "10" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
			HttpServletRequest request) throws UnsupportedEncodingException {
		ModelAndView mv = new ModelAndView("admin/banner/list");
		// 搜索
		List<ActionBanner> banners = adminBannerService.selectBannerListByPaper(null, pageSize, pageNO);
		mv.addObject("banners", banners);
		mv.addObject("pageSize", 1);
		mv.addObject("url", "/admin/banner/listUI?pageSize=" + pageSize + "&pageNO=");
		mv.addObject("pageNO", pageNO);
		return mv;
	}
	
	/**
	 * 添加banner-UI
	 * @return
	 */
	@RequestMapping("/addUI")
	public ModelAndView addUI(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/banner/add");
		// 注入添加token
		adminUtils.saveTokenToSession("bannerAddToken", request.getSession());
		return mv;
	}
	
	/**
	 * 添加banner
	 */
	@RequestMapping("/add")
	public ModelAndView add(BannerDTO dto, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		
		// token 校验
		String token = (String) request.getSession().getAttribute("bannerAddToken");
		// 清空token
		request.getSession().removeAttribute("token");
		if (token == null || token.isEmpty()) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		} else {
			if (!token.equals(dto.getToken())) {
				mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
				return mv;
			}
		}
		
		// 校验
		if (dto.getBannerStartDate() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerEndDate() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerStartDate().getTime() > dto.getBannerEndDate().getTime()) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerStatus() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerName() == null || dto.getBannerName().length() == 0 || dto.getBannerName().length() > 20) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerDesc() == null || dto.getBannerDesc().length() == 0 || dto.getBannerDesc().length() > 100) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerType() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		// add
		ActionBanner actionBanner = new ActionBanner();
		actionBanner.setBannerDesc(dto.getBannerDesc());
		actionBanner.setBannerEndDate(dto.getBannerEndDate());
		actionBanner.setBannerName(dto.getBannerName());
		actionBanner.setBannerStartDate(dto.getBannerStartDate());
		actionBanner.setBannerStatus(dto.getBannerStatus());
		actionBanner.setBannerType(dto.getBannerType());
		if (adminBannerService.insertBanner(actionBanner)) {
			// 更新缓存
			adminBannerService.selectNowBannerByTypeToCache(null);
			mv.addObject("msgObj", new MessageDTO(true, "添加成功", "添加banner成功，稍后请添加所属的图片"));
			return mv;
		} else {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
	}
	
	/**
	 * 修改banner状态
	 */
	@ResponseBody
	@RequestMapping("/updateBannerStatus/stop/{id}")
	public JSONDTO updateBannerStatus(
			@PathVariable("id") Integer bannerId
			) {
		JSONDTO dto = new JSONDTO();
		if (adminBannerService.stopBannerById(bannerId)) {
			// 更新缓存
			adminBannerService.selectNowBannerByTypeToCache(null);
			dto.setFlag(true);
			dto.setInfo("banner已经暂停使用");
			return dto;
		}
		dto.setInfo("更新异常，请重试!");
		return dto;
	}

	/**
	 * 修改banner-UI
	 * @return
	 */
	@RequestMapping("/updateUI/{id}")
	public ModelAndView updateUI(
			@PathVariable("id") Integer id,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/banner/update");
		ActionBanner actionBanner = adminBannerService.selectBannerById(id);
		if (actionBanner == null) {
			mv.setViewName("admin/msg/msg");
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		mv.addObject("banner", actionBanner);
		// 注入添加token
		request.getSession().setAttribute("updateToken", adminUtils.byte2hex(adminUtils.createRandomByte()));
		return mv;
	}
	
	/**
	 * 修改banner
	 */
	@RequestMapping("/update")
	public ModelAndView updateBanner(
			BannerDTO dto,
			HttpServletRequest request
			) {
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		// token 校验
		String token = (String) request.getSession().getAttribute("updateToken");
		if (token == null || token.isEmpty()) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		} else {
			if (!token.equals(dto.getToken())) {
				mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
				return mv;
			}
		}
		// 校验
		if (dto.getBannerStartDate() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerEndDate() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerStartDate().getTime() > dto.getBannerEndDate().getTime()) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerStatus() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerName() == null || dto.getBannerName().length() == 0 || dto.getBannerName().length() > 20) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerDesc() == null || dto.getBannerDesc().length() == 0 || dto.getBannerDesc().length() > 100) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		if (dto.getBannerType() == null) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		// 组装数据
		ActionBanner actionBanner = new ActionBanner();
		actionBanner.setBannerId(dto.getBannerId());
		actionBanner.setBannerDesc(dto.getBannerDesc());
		actionBanner.setBannerEndDate(dto.getBannerEndDate());
		actionBanner.setBannerName(dto.getBannerName());
		actionBanner.setBannerStartDate(dto.getBannerStartDate());
		actionBanner.setBannerStatus(dto.getBannerStatus());
		actionBanner.setBannerType(dto.getBannerType());
		if (adminBannerService.updateBannerById(actionBanner)) {
			// 更新缓存
			adminBannerService.selectNowBannerByTypeToCache(null);
			mv.addObject("msgObj", new MessageDTO(true, "修改成功", "修改banner成功，刷新即可"));
			return mv;
		} else {
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
	}
	
	/**
	 * 修改banner图片UI
	 * @param id
	 * @return
	 */
	@RequestMapping("/updateBannerImageUI/{id}")
	public ModelAndView updateBannerImage(
			@PathVariable("id") Integer id
			) {
		ModelAndView mv = new ModelAndView("admin/banner/bannerImgList");
		// 判断ID
		if (id == null) {
			mv.setViewName("admin/msg/msg");
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		// 注册活动
		ActionBanner actionBanner = adminBannerService.selectBannerById(id);
		if (actionBanner == null) {
			mv.setViewName("admin/msg/msg");
			mv.addObject("msgObj", new MessageDTO(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按规定填写数据！"));
			return mv;
		}
		// 注册活动所属图片
		mv.addObject("banner", actionBanner);
		List<ActionBannerImage> images = adminBannerService.selectBannerImgByBannerId(id);
		mv.addObject("images", images);
		// 更新缓存
		adminBannerService.selectNowBannerByTypeToCache(null);
		return mv;
	}
	
	/**
	 * 为banner添加图片
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addImage/{id}")
	public JSONDTO addBannerImages(
			@PathVariable("id") Integer id,
			HttpServletRequest request
			) {
		JSONDTO dto = new JSONDTO();
		// 注册活动
		ActionBanner actionBanner = adminBannerService.selectBannerById(id);
		if (actionBanner == null) {
			dto.setInfo("您的操作有误!");
			return dto;
		}
		// ID
		if (id == null) {
			dto.setInfo("您的操作有误!");
			return dto;
		}
		// 解析数据
		String checkOutUrl = request.getParameter("checkOutUrl");
		if (checkOutUrl == null || checkOutUrl.isEmpty()) {
			dto.setInfo("外链不能为空!");
			return dto;
		}
		String imgUrl = request.getParameter("imgUrl");
		if (imgUrl == null || imgUrl.isEmpty()) {
			dto.setInfo("图片不能为空!");
			return dto;
		}
		ActionBannerImage actionBannerImage = new ActionBannerImage();
		actionBannerImage.setBannerImageCheckOutUrl(checkOutUrl);
		actionBannerImage.setBannerImageUrl(imgUrl);
		actionBannerImage.setBannerId(id);
		if (adminBannerService.insertBannerImg(actionBannerImage)) {
			// 更新缓存
			adminBannerService.selectNowBannerByTypeToCache(null);
			dto.setFlag(true);
			dto.setInfo(actionBannerImage.getBannerImageId()+"");
			return dto;
		} else {
			dto.setInfo("添加失败，请稍后重试!");
			return dto;
		}
	}
	
	/**
	 * 删除bannerIMG
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteImg")
	public JSONDTO deleteBannerImage(
			HttpServletRequest request
			) {
		JSONDTO dto = new JSONDTO();
		// 解析imgid
		String id = request.getParameter("imgId");
		Integer imgId = null;
		if (id == null || id.isEmpty()) {
			dto.setInfo("操作有误，请稍后重试!");
			return dto;
		} else {
			try {
				imgId = Integer.parseInt(id);
			} catch (Exception e) {
			}
		}
		if (imgId == null) {
			dto.setInfo("操作有误，请稍后重试!");
			return dto;
		}
		if (adminBannerService.deleteBannerImgById(imgId)) {
			// 更新缓存
			adminBannerService.selectNowBannerByTypeToCache(null);
			dto.setFlag(true);
		} else {
			dto.setInfo("操作有误，请稍后重试!");
		}
		return dto;
	}
}
