package com.apobates.forum.trident.controller.admin;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.api.service.TopicCarouselService;
import com.apobates.forum.core.api.service.TopicCarouselSlideService;
import com.apobates.forum.core.entity.BoardCarouselIndex;
import com.apobates.forum.core.entity.TopicCarousel;
import com.apobates.forum.core.entity.TopicCarouselSlide;
import com.apobates.forum.member.entity.ForumCalendarUnitEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.trident.controller.form.BoardCarouselForm;
import com.apobates.forum.trident.controller.form.TopicCarouselForm;
import com.apobates.forum.trident.controller.form.TopicCarouselSlideForm;
import com.apobates.forum.trident.fileupload.ImageStorageExecutor;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
/**
 * 轮播图/幻灯片控制器
 * 
 * @author xiaofanku
 * @since 20191012
 */
@Controller
@RequestMapping(value = "/admin/topic/carousel")
public class AdminTopicCarouselController {
	@Autowired
	private TopicCarouselService topicCarouselService;
	@Autowired
	private TopicCarouselSlideService topicCarouselSlideService;
	@Autowired
	private ImageStorageExecutor imageStorageExecutor;
	private final static Logger logger = LoggerFactory.getLogger(AdminTopicCarouselController.class);
	
	//忽略状态的所有轮播图
	@GetMapping(path="/")
	public String listPage(HttpServletRequest request, Model model) {
		model.addAttribute("rs", topicCarouselService.getAll().collect(Collectors.toList()));
		return "admin/topic_carousel/index";
	}
	//编辑或创建轮播图
	@GetMapping(path="/edit")
	public String editEditForm(@RequestParam(name="id", required=false, defaultValue="0") int id, HttpServletRequest request, Model model){
		TopicCarouselForm form = new TopicCarouselForm();
		TopicCarousel tc = topicCarouselService.get(id).orElse(TopicCarousel.empty());
		form.setRecord(tc.getId());
		form.setStatus(tc.isStatus());
		form.setTitle(tc.getTitle());
		form.setSummary(tc.getSummary());
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		model.addAttribute("paramId", id);
		return "admin/topic_carousel/edit";
	}
	@PostMapping(path="/edit")
	public String editEditAction(@ModelAttribute("form") TopicCarouselForm form, HttpServletRequest request, Model model){
		String ctitle = form.getTitle();
		if(!Commons.isAlphaCharacter(ctitle)){
			model.addAttribute("errors","非法的标题名称,只允许字母和数字组合,不可以使用中文");
			//
			form.setToken(Commons.randomAlphaNumeric(8));
			model.addAttribute("form", form);
			return "admin/topic_carousel/edit";
		}
		boolean symbol=false;String errMsg=null;
		try{
			if(form.isUpdate()){
				symbol = topicCarouselService.edit(form.getIntegerRecord(), ctitle, form.getSummary(), form.getBooleanStatus()).orElse(false);
			}else{
				int data = topicCarouselService.create(ctitle, form.getSummary(), form.getBooleanStatus());
				symbol = data > 0;
				if(symbol){
					form.setRecord(data);
				}
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if(symbol){
			//新增:跳转到增加幻灯片
			//编辑:
			return (form.isUpdate())?"redirect:/admin/topic/carousel/":"redirect:/admin/topic/carousel/slide/edit?carousel="+form.getRecord();
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"轮播图操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/topic_carousel/edit";
	}
	//删除remove
	@PostMapping(path="/remove", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage removeTopicCarouselAction(
			@RequestParam("id")int topicCarouselId,
			MemberSessionBean mbean,
			HttpServletRequest request,
			Model model){
		return TipMessage.Builder.take(()->topicCarouselService.remove(topicCarouselId)).success("轮播图删除成功").error("操作失败");
	}
	//轮播图下所有幻灯片,忽略状态
	@GetMapping(path="/slide")
	public String getAllSlidePage(@RequestParam("carousel")int topicCarouselId, HttpServletRequest request, Model model){
		model.addAttribute("rs", topicCarouselSlideService.getAllIgnoreStatus(topicCarouselId).collect(Collectors.toList()));
		return "admin/topic_carousel/slide_index";
	}
	//编辑或创建幻灯片
	@GetMapping(path="/slide/edit")
	public String slideEditForm(
			@RequestParam(name="id", required=false, defaultValue="0") int carouselSlideId, 
			@RequestParam(name="carousel", required=false, defaultValue="0")int carouselId, 
			HttpServletRequest request, 
			Model model){
		TopicCarouselSlideForm form = new TopicCarouselSlideForm();
		TopicCarouselSlide tcs = topicCarouselSlideService.get(carouselSlideId).orElse(TopicCarouselSlide.empty(carouselSlideId));
		form.setRecord(tcs.getId());
		form.setStatus(tcs.isStatus());
		form.setTitle(tcs.getTitle());
		form.setLink(tcs.getLink());
		form.setRanking(tcs.getRanking()+"");
		form.setCarousel(tcs.getTopicCarouselId()+"");
		form.setImageAddr(tcs.getImageAddr());
		if(carouselSlideId == 0 && carouselId>0){ //为轮播图增加幻灯片
			form.setCarousel(carouselId+"");
		}
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/topic_carousel/slide_edit";
	}
	@PostMapping(path="/slide/edit")
	public String slideEditAction(
			@ModelAttribute("form") TopicCarouselSlideForm form, 
			HttpServletRequest request, 
			Model model){
		boolean symbol=false;String errMsg=null;
		try{
			if(form.isUpdate()){
				symbol = topicCarouselSlideService.edit(form.getIntegerRecord(), form.getTitle(), form.getLink(), form.getIntegerRanking(), form.getBooleanStatus()).orElse(false);
			}else{
				//------------------------------------------------------------编码图标图片的地址
				String icoImageAddr = form.getEncodePictureAddr(imageStorageExecutor);
				//------------------------------------------------------------
				symbol = topicCarouselSlideService.create(form.getIntegerCarousel(), form.getTitle(), form.getLink(), icoImageAddr, form.getIntegerRanking(), form.getBooleanStatus())>0;
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if(symbol){
			return "redirect:/admin/topic/carousel/slide?carousel="+form.getCarousel();
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"幻灯片操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/topic_carousel/slide_edit";
	}
	//删除remove
	@PostMapping(path="/slide/remove", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage removeTopicCarouselSlideAction(
			@RequestParam("id")int topicCarouselSlideId,
			@RequestParam("carousel")int topicCarouselId,
			MemberSessionBean mbean,
			HttpServletRequest request,
			Model model){
		return TipMessage.Builder.take(()->topicCarouselSlideService.remove(topicCarouselSlideId, topicCarouselId)).success("幻灯片删除成功").error("操作失败");
	}
	//版块绑定轮播图
	@GetMapping(path="/bind")
	public String bindBoardForm(
			@RequestParam("carousel")int topicCarouselId,
			HttpServletRequest request, 
			Model model){
		BoardCarouselForm form = new BoardCarouselForm();
		form.setBoardId("0");
		form.setVolumesId("-1");
		form.setLimit("1");
		form.setUnit("3");
		form.setCarouselId(topicCarouselId+"");
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		TopicCarousel tc = topicCarouselService.get(topicCarouselId).orElse(TopicCarousel.empty());
		model.addAttribute("carousel", tc);
		return "admin/topic_carousel/bind";
	}
	@PostMapping(path="/bind")
	public String bindBoardAction(
			@ModelAttribute("form") BoardCarouselForm form, 
			HttpServletRequest request, 
			Model model){
		boolean symbol = topicCarouselService.bindBoard(form.getIntegerVolumes(), form.getLongBoard(), form.getIntegerCarousel(), form.getDateTimeExpireDate()).orElse(false);
		if(symbol){
			return "redirect:/admin/topic/carousel/bind/result?carousel="+form.getCarouselId();
		}
		model.addAttribute("errors", "版块绑定轮播图操作失败");
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		TopicCarousel tc = topicCarouselService.get(form.getIntegerCarousel()).orElse(TopicCarousel.empty());
		model.addAttribute("carousel", tc);
		return "admin/topic_carousel/bind";
	}
	@PostMapping(path="/bind/remove", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage removebindBoardRecordAction(
			@RequestParam("carousel")int topicCarouselId,
			@RequestParam("board")long boardId,
			@RequestParam("volumes")int volumesId,
			HttpServletRequest request, 
			Model model){
		return TipMessage.Builder.take(()->topicCarouselService.remove(topicCarouselId, volumesId, boardId)).success("版块轮播图关联删除成功").error("操作失败");
	}
	//版块绑定轮播图记录
	@GetMapping(path="/bind/result")
	public String bindBoardPage(
			@RequestParam("carousel")int topicCarouselId,
			HttpServletRequest request, 
			Model model){
		List<BoardCarouselIndex> rs = topicCarouselService.getAllRelative(topicCarouselId).collect(Collectors.toList());
		model.addAttribute("rs", rs);
		return "admin/topic_carousel/bind_result";
	}
	//绑定轮播图时长单位
	@GetMapping(path="/bind/unit/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Integer,String> getAllTimeUnit(HttpServletRequest request, Model model){
		return EnumArchitecture.getInstance(ForumCalendarUnitEnum.class).entrySet().stream().filter(x -> x.getKey() > 2).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
	}
}
