// EmailThread.cpp : implementation file
//

#include "stdafx.h"
#include "SmsCenter.h"
#include "EmailThread.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CEmailThread

#include "SmsCenterDlg.h"
#include "..\public\pop3\pop3.h"


typedef struct _EmailFilt
{
	TCHAR szFilt[64];
}EmailFilt;

IMPLEMENT_DYNCREATE(CEmailThread, CWinThread)

CEmailThread::CEmailThread()
{
	m_bStart = false;
	m_pSMSDlg = NULL;
}

CEmailThread::~CEmailThread()
{
}

BOOL CEmailThread::InitInstance()
{
	CoInitializeEx( NULL , COINIT_MULTITHREADED );
	// TODO:  perform and per-thread initialization here
	return TRUE;
}

int CEmailThread::ExitInstance()
{
	CoUninitialize();

	// TODO:  perform any per-thread cleanup here
	return CWinThread::ExitInstance();
}

BEGIN_MESSAGE_MAP(CEmailThread, CWinThread)
	//{{AFX_MSG_MAP(CEmailThread)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_MSG_MAP
	ON_THREAD_MESSAGE(TH_EMAIL,On_Email)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CEmailThread message handlers

void CEmailThread::On_Email(WPARAM wParam, LPARAM lParam)
{
USES_CONVERSION;

	if ( m_bStart )  //������ڷ��ͣ���������
		return ;

try
{
	m_bStart = true;
	CString strSelect;
	strSelect = _T("select email.*,users.mobile from email,users where email.Status=1 and email.userid = users.userid");
	BOOL b = m_AdoRS.Open( strSelect );
	if ( b && !m_AdoRS.IsEOF() )
	{
		long         lID;
		long         lCorpID;
		long         lUserID;
		long         lRSCount2=0;
		CString      strIP;
		CString      strUserName;
		CString      strPasswd;
		CString      strMobile;
		CString      strTemp;

		while ( !m_AdoRS.IsEOF() && lRSCount2<10000 )
		{
			char  szUserName[64]={0};
			char  szPasswd[64]={0};
			char  szPasswd2[64]={0};
			long  lCheckTime=0;
			COleDateTime tCheckLast;
			m_AdoRS.GetCollect( _T("EmailID") , lID );
			m_AdoRS.GetCollect( _T("CorpID")  , lCorpID );
			m_AdoRS.GetCollect( _T("UserID")  , lUserID );
			m_AdoRS.GetCollect( _T("IP")      , strIP );
			m_AdoRS.GetCollect( _T("UserName"), strUserName );
			m_AdoRS.GetCollect( _T("Passwd")  , strPasswd );
			m_AdoRS.GetCollect( _T("Mobile")  , strMobile);
			m_AdoRS.GetCollect( _T("CheckTime")  , lCheckTime);
			m_AdoRS.GetCollect( _T("CheckLast")  , tCheckLast);
			//�жϼ��ʱ���Ƿ���
			try
			{
				//if ( lCheckTime <=0 )
				//	lCheckTime=30;
				SYSTEMTIME stNow,stLast;
				COleDateTime tNow=COleDateTime::GetCurrentTime();
				tNow.GetAsSystemTime(stNow);
				tCheckLast.GetAsSystemTime(stLast);

				COleDateTimeSpan ts(0,0,0,lCheckTime);
				if (COleDateTime::GetCurrentTime()-tCheckLast<ts)  //δ��ʱ����
				{
					lRSCount2 ++;
					m_AdoRS.MoveNext();
					continue;
				}
			}catch(...)
			{
				LOG_APPERROR(_T("T"));
				;
			}
			//�滻�����ʱ��
			strSelect.Format( _T("update email set CheckLast=GETDATE() where EmailID=%d"),lID);
			m_AdoRS1.Open(strSelect);
			m_AdoRS1.Close();
			//������
			CDes des;
#ifdef UNICODE
			strcpy(szPasswd , W2A(strPasswd));
			strcpy(szUserName , W2A(strUserName));
			long lOut = sizeof(szPasswd2);
			des.Decrypt(szPasswd ,strlen(szPasswd),szPasswd2,lOut,szUserName,8);
			strPasswd  =A2W(szPasswd2);
#else
			strcpy(szPasswd , strPasswd);
			strcpy(szUserName , strUserName);
			long lOut = sizeof(szPasswd2);
			des.Decrypt(szPasswd ,strlen(szPasswd),szPasswd2,lOut,szUserName,8);
			strPasswd  =szPasswd2;
#endif
			//��ѯ���˱�,��ȡ�ô��û�Ӧ���˵���Ϣ
			long lFiltCount=0;
			EmailFilt * pFilt = NULL;
			strSelect.Format( _T("select * from emailfilt where UserID=%d and Status=1 and (EmailID=0 or EmailID is NULL or EmailID=%d)"),lUserID,lID);
			if (m_AdoRS1.Open( strSelect ) && !m_AdoRS1.IsEOF())
			{
				lFiltCount = m_AdoRS1.GetRecordCount();
				if ( lFiltCount<0 )
					lFiltCount = 0;
				pFilt  = new EmailFilt[lFiltCount];
				memset(pFilt , 0 , sizeof(EmailFilt)*lFiltCount);
				m_AdoRS1.MoveFirst();
				int i = 0;
				while ( !m_AdoRS1.IsEOF() )
				{
					m_AdoRS1.GetCollect( _T("Name") , strTemp );
					strTemp.MakeUpper();
					_tcscpy(pFilt[i].szFilt,strTemp);
					m_AdoRS1.MoveNext();
					i ++;
				}
				m_AdoRS1.Close();
			}
			//��ʼȡEmail
			CPop3Connection pop;
			CPop3Message popmsg;
			int iMailCount=0;
			int iMailSize=0;
			if ( pop.Connect(strIP,strUserName,strPasswd) )
			{
				if ( !pop.Statistics(iMailCount, iMailSize) )
				{
					iMailCount = 0;
					iMailSize = 0;
				}
				int iNoDayCount=0;
				int iNoInDB=0;
				//ȡEmail From ,subject ,id ������
				for ( int i=iMailCount;i>0;i-- )
				{
					if ( !pop.GetMessageHeader(i,popmsg) )
						break;
					//�����
					CString strDate    = popmsg.GetDate();
					strDate.Replace( _T("GMT") , _T("") );
					int iStart = strDate.Find(',');
					if ( iStart <=0 || iStart>strDate.GetLength()/2)
						iStart = 0;
					else
						iStart += 1;
					int iEnd = strDate.FindOneOf(_T("+-"));
					if ( iEnd <=0 || iEnd > strDate.GetLength() )
						iEnd = strDate.GetLength();
					CString strTime = strDate.Mid(iStart , iEnd-iStart );
					strTime.TrimLeft();
					strTime.TrimRight();
					COleDateTime abc;
					abc.ParseDateTime(strTime,VAR_DATEVALUEONLY);
					if ( abc.GetStatus() == COleDateTime::valid )
					{
						SYSTEMTIME t;
						::GetSystemTime(&t);
						if ( abc.GetYear() != t.wYear || 
							 abc.GetMonth() != t.wMonth ||
							 abc.GetDay() != t.wDay )
						{
							iNoDayCount ++ ;
							if ( iNoDayCount >= 3 ) //���ڲ��ǵ���Ĵ���3������֪ͨ��ֱ���˳���
							{
								break;
							}
							else
							{
								continue;  //���ڲ��ԣ�����
							}
						}
						abc.GetAsSystemTime(t);
					}
					else
					{
						iNoDayCount ++ ;
						if ( iNoDayCount >= 3 ) //���ڲ��ǵ���Ĵ���3������֪ͨ��ֱ���˳���
						{
							break;
						}
						else
						{
							continue;  //���ڲ��ԣ�����
						}
					}
					//�ж�MsgID�Ƿ��Ѵ���
					CString strMsgID = popmsg.GetMsgID();
					strMsgID.TrimLeft();
					strMsgID.TrimRight();
					if ( strMsgID.GetLength() <= 0 || strMsgID.GetLength() > 60 )
						continue;
					strMsgID.Replace(_T("'"),_T("''"));		//��ֹ'���������
					strSelect.Format( _T("select * from emailid where UserID=%d and MsgID='%s'"),lUserID,strMsgID);
					if ( m_AdoRS1.Open(strSelect) && m_AdoRS1.GetRecordCount()> 0 )  //�Ѵ��ڣ�����
					{
						m_AdoRS1.Close();
						iNoInDB ++;
						if ( iNoInDB >= 2 ) //������������������ݿ��д��ڣ����˳�
						{
							break;
						}
						else
						{
							continue;  //���ڲ��ԣ�����
						}
					}
					//û�У�����EmailID��
					strSelect.Format( _T("insert into  emailid (CorpID,UserID,MsgID,AddTime) values (%d,%d,'%s',GETDATE())") , lCorpID,lUserID,strMsgID );
					m_AdoRS1.Open(strSelect);
					m_AdoRS1.Close();

					CString strFrom    = popmsg.GetFrom();
					CString strFromMin = popmsg.GetFrom_Min();
					CString strSubject = popmsg.GetSubject();


					//�ж��Ƿ�����Ҫ���˵�Email
					BOOL bSend = false;
					strFrom.MakeUpper();
					for ( int j=0;j<lFiltCount;j++)
					{
						if ( !_tcscmp(pFilt[j].szFilt,_T("����") ) )
						{
							bSend = true;
							break;
						}
						if ( strFrom.Find(pFilt[j].szFilt) >= 0 )  //����Ҫ֪ͨ�����
						{
							bSend = true;
							break;
						}
					}
					if ( bSend )
					{
						//�ύ����
						long lMobType = MOBILE_TYPE_CMCC;
						//if ( isNumUnicom((char*)(LPCTSTR)strMobile) )
						//	lMobType = MOBILE_TYPE_UNICOM;
						
						SubmitData data={0};
						data.lCorpID = lCorpID;
						data.lUserID = lUserID;
						_tcscpy( data.szName    , _T("email") );
						_tcscpy( data.szMobile  , strMobile );
						//strcpy( data.szMsg , strMsg );
						SYSTEMTIME t;::GetLocalTime(&t);
						_stprintf(data.szMsg,_T("����%02d.%02d %02d:%02d�յ�%s���ʼ�:%s"),t.wMonth,t.wDay,t.wHour,t.wMinute,strFromMin,strSubject);
						CSendThread::SubmitSms( data,&m_AdoRS1,&m_AdoRS2,m_pSMSDlg,lMobType,SMSTYPE_EMAIL);  //���Ͷ���
					}
				}
			}
			pop.Disconnect();  //�Ͽ�����

			if ( pFilt ) {delete pFilt;pFilt=NULL;}

			lRSCount2 ++;
			m_AdoRS.MoveNext();
		}
	}
	m_bStart = false;
}
catch (...)
{
	LOG_APPERROR(_T("T"));
	m_bStart = false;
	return ;
}
	m_bStart = false;
	return ;
}

BOOL CEmailThread::SetParam(CSmsCenterDlg *pSmsDlg)
{
	m_pSMSDlg = pSmsDlg;
	BOOL b = m_adoConnection.ConnectSQLServer2(m_pSMSDlg->m_Setup.szDBName,DEFAULT_DBNAME,m_pSMSDlg->m_Setup.szDBUser,m_pSMSDlg->m_Setup.szDBPasswd, m_pSMSDlg->m_Setup.szProvider);
	if ( b )
	{
		m_adoConnection.SetCommandTimeout(7200);  //�������ӳ�ʱʱ��	
#ifdef SMSCENTER_USECLIENT
		m_adoConnection.SetCursorLocation(adUseClient);  //�������������
#endif
		m_AdoRS.SetAdoConnection( &m_adoConnection );  //�������ݿ�����
		m_AdoRS1.SetAdoConnection( &m_adoConnection );  //�������ݿ�����
		m_AdoRS2.SetAdoConnection( &m_adoConnection );  //�������ݿ�����
	}
	return b;
}