/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.com.liandisys.ycjt.ggcx.admin.utils;

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

import javax.servlet.ServletContext;

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.ui.Model;

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.utils.SearchFilter.Operator;
import cn.com.liandisys.ycjt.ggcx.common.config.Global;
import cn.com.liandisys.ycjt.ggcx.common.util.SpringContextHolder;
import cn.com.liandisys.ycjt.ggcx.common.util.StringUtils;

/**
 * 内容管理工具类
 * @author jiangchao
 * @version 2016-11-29
 */
public class CmsUtils {

    public static final String CACHE_ARTICLE_LIST = "articleListCache";

    public static final String CACHE_ARTICLE_LIST_BELONG_ID = "id_";

    public static final Integer CMS_INDEX_ARTICLE_SIZE = 7;

    private static ServletContext context = SpringContextHolder.getBean(ServletContext.class);

    private static ArticleService articleService = SpringContextHolder.getBean(ArticleService.class);

    /**
     * 获取文章
     * @param articleId 文章编号
     * @return
     */
    public static Article getArticle(String articleId) {

        return articleService.findOne(articleId);
    }

    /**
     * 获取文章列表
     * @param categoryId 分类编号
     * @param number 获取数目
     * @param param  预留参数，例： key1:'value1', key2:'value2' ...
     * 			posid	推荐位（1：首页焦点图；2：栏目页文章推荐；）
     * 			image	文章图片（1：有图片的文章）
     *          orderBy 排序字符串
     * @return
     * ${fnc:getArticleList(category.id, not empty pageSize?pageSize:8, 'posid:2, orderBy: \"hits desc\"')}"
     */
    @SuppressWarnings("unchecked")
    public static List<Article> getArticleList(String categoryId, int number, String param) {

        List<Article> cacheList = new ArrayList<Article>();
        //        CacheUtils.remove(CACHE_ARTICLE_LIST + categoryId, CACHE_ARTICLE_LIST_BELONG_ID + categoryId);
        cacheList = (List<Article>) CacheUtils.get(CACHE_ARTICLE_LIST + categoryId,
                CACHE_ARTICLE_LIST_BELONG_ID + categoryId);
        if (cacheList != null && cacheList.size() > 0) {
            return cacheList;
        } else {
            Sort sort = new Sort(Direction.DESC, new String[] { "weight", "updateDate" });
            PageRequest pageable = new PageRequest(0, number, sort);
            Map<String, SearchFilter> filters = Maps.newHashMap();
            if (!categoryId.equals("")) {
                filters.put("category.id", new SearchFilter("category.id", Operator.EQ, categoryId));
            }
            Specification<Article> spec = DynamicSpecifications.bySearchFilter(filters.values(), Article.class);
            Page<Article> jpaPage = articleService.findAll(spec, pageable);
            CacheUtils.put(CACHE_ARTICLE_LIST + categoryId, CACHE_ARTICLE_LIST_BELONG_ID + categoryId,
                    jpaPage.getContent());
            return jpaPage.getContent();
        }
    }

    /**
     * 获得文章动态URL地址
     * @param article
     * @return url
     */
    public static String getUrlDynamic(Article article) {

        if (StringUtils.isNotBlank(article.getLink())) {
            return article.getLink();
        }
        StringBuilder str = new StringBuilder();
        str.append(context.getContextPath()).append(Global.getFrontPath());
        str.append("/front/view-").append(article.getCategory().getId()).append("-").append(article.getId())
                .append(Global.getUrlSuffix());
        return str.toString();
    }

    /**
     * 获得栏目动态URL地址
     * @param category
     * @return url
     */
    public static String getUrlDynamic(Category category) {

        if (StringUtils.isNotBlank(category.getHref())) {
            if (!category.getHref().contains("://")) {
                return context.getContextPath() + Global.getFrontPath() + category.getHref();
            } else {
                return category.getHref();
            }
        }
        StringBuilder str = new StringBuilder();
        str.append(context.getContextPath()).append(Global.getFrontPath());
        str.append("/list-").append(category.getId()).append(Global.getUrlSuffix());
        return str.toString();
    }

    /**
     * 从图片地址中去除ContextPath地址
     * @param src
     * @return src
     */
    public static String formatImageSrcToDb(String src) {

        if (StringUtils.isBlank(src))
            return src;
        if (src.startsWith(context.getContextPath() + "/userfiles")) {
            return src.substring(context.getContextPath().length());
        } else {
            return src;
        }
    }

    /**
     * 从图片地址中加入ContextPath地址
     * @param src
     * @return src
     */
    public static String formatImageSrcToWeb(String src) {

        if (StringUtils.isBlank(src))
            return src;
        if (src.startsWith(context.getContextPath() + "/userfiles")) {
            return src;
        } else {
            return context.getContextPath() + src;
        }
    }

    public static void addViewConfigAttribute(Model model, String param) {

    }

    public static void addViewConfigAttribute(Model model, Category category) {

    }
}