package com.cftech.cms.cfarticle.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.cms.cfarticle.model.Cfarticle;
import com.cftech.cms.cfarticle.model.CfarticleColumnDto;
import com.cftech.cms.cfarticle.service.CfarticleService;
import com.cftech.cms.column.model.Column;
import com.cftech.cms.column.service.ColumnService;
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.FileUtils;
import com.cftech.core.util.InputStreamCache;
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 net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.htmlparser.util.ParserException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.wxbase.wxmedia.JwMediaAPI;
import org.mp.api.wxbase.wxmedia.model.WxArticlesRespponseByMaterial;
import org.mp.api.wxbase.wxmedia.model.WxMediaForMaterial;
import org.mp.api.wxbase.wxmedia.model.WxMediaForMaterialResponse;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.mp.api.wxsendmsg.model.WxArticle;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.io.IOException;
import java.util.*;


/**
 * CMS文章管理Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String CFARTICLE_VIEW = "qy:cfarticle:view"
 * 查看:public static final String CFARTICLE_EDIT = "qy:cfarticle:edit"
 *
 * @author lisw
 * @date: 2017-05-03 10:51
 */
@Slf4j
@Controller
@RequestMapping("/a/cfarticle")
public class CfarticleController {

    public static final String CFARTICLE_VIEW = "qy:cfarticle:view";
    public static final String CFARTICLE_EDIT = "qy:cfarticle:edit";

    @Autowired
    private CfarticleService cfarticleService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private ArticleService articleService;


    //列表页面
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public String list(HttpServletRequest request, Model model,String type) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        try{
            if(com.cftech.core.util.StringUtils.equals(type,"1")){
                return "cfarticle/piclist";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "cfarticle/cfarticlelist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Cfarticle cfarticle = cfarticleService.fetchById(id);
            cfarticle.setContent(ESAPI.encoder().decodeForHTML(cfarticle.getContent()));
            model.addAttribute("data", cfarticle);
            Column column = columnService.fetchById(cfarticle.getColumn());
            if(column!=null){
                model.addAttribute("columnName",column.getName());
            }
            Conds conds = new Conds();
            if(!StringUtils.isEmpty(cfarticle.getRelation_article())){
                conds.in("t.id",cfarticle.getRelation_article().split(","));
                List<Cfarticle> cfarticles = cfarticleService.fetchSearchByPage(conds,null,0,0);
                List<String> strings = new ArrayList<String>();
                for(Cfarticle cfartic : cfarticles){
                    strings.add(cfartic.getTitle());
                }
                if(strings.size()>0){
                    model.addAttribute("relationArticlesStr", com.cftech.core.util.StringUtils.join(strings.toArray(),","));
                    model.addAttribute("relationArticles",strings);
                }
            }
        }
        return "cfarticle/cfarticleform";
    }

    //图集编辑页面（新增、修改）
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/picform",method = {RequestMethod.GET,RequestMethod.POST})
    public String picform(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Cfarticle cfarticle = cfarticleService.fetchById(id);
            model.addAttribute("data", cfarticle);
            Column column = columnService.fetchById(cfarticle.getColumn());
            if(column!=null){
                model.addAttribute("columnName",column.getName());
            }
            Conds conds = new Conds();
            if(!StringUtils.isEmpty(cfarticle.getRelation_article())){
                conds.in("t.id",cfarticle.getRelation_article().split(","));
                List<Cfarticle> cfarticles = cfarticleService.fetchSearchByPage(conds,null,0,0);
                List<String> strings = new ArrayList<String>();
                for(Cfarticle cfartic : cfarticles){
                    strings.add(cfartic.getTitle());
                }
                if(strings.size()>0){
                    model.addAttribute("relationArticlesStr", com.cftech.core.util.StringUtils.join(strings.toArray(),","));
                    model.addAttribute("relationArticles",strings);
                }
            }
        }
        return "cfarticle/picform";
    }



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

    //专题文章绑定列表
    //获取列表数据
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/listDataTemp",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listDataTemp(int iDisplayStart, int iDisplayLength, Cfarticle cfarticle, HttpServletRequest request,String columnName,Long specialId) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(cfarticle.getTitle())) {
            conds.like("t.title", cfarticle.getTitle());
        }
        if (!StringUtils.isEmpty(cfarticle.getDesc())) {
            conds.like("t.desc", cfarticle.getDesc());
        }
        if(!StringUtils.isEmpty(columnName)){
            conds.like("co.name",columnName);
        }
        if (!StringUtils.isEmpty(cfarticle.getRelation_article())) {
            conds.like("t.relation_article", cfarticle.getRelation_article());
        }
        if (!StringUtils.isEmpty(cfarticle.getColumn())) {
            conds.equal("t.column", cfarticle.getColumn());
        }
        if (!StringUtils.isEmpty(cfarticle.getType())) {
            conds.equal("t.type", cfarticle.getType());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<CfarticleColumnDto> list = cfarticleService.fetchSearchByPageTemp(conds, sort, iDisplayStart, iDisplayLength,specialId);
        Integer counts = cfarticleService.countTemp(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Cfarticle cfarticle, HttpServletRequest request,String columnName,String startTime) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(cfarticle.getTitle())) {
            conds.like("t.title", cfarticle.getTitle());
        }
        if (!StringUtils.isEmpty(cfarticle.getDesc())) {
            conds.like("t.desc", cfarticle.getDesc());
        }
        if(!StringUtils.isEmpty(columnName)){
            conds.like("co.name",columnName);
        }
        if (!StringUtils.isEmpty(cfarticle.getRelation_article())) {
            conds.like("t.relation_article", cfarticle.getRelation_article());
        }
        if (!StringUtils.isEmpty(cfarticle.getColumn())) {
            conds.equal("t.column", cfarticle.getColumn());
        }
        if (!StringUtils.isEmpty(cfarticle.getType())) {
            conds.equal("t.type", cfarticle.getType());
        }if (!StringUtils.isEmpty(startTime)) {
            conds.equal("DATE_FORMAT(t.create_time,'%Y-%m-%d')", startTime);
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);

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

    //获取列表数据
    @RequiresPermissions(value = CFARTICLE_VIEW)
    @RequestMapping(value = "/listDataInOrder",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listDataInOrder(String articles,HttpServletRequest request,String whereArticles) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if(!StringUtils.isEmpty(whereArticles)){
          conds.in("t.id",whereArticles.split(","));
        }

        if(!StringUtils.isEmpty(articles)){
           if(articles.substring(articles.length()-1,articles.length()).equals(",")){
               articles= articles.substring(0,articles.lastIndexOf(","));
           }
        }

        List<Cfarticle> list = cfarticleService.fetchSearchByPageInOrder(conds, articles);

        JSONObject rtnJson = new JSONObject();
        rtnJson.put("list",list);
        return rtnJson;
    }

    /**
     * 组合图文为微信素材图文
     * @param articles
     * @param request
     * @return
     */
    @RequestMapping(value = "/mergeArticles",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject mergeArticles(String articles,HttpServletRequest request,String domain) throws WexinReqException, ParserException, IOException {
        JSONObject rtnJson = new JSONObject();
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if(!StringUtils.isEmpty(articles)){
            conds.in("t.id",articles.split(","));
        }
        List<Cfarticle> list = cfarticleService.fetchSearchByPageInOrder(conds, articles);
        List<WxArticle> wxArticles = new ArrayList<WxArticle>();
        for(int i =0,j=list.size();i<j;i++){
            Cfarticle article = list.get(i);
            WxArticle wxArticle = new WxArticle();
            String image = "";
            if(!article.getBigimg().startsWith("http")){
                article.setBigimg(domain+article.getBigimg());
            }
            if(!article.getSmallimg().startsWith("http")){
                article.setSmallimg(domain+article.getSmallimg());
            }
            if(i==0){
                image = article.getBigimg();//多图文中的第一个使用大图作为封面
            }else{
                image = article.getSmallimg();//多图文中非第一个图文，使用小图作为封面
            }
            //将封面转换成微信图片ID
            WxMediaForMaterial wx = new WxMediaForMaterial();
            Map<String,Object> imageMap = FileUtils.getInputStreamMap(image);
            String suffix = imageMap.get("type").toString();
            try{
               // InputStream fileTypeStream = isc.getInputStream();
               //fileType = fileTypeJudge.getType(fileTypeStream);
              //  stream = new ByteArrayInputStream(buffer);
            }catch (Exception e){
                e.printStackTrace();
            }
            // stream.reset();
//            fileType = FileType.JPEG;
            wx.setFileName(UUID.randomUUID().toString()+suffix);
            InputStreamCache wxInputStream= (InputStreamCache) imageMap.get("inputstream");
            wx.setInputStream(wxInputStream.getInputStream());
            wx.setType("image");
            WxMediaForMaterialResponse response = JwMediaAPI.uploadMediaFileByMaterial(mpTokenUtil.getToken(accountsId), wx);
            if (response != null) {
                article.setThumbMediaId(response.getMedia_id());
            } else {
                rtnJson.put("errorNo", 3);
                return rtnJson;
            }
            //将内容中的图片，转换成微信图文专用图片（注:微信图文中不支持外部链接图片，故需要把内容中的图片上传到微信）
            String content =  articleImg(ESAPI.encoder().decodeForHTML(article.getContent()),mpTokenUtil.getToken(accountsId),domain);
            wxArticle.setTitle(article.getTitle());
            wxArticle.setContent(content);
            wxArticle.setShow_cover_pic("0");
            wxArticle.setAuthor(article.getAuthor());
            wxArticle.setThumb_media_id(article.getThumbMediaId());
            wxArticle.setContent_source_url(article.getContentSourceUrl());
            wxArticle.setDigest(article.getDesc());
            wxArticles.add(wxArticle);
        }
        String mediaId = JwSendMessageAPI.getMediaId(mpTokenUtil.getToken(accountsId),wxArticles);


        /**
         * 同步微信素材，防止不实时
         */
//        int count =  articleService.updateSynsTable(mpTokenUtil.getToken(accountsId),accountsId);
        WxArticlesRespponseByMaterial response =  JwMediaAPI.getArticlesByMaterial(mpTokenUtil.getToken(accountsId),mediaId);





        if(response!=null){
            MpArticle article = new MpArticle();
            List<WxArticle> news_item = response.getNews_item();
            if(news_item!=null && news_item.size()>0){
                JSONArray array = JSONArray.fromObject(news_item);
                article.setAccountsId(accountsId);
                article.setCreateBy(UserUtils.getUser().getId());
                article.setUpdateBy(UserUtils.getUser().getId());
                article.setDelFlag(false);
                article.setStatus("0");
                article.setWxUpdateTime(new Date(Long.valueOf(response.getUpdate_time() * 1000)));
                article.setNews_item(array.toString());
                article.setMedia_id(mediaId);
                articleService.save(article);
            }
        }

        rtnJson.put("mediaId",mediaId);
        rtnJson.put("errorNo",0);
        return rtnJson;
    }



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


    //将content中的img，上传到微信图文专用图片链接
    private String articleImg(String content,String accessToken,String domain) throws ParserException, IOException {
        Document doc = Jsoup.parse(content);
        Elements aa = doc.select("img");
        for (Element element: aa) {
            String oldImgSrc = element.attr("src");
            if(!oldImgSrc.startsWith("http")){
                oldImgSrc=domain+oldImgSrc;
            }
             Map<String,Object> imageMap = FileUtils.getInputStreamMap(oldImgSrc);
            InputStreamCache isc = (InputStreamCache) imageMap.get("inputstream");
            String suffix = imageMap.get("type").toString();
            String newImgSrc= JwSendMessageAPI.UploadImageurl(accessToken, isc.getInputStream(), UUID.randomUUID().toString()+suffix);
            content = content.replace(oldImgSrc.replace(domain,""),newImgSrc);
        }

        Elements elements = doc.getAllElements();
        for (Element element: elements) {
            String style = element.attr("style");
            if (!StringUtils.isEmpty(style)) {
                int index = style.indexOf("background-image");
                if (index > -1) {
                    style = style.substring(index);
                    style = style.substring(0, style.indexOf(";"));
                    System.out.println(style);
                    style = style.substring(style.indexOf("(")+1, style.indexOf(")"));
                    Map<String,Object> imageMap = FileUtils.getInputStreamMap(style);
                    InputStreamCache isc = (InputStreamCache) imageMap.get("inputstream");
                    String suffix = imageMap.get("type").toString();
                    String newImgSrc= JwSendMessageAPI.UploadImageurl(accessToken, isc.getInputStream(), UUID.randomUUID().toString()+suffix);
                    content = content.replace(style,newImgSrc);
                }
                int indexWebkit = style.indexOf("-webkit-border-image");
                if (indexWebkit > -1) {
                    style = style.substring(indexWebkit);
                    style = style.substring(0, style.indexOf(";"));
                    System.out.println(style);
                    style = style.substring(style.indexOf("(")+1, style.indexOf(")"));
                    Map<String,Object> imageMap = FileUtils.getInputStreamMap(style);
                    InputStreamCache isc = (InputStreamCache) imageMap.get("inputstream");
                    String suffix = imageMap.get("type").toString();
                    String newImgSrc= JwSendMessageAPI.UploadImageurl(accessToken, isc.getInputStream(), UUID.randomUUID().toString()+suffix);
                    content = content.replace(style,newImgSrc);
                }
            }
        }
//        Parser parser =new Parser(content);
//        NodeFilter filter = new TagNameFilter("img");  //获取所有的img标签
//        NodeFilter backFilter = new HasAttributeFilter("background-image");
//        NodeList nodes = parser.extractAllNodesThatMatch(filter);
//        NodeList backNodes = parser.extractAllNodesThatMatch(backFilter);
//        Node eachNode = null;
//        ImageTag imageTag = null;
//        String oldSrcPath = null;
//        String dataSrcPath = null;
//        if (nodes != null)
//        {
//            for (int i = 0; i < nodes.size(); i++)
//            {
//                eachNode = (Node)nodes.elementAt(i);
//                if (eachNode instanceof ImageTag)
//                {
//                    imageTag = (ImageTag)eachNode;
//                    String oldStr=imageTag.toHtml();
//                    oldSrcPath = imageTag.getAttribute("src");  //获取src属性
//                    Map<String,Object> imageMap = FileUtils.getInputStreamMap(oldSrcPath);
//                    InputStreamCache isc = (InputStreamCache) imageMap.get("inputstream");
//                    String suffix = imageMap.get("type").toString();
//                    String url= JwSendMessageAPI.UploadImageurl(accessToken, isc.getInputStream(), UUID.randomUUID().toString()+suffix);
//                    if(StringUtils.isEmpty(url)){
//                        return null;
//                    }
//                    imageTag.setAttribute("src",url);
//                    String newStr=imageTag.toHtml();
//                    content=content.replace(oldStr,newStr);
//
//                }
//            }
//        }
//        if(backNodes!=null){
//            for(int i=0;i<backNodes.size();i++){
//                eachNode=backNodes.elementAt(i);
//                if (eachNode instanceof ImageTag)
//                {
//                    imageTag = (ImageTag)eachNode;
//                    String oldStr=imageTag.toHtml();
//                    oldSrcPath = imageTag.getAttribute("background-image");  //获取src属性
//                    Map<String,Object> imageMap = FileUtils.getInputStreamMap(oldSrcPath);
//                    InputStreamCache isc = (InputStreamCache) imageMap.get("inputstream");
//                    String suffix = imageMap.get("type").toString();
//                    String url= JwSendMessageAPI.UploadImageurl(accessToken, isc.getInputStream(), UUID.randomUUID().toString()+suffix);
//                    if(StringUtils.isEmpty(url)){
//                        return null;
//                    }
//                    imageTag.setAttribute("background-image",url);
//                    String newStr=imageTag.toHtml();
//                    content=content.replace(oldStr,newStr);
//                }
//            }
//        }
        return content;
    }
    @RequestMapping(value = "/updatecom")
    @ResponseBody
    public JSONObject updatecom(String datas){

        return  cfarticleService.updatecom(datas);
    }
    @RequestMapping(value = "/selectYes")
    @ResponseBody
    public JSONObject selectYes() {
        return cfarticleService.selectYes();
    }

    @RequestMapping(value = "/selectBanner")
    @ResponseBody
    public JSONObject selectBanner() {
        return cfarticleService.selectBanner();
    }
}
