package com.cftech.mp.article.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.mp.article.model.MpArticle;
import com.cftech.mp.article.service.ArticleService;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * 素材管理Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String ARTICLE_VIEW = "mp:article:view"
 * 查看:public static final String ARTICLE_EDIT = "mp:article:edit"
 *
 * @author lisw
 * @date: 2017-04-18 17:37
 */
@Slf4j
@Controller
@RequestMapping("/a/article")
public class ArticleController {

    public static final String ARTICLE_VIEW = "mp:article:view";
    public static final String ARTICLE_EDIT = "mp:article:edit";

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private ArticleService articleService;

    @RequestMapping(value = "newsList",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject articleList(HttpServletRequest request, int iDisplayStart, int iDisplayLength){
        JSONObject rtnJson = new JSONObject();
        Long accountsId = UserUtils.getmpaccounts(request);
       List<MpArticle> articles = new ArrayList<MpArticle>();
        int count = 0;
        try {
            Conds conds = new Conds();
            conds.equal("del_flag",0);
            conds.equal("accounts_id",accountsId);
           articles=articleService.fetchSearchByPage(conds,null,iDisplayStart,iDisplayLength);
            count = articleService.count(conds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        rtnJson.put("iTotalRecords", count);
        rtnJson.put("iTotalDisplayRecords", count);
        rtnJson.put("aaData",articles);
        return  rtnJson;
    }





    //列表页面
    @RequiresPermissions(value = ARTICLE_VIEW)
    @RequestMapping(value="/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "article/articlelist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = ARTICLE_VIEW)
    @RequestMapping(value="/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            MpArticle article = articleService.fetchById(id);
            model.addAttribute("data", article);
        }
        return "article/articleform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = ARTICLE_EDIT)
    @RequestMapping(value="/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(MpArticle article, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        if (article != null && article.getId() != null) {
            article.setUpdateBy(UserUtils.getUser().getId());
            articleService.update(article);
            rtnJson.put("errorNo", 0);
        } else {
            article.setAccountsId(accountsId);
            article.setDelFlag(false);
            article.setAccountsId(UserUtils.getmpaccounts(request));
            article.setCreateBy(UserUtils.getUser().getId());
            article.setUpdateBy(UserUtils.getUser().getId());
            articleService.save(article);
            rtnJson.put("errorNo", 2);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = ARTICLE_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, MpArticle article, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("wx_update_time", OrderType.DESC);

        List<MpArticle> list = articleService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = articleService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = ARTICLE_EDIT)
    @RequestMapping(value="/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            articleService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    //同步微信官图文素材
    @RequiresPermissions(value = ARTICLE_EDIT)
    @RequestMapping(value="/syns",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject syns(HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        try {
            Long accountsId = UserUtils.getmpaccounts(request);
            String accessToken = tokenUtil.getToken(accountsId);
            int count =  articleService.updateSynsTable(accessToken,accountsId);

            rtnJson.put("errorNo",0);
            rtnJson.put("count",count);
        }catch (Exception e) {
            rtnJson.put("errorNo",1);
            e.printStackTrace();
        }
        return rtnJson;
    }

    //图文素材预览接口
    @RequestMapping(value="preview",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject preview(HttpServletRequest request,String openId,String mediaId){
        JSONObject rtnJson = new JSONObject();

        if(!StringUtils.isEmpty(openId) && !StringUtils.isEmpty(mediaId)){
            Long accountid = UserUtils.getmpaccounts(request);
            try {
                JwSendMessageAPI.messagePrivateMediaId(tokenUtil.getToken(accountid),openId,mediaId);
                rtnJson.put("errorNo",0);
            } catch (WexinReqException e) {
                e.printStackTrace();
            }
        }else{
            rtnJson.put("errorNo",1);
        }
        return rtnJson;
    }

}
