package cn.com.liandisys.ycjt.ggcx.admin.controller.cms;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.com.liandisys.ycjt.ggcx.admin.model.cms.Article;
import cn.com.liandisys.ycjt.ggcx.admin.model.cms.Category;
import cn.com.liandisys.ycjt.ggcx.admin.service.cms.ArticleService;
import cn.com.liandisys.ycjt.ggcx.admin.service.cms.CategoryService;
import cn.com.liandisys.ycjt.ggcx.admin.service.cms.FileTplService;
import cn.com.liandisys.ycjt.ggcx.admin.utils.TplUtils;
import cn.com.liandisys.ycjt.ggcx.common.constant.CommonConstant;
import cn.com.liandisys.ycjt.ggcx.common.util.StringUtils;

/**
 * 内容管理-栏目控制器
 * @author jiangchao
 * @version 2016-11-29
 */
@Controller
@RequestMapping(value = "/admin/cms/category")
public class CategoryController {
	
	public static final String TOP_CATEGORY_ID = "1";

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private FileTplService fileTplService;
	@Autowired
	private ArticleService articleService;
	
	@RequestMapping(value="/list")
	public String list(Model model,String message){
		Sort sort = new Sort(Direction.ASC, new String[] { "sort" });
		List<Category> list = categoryService.findAll(sort);
		List<Category> sortList = Lists.newArrayList();
		Category.sortList(sortList, list, null);
		model.addAttribute("list", sortList);
		model.addAttribute("message", message);
		return "admin/cms/categoryList";
	}
	
	@RequestMapping(value = "form")
	public String form(Category category, Model model) {
		if ((category.getParent()==null||category.getParent().getId()==null)&&!TOP_CATEGORY_ID.equals(category.getId())){
			category.setParent(new Category(TOP_CATEGORY_ID));
			Category parent = categoryService.findOne(category.getParent().getId());
			category.setParent(parent);
		}
		model.addAttribute("listViewList",getTplContent(Category.DEFAULT_TEMPLATE));
        model.addAttribute("category_DEFAULT_TEMPLATE",Category.DEFAULT_TEMPLATE);
        model.addAttribute("contentViewList",getTplContent(Article.DEFAULT_TEMPLATE));
        model.addAttribute("article_DEFAULT_TEMPLATE",Article.DEFAULT_TEMPLATE);
		model.addAttribute("category", category);
		return "admin/cms/categoryForm";
	}
	
	@RequestMapping(value = "save")
	public String save(Category category, Model model, RedirectAttributes redirectAttributes) {
		categoryService.save(category);
		redirectAttributes.addAttribute("message", "保存栏目'" + category.getName() + "'成功");
		return "redirect:list";
	}
	
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts,RedirectAttributes redirectAttributes) {
    	int len = ids.length;
    	Category[] entitys = new Category[len];
    	for (int i = 0; i < len; i++) {
    		entitys[i] = categoryService.findOne(ids[i]);
    		entitys[i].setSort(sorts[i]);
    		categoryService.save(entitys[i]);
    	}
    	redirectAttributes.addAttribute("message", "保存栏目排序成功!");
		return "redirect:list";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Category category, RedirectAttributes redirectAttributes) {
		if (Category.isRoot(category.getId())){
			redirectAttributes.addAttribute("message", "删除栏目失败, 不允许删除顶级栏目或编号为空");
			return "redirect:list";
		}
		List<Category> children = categoryService.findByParentId(category.getId());
		if(children!=null && children.size()>0){
			redirectAttributes.addAttribute("message", "删除栏目失败, 请先删除"+category.getName()+"栏目下的子级栏目");
			return "redirect:list";
		}
		List<Article> articles = articleService.findByCategoryId(category.getId());
		if(articles!=null && articles.size()>0){
			redirectAttributes.addAttribute("message", "删除栏目失败, 请先删除"+category.getName()+"栏目下的文章");
			return "redirect:list";
		}
		categoryService.delete(category);
		redirectAttributes.addAttribute("message", "删除栏目成功");
		return "redirect:list";
	}
	
	@ModelAttribute("category")
	public Category getCategory(@RequestParam(required=false) String id){
		if (StringUtils.isNotBlank(id)){
			return categoryService.findOne(id);
		}else{
			return new Category();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String module, @RequestParam(required=false) String extId, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Sort sort = new Sort(Direction.ASC, new String[] { "sort" });
		List<Category> list = categoryService.findAll(sort);
		for (int i=0; i<list.size(); i++){
			Category e = list.get(i);
			if (extId == null || (extId!=null && !extId.equals(e.getId()))){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParent()!=null?e.getParent().getId():0);
				map.put("name", e.getName());
				map.put("module", e.getModule());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	private List<String> getTplContent(String prefix) {
   		List<String> tplList = fileTplService.getNameListByPrefix(CommonConstant.TPL_BASE);
   		tplList = TplUtils.tplTrim(tplList, prefix, "");
   		return tplList;
   	}
}
