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

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

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.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.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.CmsUtils;
import cn.com.liandisys.ycjt.ggcx.admin.utils.DynamicSpecifications;
import cn.com.liandisys.ycjt.ggcx.admin.utils.JsonMapper;
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.admin.utils.TplUtils;
import cn.com.liandisys.ycjt.ggcx.common.constant.CommonConstant;
import cn.com.liandisys.ycjt.ggcx.common.util.StringUtils;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;

/**
 * 内容管理-文章控制器
 * @author jiangchao
 * @version 2016-11-29
 */
@Controller
@RequestMapping(value = "/admin/cms/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private FileTplService fileTplService;

    //本地自己调试使用
    //    private String masterKey = "50c1b278c274f1405514bc6f";
    //
    //    private String appKey = "583704c2ba9c55d1be353f0c";

    //服务器打版本使用
    //    private String masterKey = "4b2cb195a6de02a1b1b7e3b3";
    //
    //    private String appKey = "9e337475066ef829430d8ccf";

    // properties 配置文件名称
    PropertyResourceBundle res = (PropertyResourceBundle) PropertyResourceBundle.getBundle("application");

    // 获取properties配置文件中的属性值
    String masterKey = res.getString("masterKey");

    String appKey = res.getString("appKey");

    @RequestMapping(value = "/list")
    public String list(Model model, @ModelAttribute("pageRequest") PageRequest pageRequest,
            @RequestParam(value = "category.id", required = false, defaultValue = "") String categoryId,
            @RequestParam(value = "title", required = false, defaultValue = "") String title, String message) {

        Map<String, SearchFilter> filters = Maps.newHashMap();
        if (!categoryId.equals("")) {
            filters.put("category.id", new SearchFilter("category.id", Operator.EQ, categoryId));
            Category category = categoryService.findOne(categoryId);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("categoryName", category.getName());
        }
        if (!title.equals("")) {
            filters.put("title", new SearchFilter("title", Operator.LIKE, title));
            model.addAttribute("title", title);
        }
        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);
        model.addAttribute("message", message);
        model.addAttribute("user",SecurityUtils.getSubject().getPrincipal());
        //System.out.println(masterKey);
        //System.out.println(appKey);
        return "admin/cms/articleList";

    }

    @RequestMapping(value = "form")
    public String form(Article article, Model model,
            @RequestParam(value = "TempcategoryId", required = false, defaultValue = "") String TempcategoryId) {

        // 如果当前传参有子节点，则选择取消传参选择
        if (article.getCategory() != null && StringUtils.isNotBlank(article.getCategory().getId())) {
            List<Category> list = categoryService.findByParentId(article.getCategory().getId());
            if (list.size() > 0) {
                article.setCategory(null);
            } else {
                article.setCategory(categoryService.findOne(article.getCategory().getId()));//获得文章父级节点
            }
        }
        model.addAttribute("contentViewList", getTplContent());
        model.addAttribute("article_DEFAULT_TEMPLATE", Article.DEFAULT_TEMPLATE);
        model.addAttribute("article", article);
        model.addAttribute("TempcategoryId", TempcategoryId);
        CmsUtils.addViewConfigAttribute(model, article.getCategory());
        return "admin/cms/articleForm";
    }

    /**
     * 文章选择列表
     */
    @RequiresPermissions("cms:article:view")
    @RequestMapping(value = "selectList")
    public String selectList(Article article, @ModelAttribute("pageRequest") PageRequest pageRequest, Model model,
            @RequestParam(value = "category.id", required = false, defaultValue = "") String categoryId,
            @RequestParam(value = "title", required = false, defaultValue = "") String title) {

        Map<String, SearchFilter> filters = Maps.newHashMap();
        if (!categoryId.equals("")) {
            filters.put("category.id", new SearchFilter("category.id", Operator.EQ, categoryId));
        }
        if (!title.equals("")) {
            filters.put("sex", new SearchFilter("title", Operator.LIKE, title));
        }
        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);
        return "admin/cms/articleSelectList";
    }

    //保存按钮的功能
    @RequestMapping(value = "save")
    public String save(Article article, Model model, RedirectAttributes redirectAttributes,
            @RequestParam(value = "TempcategoryId", required = false, defaultValue = "") String TempcategoryId)
            throws UnsupportedEncodingException, APIConnectionException, APIRequestException {

    	// 如设置发布时间，则用发布时间覆盖创建时间
    	if (article.getPublisheDate()!=null && article.getPublisheDate()!="") {
    		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		try {
				Date date = format.parse(article.getPublisheDate());
			    article.setCreateDate(date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				article.setCreateDate(new Date());
			}  
    	} else {
    		if (article.getCreateDate() !=null) {
    			
    		} else {
    			article.setCreateDate(new Date());
    		}
    	}
    	
        articleService.save(article);
        redirectAttributes.addAttribute("message", "保存文章'" + StringUtils.abbr(article.getTitle(), 50) + "'成功");
        redirectAttributes.addAttribute("category.id", TempcategoryId);

        // 栏目区分为 2：交通要闻时 发推送消息
        if (article.getCategory() != null && "2".equals(article.getCategory().getId()) 
        		&& "1".equals(article.getAppIndexView())) {
            sendMessage(article.getTitle());
        }

        return "redirect:list";
    }

    private void sendMessage(String message) throws APIConnectionException, APIRequestException {

        JPushClient jpushClient = new JPushClient(masterKey, appKey, null, ClientConfig.getInstance());
        PushPayload payload = buildPushObject_all_all_alert(message);
        try {
            PushResult result = jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            System.out.println(e);
            throw e;
        } catch (APIRequestException e) {
            System.out.println(e);
            throw e;
        }
    }

    public static PushPayload buildPushObject_all_all_alert(String message) {

        return PushPayload.alertAll(message);
    }

    @RequestMapping(value = "delete")
    public String delete(Article article, RedirectAttributes redirectAttributes) {

        articleService.delete(article);
        redirectAttributes.addAttribute("message", "删除文章成功");
        return "redirect:list";
    }
    @RequestMapping(value = "publish")
    public String publish(Article article, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException, APIConnectionException, APIRequestException {

    	Article articlec = articleService.findOne(article.getId());
    	articlec.setDelFlag("0");
    	articleService.save(articlec);
        redirectAttributes.addAttribute("message", "发布文章成功");
     // 栏目区分为 2：交通要闻时 发推送消息
        if (article.getCategory() != null && "2".equals(article.getCategory().getId()) 
        		&& "1".equals(article.getAppIndexView())) {
            sendMessage(article.getTitle());
        }
        return "redirect:list";
    }

    /**
     * 通过编号获取文章标题
     */
    @ResponseBody
    @RequestMapping(value = "findByIds")
    public String findByIds(String ids) {

        List<Object[]> list = articleService.findByIds(ids);
        return JsonMapper.nonDefaultMapper().toJson(list);
    }

    @ModelAttribute("article")
    public Article getArticle(@RequestParam(required = false) String id) {

        if (StringUtils.isNotBlank(id)) {
        	Article article = articleService.findOne(id);
        	if (article != null) {
        		if (article.getAppIndexView()=="" || article.getAppIndexView() == null) {
        			article.setAppIndexView("0");
        		}
        		if (article.getAppInfoView()=="" || article.getAppInfoView() == null) {
        			article.setAppInfoView("0");
        		}
        	}
            return article;
        } else {
            return new Article();
        }
    }

    /**
     * 分页信息获取
     * 
     */
    @ModelAttribute("pageRequest")
    public PageRequest getPageRequest(@RequestParam(value = "pageNo", required = false, defaultValue = "1") String page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "20") String size) {

        Sort sort = new Sort(Direction.DESC, new String[] { "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;
    }

    private List<String> getTplContent() {

        List<String> tplList = fileTplService.getNameListByPrefix(CommonConstant.TPL_BASE);
        tplList = TplUtils.tplTrim(tplList, Article.DEFAULT_TEMPLATE, "");
        return tplList;
    }
}
