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

import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.TopicService;
import com.apobates.forum.core.api.service.TopicTagService;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.core.entity.TopicTag;
import com.apobates.forum.event.elderly.ActionEventCulpritor;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.trident.controller.form.TopicTagForm;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.StringSeekUtils;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
/**
 * 话题标签控制器
 * 
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/admin/topic/tag")
public class AdminTopicTagController {
	@Autowired
	private TopicTagService topicTagService;
	@Autowired
	private TopicService topicService;
	@Value("${site.pageSize}")
	private int pageSize;
	
	@GetMapping(path="/")
	public String listPage(
			@RequestParam(value = "p", required = false, defaultValue = "1") int page, 
			HttpServletRequest request, 
			Model model) {
		FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/admin/topic/tag/").addPageSize("number", pageSize);
		Pageable pr = new PageRequest(page, fpbuild.getPageSize());
		Page<TopicTag> rs = topicTagService.getAll(pr);
		model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
		model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
		return "admin/topic_tag/index";
	}
	
	/*删除同时删除话题关联的标题
	@PostMapping(path="/remove", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage removeTagAction(
			@RequestParam("id")long tagId, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model){
		boolean symbol = topicTagService.remove(tagId).getOrElse(false);
		if (symbol) {
			return TipMessage.ofSuccess("标签删除成功");
		}
		return TipMessage.ofError("操作失败");
	}*/
	
	//删除话题标签的关联
	@PostMapping(path="/delete", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage deleteTagRelativeAction(
			@RequestParam("id")long tagId, 
			@RequestParam("topic")long topicId, 
			@RequestParam(value = "token", required = false, defaultValue = "0")String token, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model){
		ActionEventCulpritor aec = ActionEventCulpritor.getInstance(mbean.getMid(), mbean.getNickname(), request, token);
		return TipMessage.Builder.take(()->topicTagService.deleteForTopic(topicId, tagId, aec)).success("成功删除标签").error("操作失败");
	}
	
	@GetMapping(path="/collection")
	public String topicTaglistPage(
			@RequestParam("topic")long topicId, 
			HttpServletRequest request, 
			Model model) {
		model.addAttribute("rs", topicTagService.getAllBy(topicId));
		return "admin/topic_tag/topic";
	}
	
	//为话题新增标签
	@GetMapping(path="/create")
	public String createTopicTagForm(
			@RequestParam("topic")long topicId, 
			HttpServletRequest request, 
			Model model){
		Topic topic = topicService.get(topicId).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
		TopicTagForm form = new TopicTagForm();
		form.setToken(Commons.randomAlphaNumeric(8));
		form.setTopic(topicId);
		form.setTitle(topic.getTitle());
		model.addAttribute("form", form);
		return "admin/topic_tag/topic_edit";
	}
	@PostMapping(path="/create")
	public String createTopicTagAction(
			@ModelAttribute("form")TopicTagForm form, 
			MemberSessionBean mbean, 
			HttpServletRequest request, 
			Model model){
		//过滤一下
		String newTagNames = Commons.htmlPurifier(form.getNames()).trim();
		//获取话题的内容以便词频统计
		Topic topic = topicService.getTopicContent(form.getTopic(), null);
		if(null == topic){
			form.setToken(Commons.randomAlphaNumeric(8));
			model.addAttribute("form", form);
			//
			model.addAttribute("errors", "话题不存在或暂时无法访问");
			return "admin/topic_tag/topic_edit";
		}
		int rates = StringSeekUtils.queryWordCountByBM(topic.getTitle()+" "+topic.getContent().getContent(), newTagNames);
		//
		ActionEventCulpritor aec = ActionEventCulpritor.getInstance(mbean.getMid(), mbean.getNickname(), request, form.getToken());
		String errMsg=null;
		try{
			long id = topicTagService.create(topic.getId(), newTagNames, rates, aec);
			if(id>0){
				return "redirect:/admin/topic/tag/collection?topic="+form.getTopic();
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		//
		model.addAttribute("errors", Commons.optional(errMsg, "增加话题标签操作失败"));
		return "admin/topic_tag/topic_edit";
	}
}
