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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.trs.cms.CMSConstants;
import com.trs.infra.util.CMyString;
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.wcmhy06_szf.ServiceImplWcm;
import com.trs.web2frame.tool.tyjyh.wcmhy06_szf.StartGKSZF;

import net.sf.json.JSONObject;

public class StartGKSZF {
	private static Map<String, String> classInfoMap ;
	private static ServiceImplWcm wcm=new ServiceImplWcm(); ;
	static {
		try {
			classInfoMap = wcm.queryClassinfoMapping();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    public static void main(String[] args)  {
        StartGKSZF wcmStart=new StartGKSZF();
        try {
            String channelId;// wcm中的channelId
    		String channelIdFor;// 海云中的channelId
    		List<Map<String, Object>> listmap = new ArrayList<>();
    		listmap = wcm.queryChanelRelation();
    		System.out.println("需导栏目数量：" + listmap.size());
//    		wcmStart.DataExchangeByChannel("586", "35584");//迁移数据cm.quetoDocInChannel(channelId);
    		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();
                    wcmStart.DataExchangeByChannel(channelId, channelIdFor);//迁移数据cm.quetoDocInChannel(channelId);//处理引用关系
    			}
    		}
        } catch (Exception e) {
            Log_Exception.Error_txt("公开StartMethord（）方法异常！"+e.getMessage());
        }
	}

    /**
     * 根据新旧栏目对应关系迁移数据
     * @param wcmChannelId
     * @param hyChannelId
     * @param siteId 
     */
    public void DataExchangeByChannel(String wcmChannelId,String hyChannelId){
        Log_Exception.Logger_txt("-------公开Start-------将原栏目id：" + wcmChannelId + "中得数据导入海云平台" + hyChannelId + "---------Start--------");
        String sServiceId = "gov_webdocument";
        String sMethodName = "saveDocumentInOpenData";//自定义视图
        try {
            List<Map<String,Object>> oldMaps=wcm.GetAllSZFGKDocInfoFromOldDB(wcmChannelId," ");
            System.out.println("本栏目总条数"+oldMaps.size());
            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("Title").toString();
                    oPostData.put("DOCTYPE",CMSConstants.CONTENT_BODY_HTML);
                    
                    if (map.get("placekey") != null) {
                    	oPostData.put("placekey", map.get("placekey"));
                    }
                    if (map.get("efectdate") != null) {
                    	oPostData.put("efectdate", map.get("efectdate"));
                    }
                    if (map.get("Description") != null) {
                    	oPostData.put("Description", map.get("Description"));
                    }
                    if (map.get("RidxId") != null) {
                    	oPostData.put("RidxId", map.get("RidxId"));
                    }
                    if (map.get("acesmthd") != null) {
                    	oPostData.put("acesmthd", map.get("acesmthd"));
                    }
                    if (map.get("Rtitle") != null) {
                    	oPostData.put("Rtitle", map.get("Rtitle"));
                    }
                    if (map.get("fileNum") != null) {
                    	oPostData.put("fileNum", map.get("fileNum"));
                    }
                    //关键词
                    if (map.get("Keywords") != null) {
                        String Keywords = (String) map.get("Keywords");
                        Keywords = Keywords.replaceAll("<br/>", "");//
                        Keywords = Keywords.replaceAll("<br>", "");//
                        oPostData.put("Keywords", Keywords);
                    }
                    //idxID-必填
                    if (map.get("idxID") != null) {
                    	oPostData.put("oldidxid", map.get("idxID"));//旧索引号
                        oPostData.put("IDXID", map.get("idxID"));
                    }
                    if (map.get("Abolidate") != null) {
                        oPostData.put("Abolidate", map.get("Abolidate"));
                    }
                    if (map.get("mdUpdTime") != null) {
                        oPostData.put("mdUpdTime", map.get("mdUpdTime"));
                    }
                    if (map.get("PubDate") != null) {
                        oPostData.put("PubDate", map.get("PubDate"));
                    }
                    if (map.get("Publisher") != null) {
                        oPostData.put("Publisher", map.get("Publisher"));
                    }
                    if (map.get("BGXZ") != null) {
                        oPostData.put("BGXZ", map.get("BGXZ"));
                    }
                    if (map.get("ZXZX") != null) {
                        oPostData.put("ZXZX", map.get("ZXZX"));
                    }
                    if (map.get("ZXTS") != null) {
                        oPostData.put("ZXTS", map.get("ZXTS"));
                    }
                    if (map.get("ZXSB") != null) {
                        oPostData.put("ZXSB", map.get("ZXSB"));
                    }
                    if (map.get("ZXCX") != null) {
                        oPostData.put("ZXCX", map.get("ZXCX"));
                    }
                    if (map.get("JGGS") != null) {
                        oPostData.put("JGGS", map.get("JGGS"));
                    }
                    if (map.get("MZ") != null) {
                        oPostData.put("MZ", map.get("MZ"));
                    }
                    if (map.get("ZW") != null) {
                        oPostData.put("ZW", map.get("ZW"));
                    }
                    if (map.get("FGGZ") != null) {
                        oPostData.put("FGGZ", map.get("FGGZ"));
                    }
                    if (map.get("XSDWLJ") != null) {
                        oPostData.put("XSDWLJ", map.get("XSDWLJ"));
                    }
                    if (map.get("XSDWLJ") != null) {
                        oPostData.put("XSDWLJ", map.get("XSDWLJ"));
                    }
                    if (map.get("Rreports") != null) {
                        oPostData.put("Rreports", map.get("Rreports"));
                    }
                    
                    //主题分类-必填
                    if (map.get("subcat") != null&&!map.get("subcat").toString().equals("")) {
                    	String[] split = map.get("subcat").toString().split(",");
                    	String newsubcat = "";
                    	for(String oldthe:split) {
                    		String newthe = classInfoMap.get(oldthe);
                    		if(CMyString.isEmpty(newthe))continue;
                    		newsubcat += newthe+",";
                    	}
                    	if(!CMyString.isEmpty(newsubcat)) {
                    		newsubcat = newsubcat.substring(0,newsubcat.length()-1);
                    		oPostData.put("SUBCAT", newsubcat);
                    	}
                    	
                    }
                    
                    //所属体裁-必填
                    if (map.get("themecat") != null&&!map.get("themecat").toString().equals("")) {
                    	String[] split = map.get("themecat").toString().split(",");
                    	String newthemecat = "";
                    	for(String oldthe:split) {
                    		String newthe = classInfoMap.get(oldthe);
                    		if(CMyString.isEmpty(newthe))continue;
                    		newthemecat += newthe+",";
                    	}
                    	if(!CMyString.isEmpty(newthemecat)) {
                    		newthemecat = newthemecat.substring(0,newthemecat.length()-1);
                    		oPostData.put("themecat", newthemecat);
                    	}
                    }
                    
                    //机构分类
                    if (map.get("organcat") != null&&!map.get("organcat").toString().equals("")) {
                    	String[] split = map.get("organcat").toString().split(",");
                    	String neworg = "";
                    	for(String oldthe:split) {
                    		String newthe = classInfoMap.get(oldthe);
                    		if(CMyString.isEmpty(newthe))continue;
                    		neworg += newthe+",";
                    	}
                    	if(!CMyString.isEmpty(neworg)) {
                    		neworg = neworg.substring(0,neworg.length()-1);
                    		oPostData.put("organcat", neworg);
                    	}
                    }
                    
                    //机构分类
                    if (map.get("newthemecat") != null&&!map.get("newthemecat").toString().equals("")) {
                    	String[] split = map.get("newthemecat").toString().split(",");
                    	String neworg = "";
                    	for(String oldthe:split) {
                    		String newthe = classInfoMap.get(oldthe);
                    		if(CMyString.isEmpty(newthe))continue;
                    		neworg += newthe+",";
                    	}
                    	if(!CMyString.isEmpty(neworg)) {
                    		neworg = neworg.substring(0,neworg.length()-1);
                    		oPostData.put("newthemecat", neworg);
                    	}
                    }
                    
                    
                    if (map.get("ispdffile") != null) {
                    	if("是".equals(map.get("ispdffile").toString())) {
                    		oPostData.put("ispdffile", "1");
                    	}else if("否".equals(map.get("ispdffile").toString())){
                    		oPostData.put("ispdffile", "2");
                    	}else {
                    		oPostData.put("ispdffile", map.get("ispdffile"));
                    	}
                    }
                    
                    //标题-必填
                    if (docTitle != null) {
                        oPostData.put("TITLE", docTitle);
                    }
                    
					if (map.get("Content") != null) {
						String htmlContent = map.get("Content").toString();
						// 处理内容中附件
						String ret_htmlContent = wcm.GetRetHtmlContent(htmlContent);
						if (ret_htmlContent != null && !ret_htmlContent.equals("")) {
							htmlContent = ret_htmlContent;
						}
						oPostData.put("Content", htmlContent);
					} else {
						oPostData.put("Content", "");
					}
                    
                  
                    
//                    //发布日期-必填
//                    if (map.get("PUBDATE") != null) {
//                    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                    	 Date date = sdf.parse(map.get("PUBDATE").toString());
//                    	 String pubdate = sdf.format(date);
//                        oPostData.put("fbrq", pubdate);
//                    }
                    
					String docOrder = "";
					if (map.get("DOCORDER") != null) {
						docOrder = map.get("DOCORDER").toString();
					}
                    
                    oPostData.put("olddocid", wcmDocId);
                    
                    
					//处理附件
					Map<String, Object> getRelFileInfoByDocId = wcm.GetRelFileInfoByDocId(wcmDocId);
					oPostData.put("DOCATTACHFILEFIELD", getRelFileInfoByDocId.get("docRelFile"));
					oPostData.put("DOCATTACHPICFIELD", getRelFileInfoByDocId.get("docRelPic"));

                    //调迁移接口
                    System.out.println(count+"标题:"+wcmRecId+docTitle);
                    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+"条，成功！");
                                JSONObject dataObject=JSONObject.fromObject(rObject.getString("DATA"));
                                String hyRecId=dataObject.getString("RECID");
                                String hyDocId=dataObject.getString("DOCID");
                                
	                            //记录原始文章的docorder
	                            int res = wcm.updateChnldoc(hyRecId,docOrder);
                                if(res<1){
                                    Log_Exception.Logger_txt("公开chnldoc更新失败,海云recid:"+hyRecId+",wcm排序字段:"+docOrder);
                                }
                                
                                Map<String,Object> resultMap=new HashMap<>();
                                resultMap=wcm.GetResultInfo(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),"gk",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), "gk", messageInfo);
                                }
                                if(!isSuc){
                                    Log_Exception.Logger_txt("公开错误信息表 "+wcmRecId+" :插入/更新失败！");
                                }
                            }
                        }
                    }catch(Exception e){
						Boolean isSuc=false;
						isSuc = wcm.InsertLogMessageInfo(Integer.valueOf(wcmRecId), "gk", "网络连接失败");
                        if(!isSuc){
                            Log_Exception.Logger_txt("公开错误信息表 "+wcmRecId+" :插入失败！");
                        }
						e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            Log_Exception.Error_txt("公开DataExchangeByChannel方法异常！"+e.getMessage());
        }
    }

}
