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

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 ViewMoveUpdate {

    public static void main(String[] args) throws ParseException {
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
        Date parse = dateFormat.parse("2019-08-01");
        ViewMoveUpdate viewMove = new ViewMoveUpdate();
        long time = parse.getTime();
        System.out.println(time);
        viewMove.DataZhiXunByChannelAddOrUpdateByDate("8ab3c796b5b64b5fa65e12ff88b5bff9","4482",time+"");
    }
    /**
     * 资讯视图 - 增量数据迁移
     * 开普系统的文档id 对应 海运系统当中的 oldDocid 去海云里面查询对应的文档对应的docid，将docid设置到对应的ObjectId即可完成更新
     *
     * @param kpChannelId
     * @param hyChannelId
     */
    public void DataZhiXunByChannelAddOrUpdateByDate(String kpChannelId,String hyChannelId,String date){
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + 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.GetAllDocInfoFromKPDBByDate(kpChannelId,date);
            if(allDocInfoFromKPDBdMaps!=null){
                int count=0;
                for (Map<String,Object> map : allDocInfoFromKPDBdMaps) {

                    String titleLog = "";

                    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("DOCTYPE", CMSConstants.CONTENT_BODY_HTML);
                    oPostData.put("isShenhe", "1");
                    DocumentData documentData = new DocumentData(map);
                    String manuscriptIdOldDocId = documentData.getManuscriptId();
                    if(manuscriptIdOldDocId != null && manuscriptIdOldDocId != ""){
                        //查询海云的docid
                        String ObjectId = serviceImplKp.GetWcmMetaTableGovDocNewsMetaDataIdByOldDocId(manuscriptIdOldDocId,hyChannelId);
                        if(ObjectId != null && ObjectId != ""){
                            oPostData.put("ObjectId", ObjectId);
                        }
                    }
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null && documentData.getTitle() != "null") {
                        oPostData.put("DOCTITLE", Jsoup.parse(documentData.getTitle()).text()  );
                    }
                    //副标题
                    if (documentData.getSubTitle() != null && documentData.getSubTitle() != "null") {
                        oPostData.put("SUBDOCTITLE",Jsoup.parse(documentData.getSubTitle()).text() );
                        titleLog = 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(titleLog,documentData.getManuscriptId(),count);
                        e.printStackTrace();
                    }
                    System.out.println("------------------------------------------------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log_Exception.Error_txt("DataZhiXunByChannel error"+e.getMessage());
        } finally {
        }
    }
    /**
     * 资讯视图 - 抄送增量栏目数据迁移
     * @param kpChannelId
     * @param hyChannelId
     */
    public void DataZhiXunByChannelGetAllDocAddOrUpdateByDate(String kpChannelId,String hyChannelId,String date){
        Log_Exception.Logger_txt("-------Start-------kpChannelId:" + kpChannelId + "--hyChannelId:" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInWeb";//自定义视图
        ServiceImplKp serviceImplKp=new ServiceImplKp();
        Annex annex = new Annex();
        List<Map<String, String>> mapAllDocs = serviceImplKp.GetAllDocCmsCarbonCopy(kpChannelId);
        for (Map<String, String> mapAllDoc : mapAllDocs) {
            String manuscript_id = mapAllDoc.get("MANUSCRIPT_ID");
            List<Map<String, Object>> allDocInfoFromKPDBdMaps = serviceImplKp.GetAllDocInfoFromByMANUSCRIPT_ID(manuscript_id);
            System.out.println(allDocInfoFromKPDBdMaps);
            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("DOCTYPE", CMSConstants.CONTENT_BODY_HTML);
                    oPostData.put("isShenhe", "1");
                    DocumentData documentData = new DocumentData(map);
                    String manuscriptIdOldDocId = documentData.getManuscriptId();
                    if(manuscriptIdOldDocId != null && manuscriptIdOldDocId != ""){
                        //查询海云的docid
                        String ObjectId = serviceImplKp.GetWcmMetaTableGovDocNewsMetaDataIdByOldDocId(manuscriptIdOldDocId,hyChannelId);
                        if(ObjectId != null && ObjectId != ""){
                            oPostData.put("ObjectId", ObjectId);
                        }
                    }
                    System.out.println(documentData);
                    //标题-必填
                    if (documentData.getTitle() != null && documentData.getTitle() != "null") {
                        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("------------------------------------------------------------");
                }
            }

        }


    }



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