package com.trs.web2frame.tool.tyjyh.ggzyzheng;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.trs.cms.CMSConstants;
import com.trs.web2frame.WCMServiceCaller;
import com.trs.web2frame.dispatch.Dispatch;
import com.trs.web2frame.tool.tyjyh.Log_Exception;
import com.trs.web2frame.tool.tyjyh.tongliao.*;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 视图类
 */
public class ViewMoveGgzy {

    public static void main(String[] args) {
        ViewMoveGgzy viewMove = new ViewMoveGgzy();
    }
    /**
     * 资讯视图
     * @param kpChannelId
     * @param hyChannelId
     */
    public void DataZhiXunByChannel(String kpChannelId,String hyChannelId,String tableName){
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + kpChannelId + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInWeb";//自定义视图
        ServiceImplGgzy serviceImplKp=new ServiceImplGgzy();
        Annex annex = new Annex();
        try {
            List<Map<String,String>> allDocInfoFromKPDBdMaps = serviceImplKp.getNmgGgzy(kpChannelId,tableName);
            if(allDocInfoFromKPDBdMaps!=null){
                int count=0;
                for (Map<String,String> map : allDocInfoFromKPDBdMaps) {
                    System.out.println("------------------------------------------------------------");
                    Map<String,Object> oPostData=new HashMap<>();
                    oPostData.put("ObjectId", 0);
                    oPostData.put("ChannelId", Integer.parseInt(hyChannelId));// 目标栏目id
                    oPostData.put("CurrUserName", "dev");
                    oPostData.put("isShenhe", "1");
                    oPostData.put("DOCTYPE", CMSConstants.CONTENT_BODY_HTML);
                    DocumentDataBenJi documentData = new DocumentDataBenJi(map);
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null && documentData.getTitle() != "null") {
                        oPostData.put("DOCTITLE", Jsoup.parse(documentData.getTitle()).text()  );
                    }
                    //发布时间
                    if (documentData.getTime() != null) {
                        oPostData.put("DOCRELTIME", documentData.getTime());
                    }
                    //创建时间
                    if (documentData.getTime() != null) {
                        oPostData.put("CRTIME", documentData.getTime());
                    }
                    //来源
                 /*   if (documentData.getB_source() != null && documentData.getB_source() != "") {
                        oPostData.put("DOCSOURCENAME",documentData.getB_source());
                    }*/
                    //摘要
                    if (documentData.getId() != null) {
                        oPostData.put("oldDocid", documentData.getId());
                    }
                    //处理附件
                    try {
                        if (documentData.getId() != null) {
                            Map<String, Object> getRelFileInfoByDocId = annex.getZhiXunFileInfoByDocId(JsoupUtilsView.filePath,documentData.getId());
                            if( getRelFileInfoByDocId.get("docRelFile") != null){
                                oPostData.put("docRelFile", getRelFileInfoByDocId.get("docRelFile"));
                            }
                            if( getRelFileInfoByDocId.get("docRelPic") != null){
                                oPostData.put("docRelPic", getRelFileInfoByDocId.get("docRelPic"));
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        // 内容中图片和附件需要特殊处理
                        if (documentData.getContent()  != null) {
                            String  currentFilePathHtmlUrl = documentData.getContent();
                            System.out.println("===================start=======================");
                            System.out.println(currentFilePathHtmlUrl);
                            JsoupUtilsView jsoupUtils = new JsoupUtilsView();
                            String html = jsoupUtils.rexStringHtml(currentFilePathHtmlUrl);
                            System.out.println("==============================================");
                            System.out.println(html);
                            System.out.println("===================end========================");
                            oPostData.put("DOCHTMLCON", html);
                        } else {
                            oPostData.put("DocHtmlCon", "&nbsp;");
                            oPostData.put("DOCCONTENT", "&nbsp;");
                        }
                    }catch (Exception e){
                        oPostData.put("DocHtmlCon", "&nbsp;");
                        oPostData.put("DOCCONTENT", "&nbsp;");
                        e.printStackTrace();
                    }
                    //查询是否有重定向链接，如果有调用链接视图
                    String content = documentData.getContent();
                    if(content.equals("链接文章")){
                        if (documentData.getContent() != null && documentData.getContent() != "") {
                            oPostData.put("DOCTYPE", CMSConstants.CONTENT_BODY_LINK);
                            oPostData.put("DOCLINK", documentData.getContent());
                        }
                    }
                    if(content.equals("文件文章")){
                        String url = JsoupUtilsView.filePath +""+ documentData.getUrl();
                        String filename = documentData.getUrl();
                        String docTitle = documentData.getTitle();
                        if (documentData.getContent() != null && documentData.getContent() != "") {
                            Dispatch oDispatch = WCMServiceCaller.UploadFile(url);
                            if (oDispatch != null) {
                                String docfilename = oDispatch.getUploadShowName();
                                String DOCFILE = "[";
                                DOCFILE += "{\"AppFile\": \"" + docfilename + "\",\"AppDesc\":\"" + docTitle
                                        + "\",\"AppendixId\":\"0\", \"SrcFile\":\"" + filename
                                        + "\",\"OTHEROPERATION\":0 }";
                                DOCFILE += "]";

                                oPostData.put("DocFileName", docfilename);
                                oPostData.put("DOCFILE", DOCFILE);
                                // oPostData.put("DOCPUBURL",oDispatch);
                            }

                        }
                    }

                    try {
                        System.out.println(oPostData);
                        Dispatch result = WCMServiceCaller.Call(sServiceId, sMethodName, oPostData, true);
                        count++;
                        if(result!=null){
                            JSONObject rObject = JSONObject.fromObject(result.getResponseText().toString());
                            if (rObject.get("ISSUCCESS").toString().equals("true")){
                                System.out.println("DOCTITLE:"+documentData.getTitle());
                                System.out.println("count:"+count);
                                System.out.println("oldDocid:"+documentData.getId());
                                try {
                                    //处理引用文章
                                    String manuscriptId = documentData.getId();
                                    if(manuscriptId != null && manuscriptId != ""){
                                        ColumnMapping columnMapping = new ColumnMapping();
                                        columnMapping.ColumnMappingCheck(manuscriptId);
                                    }
                                }catch (Exception ee){
                                    ee.printStackTrace();
                                }
                            }else{
                                String serror = JSON.toJSONString(rObject);
                                System.out.println(serror);
                                outPrint(serror,documentData.getId(),count);
                            }
                        }
                    }catch(Exception e) {
                        outPrint("",documentData.getId(),count);
                        e.printStackTrace();
                    }
                    System.out.println("------------------------------------------------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataZhiXunByChannel error"+e.getMessage());
        } finally {
        }
    }

    public String updateFile(String url) throws Exception {
        System.out.println("==============");
        String fileNameRe = null;
        try {
            if(url != null && url != ""){
                System.out.println(url);
                Dispatch dispatch = WCMServiceCaller.UploadFile(url);
                System.out.println("-----------"+dispatch.getUploadShowName());
                fileNameRe = dispatch.getUploadShowName();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileNameRe;
    }


    public void outPrint(String serror,String ManuscriptId,int count){
        try (
                BufferedWriter writer = new BufferedWriter(new FileWriter(ColumnConfig.outPrintFile,true))
        )
        {
            writer.write(serror+","+ManuscriptId+","+count+",");
            writer.newLine(); // 换行
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public String getJg(String jgmc)
    {

        String code = null;
        List<DemoDataJiGou> list = new ArrayList<>();
        EasyExcel.read(ColumnConfig.fileName, DemoDataJiGou.class, new PageReadListener<DemoDataJiGou>(dataList -> {
            for (DemoDataJiGou demoDataJiGou : dataList) {
                String jgName = demoDataJiGou.getJgName();
                if(jgName != null && jgName != ""){
                    list.add(demoDataJiGou);
                }
            }
        })).sheet().doRead();
        for (DemoDataJiGou demoDataJiGou : list) {
            if(demoDataJiGou.getJgName().equals(jgmc)){
                code = demoDataJiGou.getCode();
            }
        }
        return code;
    }
}
