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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.trs.cms.CMSConstants;
import com.trs.web2frame.WCMServiceCaller;
import com.trs.web2frame.dispatch.Dispatch;
import com.trs.web2frame.tool.tyjyh.FujianUtil;
import com.trs.web2frame.tool.tyjyh.wcmhy02.si.WCMUtilInterface02;
import com.trs.web2frame.tool.tyjyh.wcmhy02.si.ZWuplod;
import com.trs.web2frame.util.Annex;
import com.trs.web2frame.util.Interface;
import com.trs.web2frame.util.Log_Exception;
import com.trs.web2frame.util.Util;
import com.trs.web2frame.util.Annex.HandleResult;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import net.sf.json.JSONObject;

public class StartNewsWCMDataExchange {
	public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");// 设置日期格式

	public static void main(String[] args) {
		StartNewsWCMDataExchange wcm = new StartNewsWCMDataExchange();
		// 配置附件信息
		FujianUtil fj = new FujianUtil();
		// fj.root1="http://192.156.41.118:8081/fagaiwei/WCMData/";//附件的网络地址
		// fj.root2="F:\\市政府\\附件\\TRS2019120401\\TRS\\TRSWCMV7\\WCMData/";//附件的本地地址（要改成自己本地的附件文件夹）

		wcm.StartMethord();
	}

	public void StartMethord() {
		ServiceImplWcm02 wcmSTest = new ServiceImplWcm02();
		StartNewsWCMDataExchange wcm = new StartNewsWCMDataExchange();
		try {
			String channelId;// wcm中的channelId
			String channelIdFor;// 海云中的channelId
			List<Map<String, Object>> listmap = new ArrayList<>();
			listmap = wcmSTest.queryChanelRelation();// 获取新老栏目对应关系
			System.out.println("需导栏目数量：" + listmap.size());
			for (Map<String, Object> map : listmap) {
				if (map.get("oldchanelid") != null && map.get("newchanelid") != null) {
					channelId = map.get("oldchanelid").toString();
					channelIdFor = map.get("newchanelid").toString();
					long startTime = Util.fromDateStringToLong(df.format(new Date()));

					// 第一步，迁移数据；第二步，处理引用关系；第三步，调整顺序；（注意：要按照步骤顺序去运行程序）
					wcm.DataExchangeByChannel(channelId, channelIdFor);// 迁移数据

					// wcm.quetoDocInChannel(channelId);//处理引用关系

					// wcm.ChangeDocOrder(channelId);//调序

					long stopTime = Util.fromDateStringToLong(df.format(new Date()));
					// 计算时间差,单位毫秒
					long timeSpan_temp = stopTime - startTime;
//					Log_Exception.Run_txt("处理完成，总时间为（毫秒）：" + timeSpan_temp);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
			Log_Exception.Error_txt("StartMethord（）方法异常！" + e.getMessage());
		}

	}

	/**
	 * 根据新旧栏目对应关系迁移数据
	 * 
	 * @param wcmChannelId
	 * @param hyChannelId
	 */
	public static long quetoTotalTime = 0;
	public static int quetoTotalCount = 0;

	public void DataExchangeByChannel(String wcmChannelId, String hyChannelId) {
		Log_Exception.Logger_txt(
				"-------Start-------将原栏目id：" + wcmChannelId + "中得数据导入海云平台" + hyChannelId + "---------Start--------");
		String sServiceId = "gov_webdocument";
		String sMethodName = "saveDocumentInOpenData";// 自定义视图
		ServiceImplWcm02 wcm = new ServiceImplWcm02();
		WCMUtilInterface02 wcmUtil = new WCMUtilInterface02();
		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", hyChannelId);// 目标栏目id
					oPostData.put("CurrUserName", "test1");
					String wcmRecId = map.get("RECID").toString();// 文档记录Id
					String wcmDocId = map.get("DOCID").toString();// 文档ID
					String Model = map.get("MODAL").toString();// 引用类型 1：本身/复制 2：链接 3：镜像
					String docTitle = "";
					docTitle = map.get("DOCTITLE").toString();
					if (map.get("DOCTYPE") != null) {
						oPostData.put("DOCTYPE", map.get("DOCTYPE"));// 判断如果是文件类型文档
						if (map.get("DOCTYPE").toString().equals("40")) {
							String docPubUrl = map.get("DOCPUBURL") != null ? map.get("DOCPUBURL").toString() : "";
							String filename = docPubUrl.substring(docPubUrl.lastIndexOf("/") + 1, docPubUrl.length());
							String final_file = FujianUtil.getLocalFullPathDownload(filename);// 拼接后的数据,运行代码前需要配置路径
							if (!final_file.equals("")) {
								Dispatch oDispatch = WCMServiceCaller.UploadFile(final_file);
								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);
								}
							}

						}

					} else {
						oPostData.put("DOCTYPE", CMSConstants.CONTENT_BODY_HTML);
					}
					if (map.get("SUBDOCTITLE") != null) {
						oPostData.put("ShortTitle", map.get("SUBDOCTITLE"));
						oPostData.put("SUBDOCTITLE", map.get("SUBDOCTITLE"));
					}
					if (map.get("DOCKEYWORDS") != null) {
						String keyword = (String) map.get("DOCKEYWORDS");
						keyword = keyword.replaceAll("<br/>", "");//
						keyword = keyword.replaceAll("<br>", "");//
						oPostData.put("DOCKEYWORDS", keyword);
					}

					if (map.get("DOCPEOPLE") != null) {
						oPostData.put("DOCPEOPLE", map.get("DOCPEOPLE"));
					}
					if (map.get("DOCSOURCENAME") != null) {
						oPostData.put("DOCSOURCENAME", map.get("DOCSOURCENAME"));
					}
					if (map.get("DOCAUTHOR") != null) {
						oPostData.put("DOCAUTHOR", map.get("DOCAUTHOR"));
					}
					if (map.get("DOCPUBTIME") != null) {
						oPostData.put("DOCPUBTIME", map.get("DOCPUBTIME"));
					}
					if (map.get("DOCRELTIME") != null) {
						oPostData.put("DOCRELTIME", map.get("DOCRELTIME"));
					}
					if (map.get("DOCABSTRACT") != null) {
						oPostData.put("DOCABSTRACT", map.get("DOCABSTRACT"));
					}
					if (map.get("DOCCONTENT") != null) {
						oPostData.put("DOCCONTENT", map.get("DOCCONTENT"));
					} else {
						oPostData.put("DOCCONTENT", "");
					}
					if (map.get("DOCLINK") != null) {
						oPostData.put("DOCLINK", map.get("DOCLINK"));
					}

					// 内容中图片和附件需要特殊处理
					if (map.get("DOCHTMLCON") != null) {
						String htmlContent = map.get("DOCHTMLCON").toString();

						// 处理 正文图片
						String pcontent = ZWuplod.contentResourceUpload(htmlContent, 5, "(src=\").*?(\")",
								docTitle.toString(), wcmDocId);
						// 处理 正文附件
						String fcontent = ZWuplod.contentResourceUpload(pcontent, 6, "(href=\").*?(\")",
								docTitle.toString(), wcmDocId);

						// 处理内容中附件
						String ret_htmlContent = wcmUtil.GetRetHtmlContent(htmlContent);
						if (ret_htmlContent != null && !ret_htmlContent.equals("")) {
							htmlContent = ret_htmlContent;
						}

						oPostData.put("DOCHTMLCON", htmlContent);
					} else {
						oPostData.put("DocHtmlCon", "");
						oPostData.put("DOCCONTENT", "");
					}
					// 获取文档相关的附件信息
					Map<String, Object> fileMap = wcmUtil.GetRelFileInfoByDocId(wcmDocId);
					if (fileMap != null) {
						// 默认视图
						// if(fileMap.get("docRelFile")!=null){
						// oPostData.put("docRelFile", fileMap.get("docRelFile"));
						// }
						// if(fileMap.get("DocRelPic")!=null){
						// oPostData.put("DocRelPic", fileMap.get("DocRelPic"));
						// }

						// 自定义视图
						if (fileMap.get("DOCATTACHFILEFIELD") != null) {
							oPostData.put("DOCATTACHFILEFIELD", fileMap.get("DOCATTACHFILEFIELD"));
						}
						if (fileMap.get("DOCATTACHPICFIELD") != null) {
							oPostData.put("DOCATTACHPICFIELD", fileMap.get("DOCATTACHPICFIELD"));
						}

					}
					// //获取相关文档信息（仅限于默认采编页面）
					// String docRelNews=wcmUtil.GetDocRelNewsInfo(wcmDocId);
					// if(!docRelNews.equals("")){
					// oPostData.put("DocRelation", docRelNews);//
					// }
					if (Model.equals("1")) {
						if (map.get("DOCTITLE") != null) {
							docTitle = map.get("DOCTITLE").toString();
							oPostData.put("DocTitle", docTitle);
						} else {
							docTitle = "空标题" + wcmRecId;
							oPostData.put("DocTitle", "空标题" + wcmRecId);
							oPostData.put("DOCTYPE", "20");
							oPostData.put("DOCHTMLCON", "空内容");
							oPostData.put("DOCCONTENT", "空内容");
						}

					} else {
						if (map.get("DOCTITLE") != null) {
							docTitle = map.get("DOCTITLE").toString();
						}
						oPostData.put("DocTitle", docTitle + "-占位引用标题");
					}
					// 调迁移接口
					long startTime = Util.fromDateStringToLong(df.format(new Date()));
					Dispatch result = WCMServiceCaller.Call(sServiceId, sMethodName, oPostData, true);
					long stopTime = Util.fromDateStringToLong(df.format(new Date()));
					count++;

					if (result != null) {
						JSONObject rObject = JSONObject.fromObject(result.getResponseText().toString());
						if (rObject.get("ISSUCCESS").toString().equals("true")) {
							quetoTotalCount++;
							long timeSpan_temp = stopTime - startTime;
							quetoTotalTime = quetoTotalTime + timeSpan_temp;
							if (quetoTotalCount == 1000) {
//								Log_Exception.Run_txt("saveDocumentInOpenData迁移数据接口处理1000条数据共花时间（毫秒）为：" + quetoTotalTime);
							}
							System.out.println("迁移第" + count + "条，成功！");
							JSONObject dataObject = JSONObject.fromObject(rObject.getString("DATA"));
							String hyRecId = dataObject.getString("RECID");
							Map<String, Object> resultMap = new HashMap<>();
							resultMap = wcm.GetResultInfo(Integer.valueOf(wcmRecId));
							// 存在更新，不存在插入
							if (resultMap != null && resultMap.size() > 0) {
								String hyrecid = resultMap.get("hyrecid").toString();
								String zwrecid = resultMap.get("zwrecid").toString();
								Boolean isSuc = false;
								if (Model.equals("1")) {
									isSuc = wcm.UpdateResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId),
											Integer.valueOf(zwrecid));// 如果是本身，替换海云字段
								} else {
									isSuc = wcm.UpdateResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyrecid),
											Integer.valueOf(hyRecId));// 如果不是本身，替换占位字段
								}

								if (!isSuc) {
									Log_Exception.Logger_txt("结果表 " + wcmRecId + " :更新失败！");
								}
							} else {
								Boolean isSuc = false;
								if (Model.equals("1")) {
									isSuc = wcm.InsertResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId), 0);// 如果是本身，只插入海云字段
								} else {
									isSuc = wcm.InsertResult(Integer.valueOf(wcmRecId), 0, Integer.valueOf(hyRecId));// 如果不是本身，替换占位字段
								}

								if (!isSuc) {
									Log_Exception.Logger_txt("结果表 " + wcmRecId + " :插入失败！");
								}

							}
						} else {
							System.out.println("迁移第" + count + "条，失败！");
							String messageInfo = rObject.getString("MSG");
							Log_Exception
									.Logger_txt("失败！RecID：" + wcmRecId + " 标题：" + docTitle + "错误信息：" + messageInfo);

							// 记录文档失败信息
							Boolean isSuc = false;
							Map<String, Object> Messagemap = wcm.GetLogMessageInfo(Integer.valueOf(wcmRecId));
							if (Messagemap != null && Messagemap.size() > 0) {
								isSuc = wcm.UpdateLogMessageInfo(Integer.valueOf(wcmRecId), messageInfo);
							} else {
								isSuc = wcm.InsertLogMessageInfo(Integer.valueOf(wcmRecId), docTitle, messageInfo);
							}
							if (!isSuc) {
								Log_Exception.Logger_txt("错误信息表 " + wcmRecId + " :插入/更新失败！");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log_Exception.Error_txt("DataExchangeByChannel方法异常！" + e.getMessage());
		}
	}

	/**
	 * 引用该栏目下所有需要被引用的文档
	 * 
	 * @param channelId
	 */
	public void quetoDocInChannel(String channelId) {
		Log_Exception.Logger_txt("-------Start-------处理原栏目id：" + channelId + "中数据引用关系---------Start--------");
		ServiceImplWcm02 wcm = new ServiceImplWcm02();
		WCMUtilInterface02 wcmUtil = new WCMUtilInterface02();
		try {
			// 获取该栏目下需要被引用的文档
			List<Map<String, Object>> listMap = wcm.GetAllDocNeedQueto(channelId);
			if (listMap != null) {
//				Log_Exception.Run_txt("共计需处理引用数据条数为：" + listMap.size());
			}
			for (Map<String, Object> map : listMap) {
				String WCM_RECID = "";
				String WCM_DOCID = "";
				String HY_newchanelid = "";
				String HY_RECID = "";
				String hyrecid = "";
				String WCM_MODAL = "";
				String WCM_DOCTITLE = "";// 查出原库中的标题，原因是根据引用返回的docTitle信息不完整
				if (map.get("WCM_RECID") != null && !map.get("WCM_RECID").equals("0")) {
					WCM_RECID = map.get("WCM_RECID").toString();
				}
				if (map.get("WCM_DOCID") != null && !map.get("WCM_DOCID").equals("0")) {
					WCM_DOCID = map.get("WCM_DOCID").toString();
				}
				if (map.get("HY_newchanelid") != null && !map.get("HY_newchanelid").equals("0")) {
					HY_newchanelid = map.get("HY_newchanelid").toString();
					// HY_newchanelid=wcm.GetNewChannelId(HY_newchanelid);//获取最新关系
				}
				if (map.get("WCM_MODAL") != null) {
					WCM_MODAL = map.get("WCM_MODAL").toString();
				}
				if (map.get("WCM_DOCTITLE") != null) {
					WCM_DOCTITLE = map.get("WCM_DOCTITLE").toString();
				}
				if (!WCM_DOCID.equals("")) {
					HY_RECID = wcm.GetHyRecId(WCM_DOCID);
					if (HY_RECID != null && !HY_RECID.equals("0") && HY_newchanelid != null
							&& !HY_newchanelid.equals("0")) {
						hyrecid = wcmUtil.quoteToAndGetRecId(WCM_MODAL, HY_RECID, HY_newchanelid, WCM_DOCTITLE);// 获取镜像后的文档的RECID
						if (hyrecid != null && !hyrecid.equals("")) {
							Boolean isSuc = wcm.Updatehyrecid(Integer.valueOf(WCM_RECID), Integer.valueOf(hyrecid));
							if (!isSuc) {
								Log_Exception.Logger_txt(
										"向结果表中更新镜像后的文档的RECID失败！WCM_RECID：" + WCM_RECID + " hyrecid:" + hyrecid);
							}
						} else {
							Log_Exception.Logger_txt("获取镜像后的文档的RECID失败！WCM_RECID：" + WCM_RECID + " hyrecid:" + hyrecid);
						}
					}
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			Log_Exception.Error_txt("quetoDocInChannel方法异常！" + e.getMessage());
		}
	}

	/**
	 * 调整该栏目下的顺序
	 * 
	 * @param channelId
	 */
	public void ChangeDocOrder(String channelId) {
		Log_Exception.Logger_txt("-------Start-------调序：处理原栏目id：" + channelId + "中的数据---------Start--------");
		List<Map<String, Object>> listMap = new ArrayList<>();
		ServiceImplWcm02 wcm = new ServiceImplWcm02();
		WCMUtilInterface02 wcmUtil = new WCMUtilInterface02();
		try {
			listMap = wcm.GetDocsNeedChangeOrder(channelId);
			if (listMap != null) {
				for (Map<String, Object> map : listMap) {
					String HY_newchanelid = "";
					String hyrecid = "";
					String zwrecid = "";
					boolean isSuc = false;
					if (map.get("HY_newchanelid") != null && !map.get("HY_newchanelid").equals("0")) {
						HY_newchanelid = map.get("HY_newchanelid").toString();
						// HY_newchanelid=wcm.GetNewChannelId(HY_newchanelid);
					}
					if (map.get("hyrecid") != null && !map.get("hyrecid").equals("0")) {
						hyrecid = map.get("hyrecid").toString();
					}
					if (map.get("zwrecid") != null && !map.get("zwrecid").equals("0")) {
						zwrecid = map.get("zwrecid").toString();
					}
					if (!HY_newchanelid.equals("") && !hyrecid.equals("") && !zwrecid.equals("")) {
						isSuc = wcmUtil.changeOrder(HY_newchanelid, hyrecid, zwrecid);

					}
					if (!isSuc) {
						Log_Exception.Logger_txt("WCMRECID" + map.get("WCM_RECID").toString() + "调序失败！");
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log_Exception.Logger_txt("ChangeDocOrder()方法异常！" + e.getMessage());
		}

	}

}