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

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

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.utils.CacheUtils;
import cn.com.liandisys.ycjt.ggcx.admin.utils.CmsUtils;
import cn.com.liandisys.ycjt.ggcx.admin.utils.DynamicSpecifications;
import cn.com.liandisys.ycjt.ggcx.admin.utils.SearchFilter;
import cn.com.liandisys.ycjt.ggcx.admin.utils.SearchFilter.Operator;
import cn.com.liandisys.ycjt.ggcx.common.util.StringUtils;

/**
 * 鍐呭绠＄悊-鍓嶇鎺у埗鍣�
 * @author jiangchao
 * @version 2016-11-30
 */
@Controller
@RequestMapping(value = "/front")
public class CmsFrontController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping
    public String index(Model model) {

        List<Category> categoryList = categoryService.findByParentId("1");
        //		List<Article> articleList = articleService.findAll();
        //		Map<String,List<Article>> categoryArticleMap = new HashMap<String,List<Article>>();
        //		for(Article article:articleList){
        //			String key = article.getCategory().getId();
        //			List<Article> aList = (List<Article>) (categoryArticleMap.get(key)==null?Lists.newArrayList():categoryArticleMap.get(key));
        //			if(aList.size()<8 || !CommonConstant.CATEGORY_MODULE_ARTICLE.equals(article.getCategory().getModule())){
        //				aList.add(article);
        //				categoryArticleMap.put(key, aList);
        //			}
        //		}
        for (Category category : categoryList) {
            //category.setArticleList(categoryArticleMap.get(category.getId()));
            category.setArticleList(CmsUtils.getArticleList(category.getId(), CmsUtils.CMS_INDEX_ARTICLE_SIZE, null));
        }
        model.addAttribute("categoryList", categoryList);
        return "cms/front/frontIndex";
    }

    /**
     * 鍐呭鍒楄〃
     *///
    @RequestMapping(value = "list-{categoryId}.html")
    public String list(@PathVariable String categoryId, @ModelAttribute("pageRequest") PageRequest pageRequest,
            Model model, @ModelAttribute("searchtitle") String searchtitle,
            @ModelAttribute("searchtimestart") String searchtimestart,
            @ModelAttribute("searchtimeend") String searchtimeend) {
        Category category = categoryService.findOne(categoryId);
        if (category == null) {
            return "error/404";
        }
        model.addAttribute("category", category);
        model.addAttribute("categoryList", categoryService.findByParentIdByArticle("1"));
        String view = "/frontList";
        if (StringUtils.isNotBlank(category.getCustomListView())) {
            view = "/" + category.getCustomListView();
        }
        Map<String, SearchFilter> filters = Maps.newHashMap();
        if (categoryId != null && !categoryId.equals("")) {
            filters.put("category.id", new SearchFilter("category.id", Operator.EQ, categoryId));
        }
        if (searchtitle != null && !searchtitle.equals("")) {
            filters.put("title", new SearchFilter("title", Operator.LIKE, searchtitle));
            model.addAttribute("title", searchtitle);
        }
       if (searchtimestart != null && !searchtimestart.equals("")) {
        	/*searchtimestart=searchtimestart+"00:00:00";*/
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
            try {
                Date newtimestart = (Date) sdf.parse(searchtimestart+" 00:00:00");
                filters.put("updateDateStart", new SearchFilter("updateDate", Operator.GTE, newtimestart));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            model.addAttribute("timestart", searchtimestart);
        }
        if (searchtimeend != null && !searchtimeend.equals("")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
            try {
                Date newtimeend = (Date) sdf.parse(searchtimeend+" 23:59:59");
                filters.put("updateDateEnd", new SearchFilter("updateDate", Operator.LTE, newtimeend));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            model.addAttribute("timeend", searchtimeend);
        }
        Specification<Article> spec = DynamicSpecifications.bySearchFilter(filters.values(), Article.class);
        Page<Article> jpaPage = articleService.findAll(spec, pageRequest);
        cn.com.liandisys.ycjt.ggcx.admin.model.Page<Article> page =
                new cn.com.liandisys.ycjt.ggcx.admin.model.Page<Article>(jpaPage.getNumber() + 1, jpaPage.getSize(),
                        jpaPage.getTotalElements());
        page.setList(jpaPage.getContent());
        model.addAttribute("page", page);
        CmsUtils.addViewConfigAttribute(model, category);
        return "cms/front/" + view;
    }

    /**
     * 鏄剧ず鍐呭
     */
    @RequestMapping(value = "view-{categoryId}-{contentId}.html")
    public String view(@PathVariable String categoryId, @PathVariable String contentId, Model model) {

        Category category = categoryService.findOne(categoryId);
        if (category == null) {
            return "error/404";
        }
        // 濡傛灉娌℃湁瀛愭爮鐩紝骞剁埗鑺傜偣涓鸿窡鑺傜偣鐨勶紝鏍忕洰鍒楄〃涓哄綋鍓嶆爮鐩��
        List<Category> categoryList = Lists.newArrayList();
        if (category.getParent() == null) {
            categoryList.add(category);
        } else {
            categoryList = categoryService.findByParentIdByArticle(category.getParent().getId());
        }
        // 鑾峰彇鏂囩珷鍐呭
        Article article = articleService.findOne(contentId);
        if (article == null || !Article.DEL_FLAG_NORMAL.equals(article.getDelFlag())) {
            return "error/404";
        }
        String copyfrom = article.getArticleData().getCopyfrom();

        // 鏂囩珷闃呰娆℃暟+1
        articleService.updateHitsAddOne(article);
        // 灏嗘暟鎹紶閫掑埌瑙嗗浘
        model.addAttribute("category", categoryService.findOne(article.getCategory().getId()));
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("article", article);
        model.addAttribute("copyfrom", copyfrom);
        CmsUtils.addViewConfigAttribute(model, article.getCategory());
        CmsUtils.addViewConfigAttribute(model, article.getViewConfig());
        return "cms/front/" + getTpl(article);
    }

    private String getTpl(Article article) {

        if (StringUtils.isBlank(article.getCustomContentView())) {
            String view = null;
            Category c = article.getCategory();
            boolean goon = true;
            do {
                if (StringUtils.isNotBlank(c.getCustomContentView())) {
                    view = c.getCustomContentView();
                    goon = false;
                } else if (c.getParent() == null || c.getParent().isRoot()) {
                    goon = false;
                } else {
                    c = c.getParent();
                }
            } while (goon);
            return StringUtils.isBlank(view) ? Article.DEFAULT_TEMPLATE : view;
        } else {
            return article.getCustomContentView();
        }
    }

    /**
     * 鍒嗛〉淇℃伅鑾峰彇
     * 
     */
    @ModelAttribute("pageRequest")
    public PageRequest getPageRequest(@RequestParam(value = "pageNo", required = false, defaultValue = "1") String page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") String size) {

        Sort sort = new Sort(Direction.DESC, new String[] {  "weight","updateDate" });
        if (org.springframework.util.StringUtils.hasText(page) && org.springframework.util.StringUtils.hasText(size)
                && null != sort) {
            // 椤电爜浠�0寮�濮�
            PageRequest pageable = new PageRequest(Integer.parseInt(page) - 1, Integer.parseInt(size), sort);
            return pageable;
        }
        return null;
    }

}
