package com.trs.web2frame.tool.tyjyh.wcmhy03rs_yb.wz;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.wcmhy03rs_yb.WCMUtilInterface;
import com.trs.web2frame.util.Log_Exception;

import net.sf.json.JSONObject;

public class StartWCMDataExchange {

    public static void main(String[] args) {
//    	Dispatch oDispatch = WCMServiceCaller.UploadFile("D:\\download\\rsb\\temp\\W020190704600316404555.jpg");
//    	System.out.println(oDispatch.getUploadShowName());
    	StartWCMDataExchange wcm=new StartWCMDataExchange();
        wcm.StartMethord();
    }

    public void StartMethord() {
    	ServiceImplWcm wcmSTest=new ServiceImplWcm();
        StartWCMDataExchange wcm=new StartWCMDataExchange();
        try {
            String channelId;// wcm中的channelId
			String channelIdFor;// 海云中的channelId
			String siteId="8";//医保局 wcm中需要迁移的siteId
//			String siteId="4";//人社局 wcm中需要迁移的siteId
			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();
	                wcm.DataExchangeByChannel(channelId, channelIdFor,siteId);
				}
			}
        } catch (Exception e) {
            Log_Exception.Error_txt("StartMethord()方法异常！"+e.getMessage());
        }
		
	}

    /**
     * 根据新旧栏目对应关系迁移数据
     * @param wcmChannelId
     * @param hyChannelId
     * @param siteId 
     */
    public void DataExchangeByChannel(String wcmChannelId,String hyChannelId, String siteId){
        Log_Exception.Logger_txt("-------Start-------将原栏目id：" + wcmChannelId + "中得数据导入海云平台" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInWeb";//自定义视图
        ServiceImplWcm wcm=new ServiceImplWcm();
        WCMUtilInterface wcmUtil=new WCMUtilInterface();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            
            List<Map<String,Object>> oldMaps=wcm.GetAllDocInfoFromOldDB(wcmChannelId,siteId);//// ?2、为什么要加condition条件
            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");
                    String wcmRecId=map.get("RECID").toString();//文档记录Id
                    String wcmDocId=map.get("DOCID").toString();//文档ID
                    String docTitle=map.get("DOCTITLE").toString();
                    if(map.get("DOCTYPE")!=null){
                        oPostData.put("DOCTYPE", map.get("DOCTYPE"));//判断如果是文件类型文档
                        if(map.get("DOCTYPE").toString().equals("40")){
                        	String filename = map.get("DOCFILENAME").toString();
                        	String final_file = FujianUtil.getLocalFullPathDownloadFiles(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\":\""+docTitle+"\",\"OTHEROPERATION\":0 }";
		                            DOCFILE+="]";
		                            oPostData.put("DocFileName",docfilename);
		                            oPostData.put("DOCFILE",DOCFILE);
								}
							}
                        }
                    }else{
                        oPostData.put("DOCTYPE",CMSConstants.CONTENT_BODY_HTML);
                    }
                    //标题-必填
                    if (map.get("DOCTITLE") != null) {
                        oPostData.put("DOCTITLE", map.get("DOCTITLE"));
                    }
                    
                    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("DOCRELTIME") != null) {
						oPostData.put("DOCRELTIME", map.get("DOCRELTIME"));
					}
					if (map.get("CRTIME") != null) {
						oPostData.put("CRTIME", map.get("CRTIME"));
					}
					if (map.get("DOCABSTRACT") != null) {
						oPostData.put("DOCABSTRACT", map.get("DOCABSTRACT"));
					}
					if (map.get("DOCLINK") != null) {
						oPostData.put("DOCLINK", map.get("DOCLINK"));
					}
					
					if (map.get("DOCCONTENT") != null) {
						oPostData.put("DOCCONTENT", map.get("DOCCONTENT"));
					}
					
					oPostData.put("oldDocid", wcmDocId);
					
					//处理附件
					Map<String, Object> getRelFileInfoByDocId = wcmUtil.GetRelFileInfoByDocId(wcmDocId);
					oPostData.put("docRelFile", getRelFileInfoByDocId.get("docRelFile"));
					oPostData.put("docRelPic", getRelFileInfoByDocId.get("docRelPic"));
					
					// 内容中图片和附件需要特殊处理
					if (map.get("DOCHTMLCON") != null) {
						String htmlContent = map.get("DOCHTMLCON").toString();
						// 处理内容中附件
						String ret_htmlContent = wcmUtil.GetRetHtmlContent(htmlContent);
						ret_htmlContent = wcmUtil.GetRetHtmlContentAppendix(ret_htmlContent);
						if (ret_htmlContent != null && !ret_htmlContent.equals("")) {
							htmlContent = ret_htmlContent;
						}

						oPostData.put("DOCHTMLCON", htmlContent);
					} else {
						oPostData.put("DocHtmlCon", "");
						oPostData.put("DOCCONTENT", "");
					}
					
					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+"条，成功！wcmRecId:"+wcmRecId+";wcmdocid:"+wcmDocId);
	                            JSONObject dataObject=JSONObject.fromObject(rObject.getString("DATA"));
	                            String hyRecId=dataObject.getString("RECID");
	                            String hyDocId=dataObject.getString("DOCID");
	                            Map<String,Object> resultMap=new HashMap<>();
	                            resultMap=wcm.GetResultInfo(Integer.valueOf(wcmRecId));//
	                            
	                            //存在更新，不存在插入
	                            if(resultMap!=null&&resultMap.size()>0){
	                                Boolean isSuc=false;
	                                isSuc=wcm.UpdateResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId), Integer.valueOf(wcmDocId),Integer.valueOf(hyDocId));
	                                if(!isSuc){
	                                    Log_Exception.Logger_txt("结果表 "+wcmRecId+" :更新失败！");
	                                }
	                            }else{
	                                Boolean isSuc=false;
	                                isSuc=wcm.InsertResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId), Integer.valueOf(wcmDocId),Integer.valueOf(hyDocId),map.get("DOCTITLE").toString(),map.get("CRTIME").toString());
	                                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) {
						e.printStackTrace();
					}

                }
            }
        } catch (Exception e) {
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {

        }
    }
    
}