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

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.DemoDataJiGou;
import com.trs.web2frame.tool.tyjyh.tongliao.DocumentData;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.springframework.util.ObjectUtils;

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

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

    public static void main(String[] args) throws ParseException {
        ViewMoveFind viewMove = new ViewMoveFind();
        viewMove.DataZXByChannel("05aa05f98bb14a878e1b8c60f512887f","11349");
    }
    /**
     * 	政务公开 1013 - 988 =
     * @param kpChannelId
     * @param hyChannelId
     */
    public void DataZXByChannel(String kpChannelId,String hyChannelId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + kpChannelId + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInOpenData";//自定义视图
        ServiceImplKp serviceImplKp=new ServiceImplKp();
        Annex annex = new Annex();
        try {
            List<Map<String,Object>> allDocInfoFromKPDBdMaps = serviceImplKp.GetAllDocInfoFromKPDB(kpChannelId);
            System.out.println(allDocInfoFromKPDBdMaps);
            if(allDocInfoFromKPDBdMaps!=null){
                for (Map<String,Object> map : allDocInfoFromKPDBdMaps) {
                    System.out.println("----------------------------"+map+"--------------------------------");
                    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);
                    DocumentData documentData = new DocumentData(map);
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null) {
                        String title = Jsoup.parse(documentData.getTitle()).text();
                        //在海运里面查询对应标题的内容如果返回为空则将信息记录到txt当中
                        String  OpenDatatitle = serviceImplKp.getwcmmetatablegovdocnewsTitle(title,hyChannelId);
                        if(OpenDatatitle == null || OpenDatatitle == ""){
                            outPrint(title,hyChannelId,kpChannelId,documentData.getManuscriptId());
                           new ViewMoveFind().DataZhiXunByChannelOne(hyChannelId,documentData.getManuscriptId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {
        }
    }

    public void DataZXByChannelmanuscriptIdStr(String kpChannelId,String hyChannelId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + kpChannelId + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInOpenData";//自定义视图
        ServiceImplKp serviceImplKp=new ServiceImplKp();
        Annex annex = new Annex();
        try {
            List<Map<String,Object>> allDocInfoFromKPDBdMaps = serviceImplKp.GetAllDocInfoFromKPDB(kpChannelId);
            System.out.println(allDocInfoFromKPDBdMaps);
            if(allDocInfoFromKPDBdMaps!=null){
                for (Map<String,Object> map : allDocInfoFromKPDBdMaps) {
                    System.out.println("----------------------------"+map+"--------------------------------");
                    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);
                    DocumentData documentData = new DocumentData(map);
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null) {
                        String manuscriptId = documentData.getManuscriptId();
                        //在海运里面查询对应标题的内容如果返回为空则将信息记录到txt当中
                        String  OpenDatatitle = serviceImplKp.getwcmmetatablegovdocnewsmanuscriptIdStr(manuscriptId,hyChannelId);
                        if(OpenDatatitle == null || OpenDatatitle == ""){
                            outPrint(documentData.getTitle(),hyChannelId,kpChannelId,documentData.getManuscriptId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {
        }
    }


    /**
     * 	政务公开
     * @param kpChannelId
     * @param hyChannelId
     */
    public void DataZWGKByChannel(String kpChannelId,String hyChannelId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + kpChannelId + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInOpenData";//自定义视图
        ServiceImplKp serviceImplKp=new ServiceImplKp();
        Annex annex = new Annex();
        try {
            List<Map<String,Object>> allDocInfoFromKPDBdMaps = serviceImplKp.GetAllDocInfoFromKPDB(kpChannelId);
            System.out.println(allDocInfoFromKPDBdMaps.size());
            if(allDocInfoFromKPDBdMaps!=null){
                for (Map<String,Object> map : allDocInfoFromKPDBdMaps) {
                    System.out.println("----------------------------"+map+"--------------------------------");
                    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);
                    DocumentData documentData = new DocumentData(map);
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null) {
                        String title = Jsoup.parse(documentData.getTitle()).text();
                        String manuscriptId = documentData.getManuscriptId();
                        String c_fwrq = documentData.getC_FWRQ();
                        String  OpenDatatitle = null;
                        //在海运里面查询对应标题的内容如果返回为空则将信息记录到txt当中
                        OpenDatatitle = serviceImplKp.getWCMMETATABLEGovOpenDataBYTitle(title,hyChannelId);
                        System.out.println("OpenDatatitle==="+OpenDatatitle);
                        if(OpenDatatitle == null || OpenDatatitle == ""){
                            outPrint(manuscriptId+","+title,hyChannelId,kpChannelId,documentData.getManuscriptId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {
        }
    }

    //政务公开查询附件



    public void outPrint(String title,String hyChannelId,String kpChannelId,String getManuscriptId){
        try (
                BufferedWriter writer = new BufferedWriter(new FileWriter(ColumnConfig.outPrintFileTitle,true))
        )
        {
            writer.write(title+","+hyChannelId+","+kpChannelId+","+getManuscriptId);
            writer.newLine(); // 换行
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    public void DataZhiXunByChannelOne(String hyChannelId,String manuscriptIdStr){
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInWeb";//自定义视图
        ServiceImplKp serviceImplKp=new ServiceImplKp();
        Annex annex = new Annex();
        try {
            List<Map<String,Object>> allDocInfoFromKPDBdMaps = serviceImplKp.GetAllDocInfoFromKPDBOne(manuscriptIdStr);
            if(allDocInfoFromKPDBdMaps!=null){
                int count=0;
                for (Map<String,Object> 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);
                    DocumentData documentData = new DocumentData(map);
                    System.out.println(documentData);
                    String manuscriptIdOldDocId = documentData.getManuscriptId();
                    if(manuscriptIdOldDocId != null && manuscriptIdOldDocId != ""){
                        //查询海云的docid
                        String ObjectId = serviceImplKp.GetWcmMetaTableGovDocNewsMetaDataIdByOldDocId(manuscriptIdOldDocId,hyChannelId);
                        System.out.println(ObjectId);
                        if(ObjectId != null && ObjectId != ""){
                            oPostData.put("ObjectId", ObjectId);
                            continue;
                        }
                    }
                    //标题-必填
                    if (documentData.getTitle() != null && documentData.getTitle() != "null") {
                        /*String text = Jsoup.parse(documentData.getTitle()).text();
                        int ff = text.indexOf("发展规划");
                        if(ff >= 0){
                            continue;
                        }*/
                        oPostData.put("DOCTITLE", Jsoup.parse(documentData.getTitle()).text()  );
                    }
                    //副标题
                    if (documentData.getSubTitle() != null && documentData.getSubTitle() != "null") {
                        oPostData.put("SUBDOCTITLE",Jsoup.parse(documentData.getSubTitle()).text() );
                    }
                    //短标题
                    if (documentData.getShortTitle() != null && documentData.getShortTitle() != "null") {
                        oPostData.put("SHORTTITLE",Jsoup.parse(documentData.getShortTitle()).text());
                    }
                    //关键词
                    if (documentData.getKEYWORD() != null  && documentData.getKEYWORD() != "") {
                        String keyword = documentData.getKEYWORD();
                        keyword = keyword.replaceAll("<br/>", "");//
                        keyword = keyword.replaceAll("<br>", "");//
                        oPostData.put("DOCKEYWORDS", keyword);
                    }
                    //发布时间
                    if (documentData.getPublishedTime() != null) {
                        oPostData.put("DOCRELTIME", documentData.getPublishedTime());
                    }
                    //创建时间
                    if (documentData.getCREATED_TIME() != null) {
                        oPostData.put("CRTIME", documentData.getCREATED_TIME());
                    }
                    //来源
                    if (documentData.getB_source() != null && documentData.getB_source() != "") {
                        oPostData.put("DOCSOURCENAME",documentData.getB_source());
                    }
                    //摘要
                    if (documentData.getMemo() != null && documentData.getMemo() != "") {
                        oPostData.put("DOCABSTRACT", documentData.getMemo());
                    }
                    if (documentData.getManuscriptId() != null) {
                        oPostData.put("oldDocid", documentData.getManuscriptId());
                    }
                    //处理附件
                    try {
                        if (documentData.getManuscriptId() != null) {
                            Map<String, Object> getRelFileInfoByDocId = annex.getZhiXunFileInfoByDocId(documentData.getManuscriptId());
                            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.getCurrentFilePathHtmlUrl()  != null) {
                            String  currentFilePathHtmlUrl = documentData.getCurrentFilePathHtmlUrl();
                            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();
                    }
                    //查询是否有重定向链接，如果有调用链接视图
                    if (documentData.getREDIRECT_URL() != null && documentData.getREDIRECT_URL() != "") {
                        oPostData.put("DOCTYPE", CMSConstants.CONTENT_BODY_LINK);
                        oPostData.put("DOCLINK", documentData.getREDIRECT_URL());
                    }
                    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.getManuscriptId());
                                try {
                                    //处理引用文章
                                    String manuscriptId = documentData.getManuscriptId();
                                    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.getManuscriptId(),count);
                            }
                        }
                    }catch(Exception e) {
                        outPrint("",documentData.getManuscriptId(),count);
                        e.printStackTrace();
                    }
                    System.out.println("------------------------------------------------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataZhiXunByChannel error"+e.getMessage());
        } finally {

        }
    }
    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;
    }
}
