import java.util.Vector;

import lotus.domino.AgentBase;
import lotus.domino.AgentContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.Session;

/**
* @类名:SaveToPic
* @功能:将本文档中的附件保存到图片库
* @author wnight88
* @时间: 2009-4-10
*/

public class SaveToPic extends AgentBase
{

   public void NotesMain()
  {

     try
    {
      Session session = getSession();
      AgentContext agentContext = session.getAgentContext();
        
       //当前文档
      Document currentDoc = agentContext.getDocumentContext();
       //图片库文档的ID号,若没有则为空
      String picDocUnid = currentDoc.getItemValueString( "picDocUnid");
        

       //当前数据库及视图、视图中对应的文档
      Database thisDB = agentContext.getCurrentDatabase();
      Document thisDoc = thisDB.getDocumentByUNID(currentDoc.getUniversalID());
        
       //图片库的文档,创建及追加
      Database goalDB = session.getDatabase(thisDB.getServer(), "whcg\\wjkhPic.nsf");
      Document goalDoc = null;
       if(picDocUnid.equals(""))
      {
        goalDoc = goalDB.createDocument();
        thisDoc.copyAllItems(goalDoc, true);
        goalDoc.replaceItemValue( "form", "newPic");
        goalDoc.replaceItemValue( "unid", thisDoc.getUniversalID());    
        goalDoc.save( true, true);    
      }
       else
      {
        goalDoc = goalDB.getDocumentByUNID(picDocUnid);
        thisDoc.copyAllItems(goalDoc, false);
        goalDoc.save( true, true);
      }
        
       //读取附件列表,写入到连接域中
      Vector fileNames = session.evaluate( "@AttachmentNames", goalDoc);
      String url = "";

       for ( int i = 0; i < fileNames.size(); i++)
      {
        url = url + "<br>" + "<img src='/whcg/wjkh.nsf/doclist.gif'><a href='/whcg/wjkhPic.nsf/0/"
            + goalDoc.getUniversalID() + "/$FILE/"
            + fileNames.get(i) + "'>" + fileNames.get(i)
            + "</a>";
      }

      String htmlString = "";
      htmlString = htmlString
          + "<table class=tbbg align=center border=0 cellpadding=2 cellspacing=1>";
      htmlString = htmlString + "<tr class=toptrbg>";
      htmlString = htmlString + "<td>附件列表:</td>";
      htmlString = htmlString + "</tr>";
      htmlString = htmlString + "<tr>";
      htmlString = htmlString
          + "<td bgcolor=f8f8f8>";
      htmlString = htmlString + url;
      htmlString = htmlString + "</td>";
      htmlString = htmlString + "</tr>";
      htmlString = htmlString + "</table>";

      thisDoc.replaceItemValue( "p_w_uploadList", htmlString);
       //删除原文档中的附件
       if(thisDoc.getFirstItem( "$File") != null)
      {
        thisDoc.getFirstItem( "$File").remove();
      }
      thisDoc.replaceItemValue( "picDocUnid", goalDoc.getUniversalID());
      thisDoc.save( true, true);

    }
     catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}