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

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.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.StartGK;

import net.sf.json.JSONObject;

public class StartGK {
	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)  {
        StartGK wcmStart=new StartGK();
        try {
            String channelId;// wcm中的channelId
    		String channelIdFor;// 海云中的channelId
    		List<Map<String, Object>> listmap = new ArrayList<>();
    		listmap = wcm.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();
                    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.GetAllGKDocInfoFromOldDB(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("DOCTITLE").toString();
                    oPostData.put("DOCTYPE",CMSConstants.CONTENT_BODY_HTML);
                    
                    //idxID-必填
                    if (map.get("IDXID") != null) {
                    	oPostData.put("oldidxid", map.get("IDXID"));//旧索引号
                        oPostData.put("IDXID", map.get("IDXID"));
                    }
                    //标题-必填
                    if (map.get("TITLE") != null) {
                        oPostData.put("TITLE", map.get("TITLE"));
                    }
                    
					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("description", htmlContent);
					} else {
						oPostData.put("description", "");
					}
                    
                    //文号
                    if (map.get("FILENUM") != null) {
                        oPostData.put("docno", map.get("FILENUM"));
                    }else {
                    	oPostData.put("docno", "");
                    }
                    
                    //主题分类-必填
                    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);
                    		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);
                    		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);
                    		neworg += newthe+",";
                    	}
                    	if(!CMyString.isEmpty(neworg)) {
                    		neworg = neworg.substring(0,neworg.length()-1);
                    		oPostData.put("custcat", neworg);
                    	}
                    }
                    
                    //成文日期
                    if (map.get("MDUPDTIME") != null) {
                    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    	 Date date = sdf.parse(map.get("MDUPDTIME").toString());
                    	 String pubdate = sdf.format(date);
                        oPostData.put("scrq", pubdate);
                    }
                    
                    //生效日期-必填
                    if (map.get("EFECTDATE") != null) {
                    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    	 Date date = sdf.parse(map.get("EFECTDATE").toString());
                    	 String pubdate = sdf.format(date);
                        oPostData.put("efectdat", pubdate);
                    }
                    
                    //发布日期-必填
                    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);
                    }
                    
                    //关键词
                    if (map.get("KEYWORDS") != null) {
                        String keyword = (String) map.get("KEYWORDS");
                        keyword = keyword.replaceAll("<br/>", "");//
                        keyword = keyword.replaceAll("<br>", "");//
                        oPostData.put("keywords", keyword);
                    }
                    
					String docOrder = "";
					if (map.get("DOCORDER") != null) {
						docOrder = map.get("DOCORDER").toString();
					}
                    
                    oPostData.put("olddocid", wcmDocId);
                    
                    //发布机构
                    if (map.get("PUBLISHER") != null) {
                        String PUBLISHER = (String) map.get("PUBLISHER");
                        oPostData.put("Publisher", PUBLISHER);
                    }
                    
					//处理附件
					Map<String, Object> getRelFileInfoByDocId = wcm.GetRelFileInfoByDocId(wcmDocId);
					oPostData.put("docRelFile", getRelFileInfoByDocId.get("docRelFile"));
					oPostData.put("docRelPic", 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),"",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), "", messageInfo);
                                }
                                if(!isSuc){
                                    Log_Exception.Logger_txt("公开错误信息表 "+wcmRecId+" :插入/更新失败！");
                                }
                            }
                        }
                    }catch(Exception e){
						Boolean isSuc=false;
						isSuc = wcm.InsertLogMessageInfo(Integer.valueOf(wcmRecId), "", "网络连接失败");
                        if(!isSuc){
                            Log_Exception.Logger_txt("公开错误信息表 "+wcmRecId+" :插入失败！");
                        }
						e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            Log_Exception.Error_txt("公开DataExchangeByChannel方法异常！"+e.getMessage());
        }
    }

}
