package com.trs.exchange.metadata;

import java.util.ArrayList;
import java.util.List;

import com.trs.DreamFactory;
import com.trs.TRSWCMBaseTest;
import com.trs.cms.CMSConstants;
import com.trs.cms.content.CMSObj;
import com.trs.components.metadata.center.MetaViewData;
import com.trs.components.metadata.definition.MetaView;
import com.trs.components.wcm.content.domain.AppendixMgr;
import com.trs.components.wcm.content.persistent.Appendix;
import com.trs.components.wcm.content.persistent.Channel;
import com.trs.gov.common.log.MetaDataLog;
import com.trs.gov.editorcenter.document.IGovDocumentMgr;
import com.trs.gov.editorcenter.extVersion.ExtObjectVersionMgr;
import com.trs.gov.metadata.GovMetaDataConstants;
import com.trs.infra.common.WCMException;
import com.trs.infra.persistent.db.DBManager;
import com.trs.infra.util.CMyDateTime;
import com.trs.infra.util.CMyException;

public class MetaDataExchangeTest extends TRSWCMBaseTest {
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
			.getLogger(MetaDataExchangeTest.class);

	/**
	 * 测试数据入库默认的栏目ID
	 */
	private int m_nChannelIdForTest = 12;

	private AppendixMgr m_oAppendixMgr = (AppendixMgr) DreamFactory
			.createObjectById("AppendixMgr");

	private IGovDocumentMgr m_oGovDocumentMgr = (IGovDocumentMgr) DreamFactory
			.createObjectById("IGovDocumentMgr");

	private ExtObjectVersionMgr m_oVersionMgr = (ExtObjectVersionMgr) DreamFactory
			.createObjectById("ExtObjectVersionMgr");

	/**
	 * 保存一篇最简单的网站文章
	 */
	public void testSaveNews() {
		try {
			MetaViewData oMetaData = saveGovNews();
			assertNotNull("网站资讯入库失败？", oMetaData);
		} catch (Exception ex) {
			logger.error("测试[testSaveMetaViewData]出现异常！", ex);
			fail("测试[testSaveMetaViewData]出现异常！\n"
					+ CMyException.getStackTraceText(ex));
		}

	}

	/**
	 * 保存一篇带有附件的网站文章
	 */
	public void testSaveNewsContainsAppendix() {
		try {
			// 1 保存文章
			MetaViewData oMetaData = saveGovNews();
			assertNotNull("网站资讯入库失败？", oMetaData);

			// 2 保存附件
			dowithAppendix(oMetaData, Appendix.FLAG_DOCPIC);
			dowithAppendix(oMetaData, Appendix.FLAG_DOCAPD);

			// 3 处理文章缩略图信息：Thumbfiles
			m_oGovDocumentMgr.updateThumbAndAttachField(oMetaData);

			// 4 保存版本，如果稿件太多，建议将这个环节注释掉
			MetaDataLog oMetaDataLog = creatLog(oMetaData);
			// 保存稿件版本
			m_oVersionMgr.buildVersion(oMetaData, oMetaDataLog);
			// 新建要将稿件版本修改为流程版本
			m_oVersionMgr.updateProcess(m_oLoginUser.getName(),
					oMetaData.getId());

		} catch (Exception ex) {
			logger.error("测试[testSaveNewsContainsAppendix]出现异常！", ex);
			fail("测试[testSaveNewsContainsAppendix]出现异常！\n"
					+ CMyException.getStackTraceText(ex));
		}

	}
	
	private MetaViewData saveGovNews() throws Exception, WCMException {
		DBManager dbMgrForWCM = DBManager.getDBManager();

		// 0 定义目标视图、目标栏目
		MetaView view = GovMetaDataConstants.findGovNewsView();

		Channel channel = Channel.findById(m_nChannelIdForTest);
		assertNotNull("指定栏目【" + m_nChannelIdForTest + "】不存在！", channel);

		// 1 产生新的元数据
		MetaViewData oMetaData = new MetaViewData(view);

		// 2 读取数据设置属性，这里用硬代码示例
		int nFromType = 711, nSrcId = 1008; // 原始数据的类型（比如约定711表示来自于财政局）和ID
		oMetaData.setProperty("FromType", nFromType);
		oMetaData.setProperty("FromId", String.valueOf(nSrcId));

		oMetaData.setProperty("DocType", CMSConstants.CONTENT_BODY_HTML);
		oMetaData.setProperty("ChannelId", m_nChannelIdForTest);

		oMetaData.setPropertyWithString("DocTitle", "测试一下数据迁移框架是否可用"); // 标题

		String sHTMLContent = "<DIV class=\"TRS_UEDITOR TRS_WEB\">"//
				+ "<BR>大发打发第三方打发第三方大法师<B>dafdsf</B><P>测试中文</P>" + "</DIV>";// 系统要求图文混排内容都要包一个DIV
		oMetaData.setPropertyWithString("DocHTMLCon", sHTMLContent); // 正文
		oMetaData.setProperty("DocContent", "大发打发第三方打发第三方大法师dafdsf\n测试中文\n");// 不带格式的正文

		oMetaData.setProperty("ShortTitle", "我是首页标题");
		oMetaData.setProperty("SUBDOCTITLE", "我是副标题");
		oMetaData.setProperty("DOCSOURCENAME", "我是来源");
		oMetaData.setProperty("DocAbstract", "我是摘要\n第二段文字");

		// 3 入库保存
		oMetaData.save(m_oLoginUser);
		if (oMetaData.getDocument() == null) {
			throw new WCMException(
					"Fail to save metaviewdata![SrcId=" + nSrcId + "]");
		}
		// 4 更新DocOutupId
		dbMgrForWCM.sqlExecuteUpdate(
				new String[] {
						"update WCMDocument set DocOutupId=? where DocId=?" },
				new int[] { nSrcId, oMetaData.getDocumentId() });
		return oMetaData;
	}

	private void dowithAppendix(MetaViewData _oMetaViewData, int _nAppendixFlag)
			throws WCMException {
		// 1 从原始库获取对应文档的附件，然后传到WCMData/Upload所在目录中
		String[] pAppendixFile = { "U020170817494109015293.jpeg",
				"U020170817494938975762.jpg" };

		// 2 产生将要保存的附件对象
		int nSize = pAppendixFile.length;
		List<CMSObj> nAppendixs = new ArrayList<>(nSize);
		for (int i = 0; i < nSize; i++) {
			Appendix appendix = Appendix.createNewInstance();

			appendix.setFile(pAppendixFile[i]);
			appendix.setDesc("附件说明" + i);

			appendix.setDocId(_oMetaViewData.getMetaDataId());
			appendix.setFlag(_nAppendixFlag);
			appendix.setProperty("APPSERN", i + 1);
			nAppendixs.add(appendix);
		}

		// 3 处理指定类型的附件
		m_oAppendixMgr.saveAppendixes(_oMetaViewData.getDocument(), nAppendixs,
				_nAppendixFlag);
	}
	
	private MetaDataLog creatLog(MetaViewData _oMetaData) throws WCMException {
		MetaDataLog oMetaDataLog = MetaDataLog.createNewInstance();
		oMetaDataLog.setDesChnlId(m_nChannelIdForTest);
		oMetaDataLog.setDesDept("");
		oMetaDataLog.setDesGroupId(0);
		oMetaDataLog.setDesUser(m_sCurrUserName);
		
		oMetaDataLog.setOperTime(CMyDateTime.now());
		oMetaDataLog.setOperDesc(
				"迁移数据【" + _oMetaData + "】【" + _oMetaData.getDocument() + "】");
		return oMetaDataLog;
	}


}
