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

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 net.sf.json.JSONObject;

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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StartZWGKDataExchange3 {

	public static void main(String[] args) {
    	ServiceImplWcm si=new ServiceImplWcm();
        StartZWGKDataExchange3 wcm=new StartZWGKDataExchange3();
        try {
        	wcm.DataExchangeByChannel("e319520a1ef34a94a9353edb94c49a0f", "276");
        } catch (Exception e) {
            Log_Exception.Error_txt("StartMethord()方法异常！"+e.getMessage());
        }
	}




	/**
     * 根据新旧栏目对应关系迁移数据
     * @param wcmChannelId
     * @param hyChannelId
     */
    public void DataExchangeByChannel(String wcmChannelId,String hyChannelId){
        Log_Exception.Logger_txt("-------Start-------将原栏目id：" + wcmChannelId + "中得数据导入海云平台" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInWeb";//自定义视图
        ServiceImplWcm wcm=new ServiceImplWcm();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            List<Map<String,Object>> oldMaps=wcm.GetAllDocInfoFromOldDB(wcmChannelId, "");
            if(oldMaps!=null){
                int count=0;
                for (Map<String,Object> map : oldMaps) {

                    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);
                    String wcmDocId=map.get("MANUSCRIPT_ID").toString();//文档ID
                    String docTitle=map.get("TITLE").toString();
                    //标题-必填
                    if (docTitle != null) {
                        oPostData.put("DOCTITLE", docTitle);
                    }
                    //副标题
                    if (map.get("SUB_TITLE") != null) {
						oPostData.put("SUBDOCTITLE", map.get("SUB_TITLE"));
					}
					//短标题
					if (map.get("SHORT_TITLE") != null) {
						oPostData.put("SHORTTITLE", map.get("SHORT_TITLE"));
					}
					//关键词
					if (map.get("KEYWORD") != null) {
						String keyword = (String) map.get("KEYWORD");
						keyword = keyword.replaceAll("<br/>", "");//
						keyword = keyword.replaceAll("<br>", "");//
						oPostData.put("DOCKEYWORDS", keyword);
					}
					//发布时间
					if (map.get("PUBLISHED_TIME") != null) {
						long pubtime = Long.parseLong(map.get("PUBLISHED_TIME").toString());
						Date date1 = new Date(pubtime);
						try {
							LocalDateTime localDateTime = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
							LocalDateTime after8Hours = localDateTime.plusHours(8);
							date1 = Date.from(after8Hours.atZone(ZoneId.systemDefault()).toInstant());
						}catch (Exception e){
						}
						String pubtimeStr = simpleDateFormat.format(date1);
						oPostData.put("DOCRELTIME", pubtimeStr);
					}
					//创建时间
					if (map.get("CREATED_TIME") != null) {
						long crtime = Long.parseLong(map.get("CREATED_TIME").toString());
						Date date1 = new Date(crtime);
						String crtimeStr = simpleDateFormat.format(date1);
						oPostData.put("CRTIME", crtimeStr);
					}

					//来源
					if (map.get("B_SOURCE") != null) {
						oPostData.put("DOCSOURCENAME", map.get("B_SOURCE"));
					}

					//摘要
					if (map.get("MEMO") != null) {
						oPostData.put("DOCABSTRACT", map.get("MEMO"));
					}
					//链接地址
/*					if (map.get("DOCLINK") != null) {
						oPostData.put("DOCLINK", map.get("DOCLINK"));
					}*/
					oPostData.put("oldDocid", wcmDocId);
					
					//处理附件
					try {
						Map<String, Object> getRelFileInfoByDocId = wcm.GetRelFileInfoByDocId(wcmDocId);
						oPostData.put("docRelFile", getRelFileInfoByDocId.get("docRelFile"));
						oPostData.put("docRelPic", getRelFileInfoByDocId.get("docRelPic"));
					}catch (Exception e){
						e.printStackTrace();
					}

					try {
						// 内容中图片和附件需要特殊处理
						if (map.get("currentFilePathHtmlUrl") != null) {
							String  currentFilePathHtmlUrl = map.get("currentFilePathHtmlUrl")+"";
							System.out.println(currentFilePathHtmlUrl);
							JsoupUtils jsoupUtils = new JsoupUtils();
							String html = jsoupUtils.rexStringHtml(currentFilePathHtmlUrl);
							System.out.println("================================");
							System.out.println(html);
							oPostData.put("DOCHTMLCON", html);
						} else {
							oPostData.put("DocHtmlCon", "&nbsp;");
							oPostData.put("DOCCONTENT", "&nbsp;");
						}
					}catch (Exception e){
						e.printStackTrace();
					}

					try {
	                    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("==="+count+"======wcmdocid:"+wcmDocId);
	                        }else{
								String serror = JSON.toJSONString(oPostData);
								try (BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\ruoyi\\output.txt",true))) {
									writer.write(serror+"==============wcmDocId======"+wcmDocId +"===========count=========="+count);
									writer.newLine(); // 换行
								} catch (IOException e1) {
									e1.printStackTrace();
								}
							}
	                    }
					}catch(Exception e) {
						String serror = JSON.toJSONString(oPostData);
						try (BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\ruoyi\\output.txt",true))) {
							writer.write(serror+"==============wcmDocId======"+wcmDocId +"===========count=========="+count);
							writer.newLine(); // 换行
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						e.printStackTrace();
					}
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {

        }
    }
}