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

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

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.util.Log_Exception;

import net.sf.json.JSONObject;

public class StartWCMDataExchange {

public static ServiceImplWcm01 si=new ServiceImplWcm01();
    public static void main(String[] args) {
    	StartWCMDataExchange wcm=new StartWCMDataExchange();
        //配置附件信息
        FujianUtil fj=new FujianUtil();
        wcm.StartMethord();
    }

    
    public void StartMethord() {
    	ServiceImplWcm01 wcmSTest=new ServiceImplWcm01();
        StartWCMDataExchange wcm=new StartWCMDataExchange();
        try {
            String channelId;// wcm中的channelId
		String channelIdFor;// 海云中的channelId
		List<Map<String, Object>> listmap = new ArrayList<>();
		listmap = wcmSTest.queryChanelRelation();
		System.out.println("需导栏目数量：" + listmap.size());
//		wcm.DataExchangeByChannel("57", "56021",1193,1383,1293);//天津市住房公积金管理中心

		
//		wcm.ChangeDocOrder("56129");//调序
//		wcm.DataExchangeByChannel("106", "53901");
		 
		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);//迁移数据cm.quetoDocInChannel(channelId);//处理引用关系
                //wcm.ChangeDocOrder(channelId);//调序
			}
			
		}
        } catch (Exception e) {
            //TODO: handle exception
            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";//自定义视图
        ServiceImplWcm01 wcm=new ServiceImplWcm01();
        WCMUtilInterface01 wcmUtil=new WCMUtilInterface01();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            
            List<Map<String,Object>> oldMaps=wcm.GetAllDocInfoFromOldDB(wcmChannelId);//// ?2、为什么要加condition条件
            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 Model=map.get("MODAL").toString();//引用类型 1：本身/复制  2：链接  3：镜像
                    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 docfilename = map.get("DOCSOURCENAME").toString();
                            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("DOCABSTRACT") != null) {
						oPostData.put("DOCABSTRACT", map.get("DOCABSTRACT"));
					}
					if (map.get("DOCLINK") != null) {
						oPostData.put("DOCLINK", map.get("DOCLINK"));
					}
					
					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();
						if(htmlContent.contains("在另外数据表中"))continue;
//						oPostData.put("DOCHTMLCON", "中国人<a oldsrc=\"W020190805330389250857.jpg\" href=\"/webpic/W0201908/W020190805/W020190805330389250857.jpg\">新建 Microsoft Excel 工作表.xlsx</a>");
						// 处理内容中附件
						String ret_htmlContent = wcmUtil.GetRetHtmlContentIgnore(htmlContent);
						if (ret_htmlContent != null && !ret_htmlContent.equals("")) {
							htmlContent = ret_htmlContent;
						}
						oPostData.put("DOCHTMLCON", htmlContent);
					} else {
						oPostData.put("DocHtmlCon", "");
						oPostData.put("DOCCONTENT", "");
					}
                    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));//
                            
                            //插入sql
                            String htmlContent = map.get("DOCHTMLCON").toString();
                            wcmUtil.GetRetHtmlContentSql(htmlContent,hyDocId);
                            
                            //存在更新，不存在插入
                            if(resultMap!=null&&resultMap.size()>0){
                                String hyrecid=resultMap.get("hyrecid").toString();
                                String zwrecid=resultMap.get("zwrecid").toString();
                                Boolean isSuc=false;
                                isSuc=wcm.UpdateResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId), Integer.valueOf(zwrecid));//如果是本身，替换海云字段
                                if(!isSuc){
                                    Log_Exception.Logger_txt("结果表 "+wcmRecId+" :更新失败！");
                                }
                            }else{
                                Boolean isSuc=false;
                                isSuc=wcm.InsertResult(Integer.valueOf(wcmRecId), Integer.valueOf(hyRecId), 0,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) {
            //TODO: handle exception
            Log_Exception.Error_txt("DataExchangeByChannel方法异常！"+e.getMessage());
        } finally {

        }
    }

    /**
     * 引用该栏目下所有需要被引用的文档
     * @param channelId
     */
    public void quetoDocInChannel(String channelId){
        Log_Exception.Logger_txt("-------Start-------处理原栏目id：" + channelId + "中数据引用关系---------Start--------");
        ServiceImplWcm01 wcm=new ServiceImplWcm01();
        WCMUtilInterface01 wcmUtil=new WCMUtilInterface01();
        try {
            //获取该栏目下需要被引用的文档
            List<Map<String,Object>> listMap=wcm.GetAllDocNeedQueto(channelId);
            for (Map<String,Object> map : listMap) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");// 设置日期格式
                String timeNow1 = df.format(new Date()).toString();
                System.out.println("开始引用"+timeNow1);
                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<>();
        ServiceImplWcm01 wcm=new ServiceImplWcm01();
        WCMUtilInterface01 wcmUtil=new WCMUtilInterface01();
        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());
        }

    }

    /**
	 * 获取分类信息
	 * @param classIds
	 * @return
	 */
	public String getCLassInfo(String classIds){

		ServiceImplWcm01 si=new ServiceImplWcm01();
		String classnewIds="";
		try {
			String[] strArray = null;
			if(classIds!=null&&!classIds.equals("")){
				strArray = classIds.split(",");
				for (int i = 0; i < strArray.length; i++) {
					if(i!=0){
						classnewIds+=",";
					}
					classnewIds+=si.queryClassRelation(strArray[i]);
				}
				return classnewIds;
			}else{
				return "";
			}   
			
		} catch (Exception e) {
			//TODO: handle exception
			return "";
		}
	}

    /**
	 * 获取主题信息
	 * @param classIds
	 * @return
	 */
	public Map<String,Object> getZhuTiCLassInfo(String classIds){

		
		String classnewIds="";
		String classoldIds="";
		try {
			String[] strArray = null;
			Map<String,Object> classInfomap=new HashMap<>();
			if(classIds!=null&&!classIds.equals("")){
				strArray = classIds.split(",");
				for (int i = 0; i < strArray.length; i++) {
					if(i!=0){
						classnewIds+=",";
						classoldIds+=",";
                    }
                    Map<String,Object> mapclass=si.queryZhuTiClassRelation(strArray[i]);
					if(mapclass!=null){
                        String CLASSOLDID =mapclass.get("CLASSOLDID")!=null?mapclass.get("CLASSOLDID").toString():"";
                        String CLASSNEWID=mapclass.get("CLASSNEWID")!=null?mapclass.get("CLASSNEWID").toString():"";

						classoldIds+=si.queryOldNewClass(CLASSOLDID);//获取最新对应分类
						classnewIds+=si.queryOldNewClass(CLASSNEWID);//获取最新对应分类
					}
					
                }
                classoldIds=QuChong(classoldIds);
                classnewIds=QuChong(classnewIds);
				classInfomap.put("classoldIds", classoldIds);//
				classInfomap.put("classnewIds", classnewIds);
				return classInfomap;
			}else{
				return null;
			}   
			
		} catch (Exception e) {
			//TODO: handle exception
			return null;
		}
	}

    /**
     * 
     * @param classType 分类类型  1：文种  2：主题分类
     * @param RecId 
     * @return
     */
    public String GetClassNewIdByRecId(Integer classType, String RecId){
        String classNewId="";
        try {
            if(RecId!=null&&!RecId.equals("")){
                if(classType==1){
                    String classOldId=si.queryWZIDByWCMDocID(RecId);
                    if(classOldId!=null&&!classOldId.equals("")){
                        String[] array_WZ=classOldId.split(",");
                        for (int i = 0; i < array_WZ.length; i++) {
                            String classId=si.queryOldNewClass(array_WZ[i]);
                            classOldId=classOldId.replace(array_WZ[i], classId);
                        }
                        classNewId=classOldId;
                    }
                    
                }else if(classType==2){
                    String classOldId=si.queryBELONGCLASSByWCMDocID(RecId);
                    if(classOldId!=null&&!classOldId.equals("")){
                        String[] array_WZ=classOldId.split(",");
                        for (int i = 0; i < array_WZ.length; i++) {
                            String classId=si.queryOldNewClass(array_WZ[i]);
                            classOldId=classOldId.replace(array_WZ[i], classId);
                        }
                        classNewId=classOldId;
                    }
                }
            }
            return classNewId;
        } catch (Exception e) {
            //TODO: handle exception
            Log_Exception.Logger_txt("GetClassNewIdByRecId()方法异常！"+e.getMessage());
            return null;
        }
    }

    public static String QuChong(String classInfos){
        //String ret_classInfos="";
        try {
            //如果有重复的主题则把重复的去掉
			String[] sa = classInfos.split(",");
			Set<String> ss = new HashSet<String>();
			ss.addAll(Arrays.asList(sa));
			if(sa.length != ss.size()) {
				//有重复的
				String n = "";
				for(String z : ss){
					if("".equals(n)) {
						n = z;
					}else {
						n = n+ ","+z;
					}
				}
				classInfos = n;
            }
        } catch (Exception e) {
            //TODO: handle exception
        }
        return classInfos;
    }
    
}