using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using SqlOperate;
using nspBase.Core;
using nspLable.Function;
using System.Text;
using System.IO;
using nspLable.Function.Systems;

namespace nspEmail.Lables
{
    /// <summary>
    /// EmailTempinc 的摘要说明
    /// </summary>
    public class EmailTempinc : Base.BasePage
    {
        public static int strSuccess = 0;//成功的邮件数量
        public static int strFailure = 0;//失败的数量
        public static int strCount;//发送邮件数量
        private string _StrModule;
        public static string strTypeId;
        public static string strUID;
        public static string strUserName;
        public static Regex[] regex = new Regex[2];
        public EmailTempinc()
        {
            this._StrModule = StrModule;
            RegexOptions options;
            options = RegexOptions.Singleline | RegexOptions.IgnoreCase;
            regex[0] = new Regex(@"{PB_\w+}", options);
            regex[1] = new Regex(@"{EM_\w+}", options);


        }

        public string StrModule
        {
            get { return this._StrModule; }
        }

        /// <summary>
        /// 获取邮件模版并发送
        /// </summary>
        /// <param name="template_url">邮件模版标志</param>
        /// <param name="encode">获取接收邮件信息表</param>
        public string GetTemplate(string strFlag, string strSql)
        {
            string strInfo = "";
            string sql = "select Content,Title from W_EmailTemplate  where Flag='" + strFlag + "'";
            DataTable dt = SqlHelper.ExecuteSqlQuery(sql);
            if (dt.Rows.Count != 0)
            {
                string strModes = dt.Rows[0]["Content"].ToString();
                string strTitle = dt.Rows[0]["Title"].ToString();
                dt.Clear();
                dt.Dispose();
                dt = SqlHelper.ExecuteSqlQuery(strSql);
                if (dt.Rows.Count > 0)
                {
                    int k=0;
                    strCount = dt.Rows.Count;
                    for (int i = 0; i < dt.DefaultView.Count; i++)
                    {
                        strTypeId = dt.Rows[i]["TypeID"].ToString();
                        string strEmail = dt.Rows[i]["Email"].ToString();
                        strUID = dt.Rows[i]["UserID"].ToString();
                        int strUserId = Convert.ToInt32(dt.Rows[i]["UserID"].ToString());
                        strUserName = dt.Rows[i]["LoginName"].ToString();
                        string strbody = Hope_htmlAll(strModes);
                        if (strbody.ToUpper() != "NOT FIND")
                            strInfo = clsEmail.SendMail(strEmail, strTitle, strbody, true);
                        if (strInfo == "发送成功")
                            k = k + 1;
                        string strSubType = "";
                        switch (strFlag)
                        {
                            case "us_SubScriptionNews":
                                strSubType = "商机资讯"; break;
                            case "us_SubscriptionProduct":
                                strSubType = "商机快递"; break;
                            default:
                                strSubType = "其它信息"; break;
                        }
                        EmailStatistics es = new EmailStatistics();
                        es.UserId = strUserId;
                        es.State = strInfo;
                        es.SubscriptionType = strSubType;
                        es.AddDate = DateTime.Now;
                        es.Extend = "nn";
                        new EmailStatistics().Insert(es);
                    }
                    strSuccess = k;
                    strFailure = strCount - strSuccess;
                }
            }
            return strInfo;
        }

        /// <summary>
        /// 标签处理方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Hope_htmlAll(string str)
        {
            string Restr = "";
            Restr = str;
            string strInfo_PB = "";
            string strInfo_EM = "";
            string[] arrInfo;
            try
            {
                //处理公共标签
                foreach (Match match in regex[0].Matches(Restr))
                    if (!strInfo_PB.Contains(match.Value))
                        strInfo_PB = strInfo_PB + match.Value.ToString() + "|";
                if (strInfo_PB != "")
                {
                    strInfo_PB = strInfo_PB.TrimEnd(new char[] { '|' });
                    Restr = PBFunction(Restr, strInfo_PB);
                }
                //处理邮件私有标签
                foreach (Match match in regex[1].Matches(Restr))
                {
                    strInfo_EM = strInfo_EM + match.Groups[0].ToString() + "|";

                }
                strInfo_EM = strInfo_EM.TrimEnd(new char[] { '|' });
                if (strInfo_EM != "")
                {
                    arrInfo = strInfo_EM.Split('|');
                    for (int i = 0; i < arrInfo.Length; i++)
                    {
                        Restr = Restr.Replace(arrInfo[i], EMFunction(staticTitle(arrInfo[i].ToString())));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Second exception caught.", e);
            }

            return Restr;
        }
        /// <summary>
        /// 处理全局变量
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string PBFunction(string strInfo, string str)
        {
            string[] strArray;
            strArray = str.Split('|');
            DataTable WebTable = SqlHelper.ExecuteSqlQuery("select * from W_WebBasic");


            for (int i = 0; i < strArray.Length; i++)
            {
                try
                {
                    switch (strArray[i].ToUpper())
                    {
                        case "{PB_LOGINNAME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), strUserName);
                            break;
                        case "{PB_CURRENTTIME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), System.DateTime.Now.ToString("D"));
                            break;
                        case "{PB_WEBNAME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["WebName"].ToString());
                            break;
                        case "{PB_WEBTEL}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["HotTel"].ToString());
                            break;
                        case "{PB_WEBLOGO}":
                            string str1 = "<a href=\"" + Config.WebURL + "\"><img src=\"";
                            if (WebTable.Rows[0]["WebLOGO"].ToString().Substring(0, 1) == "/")
                                str1 += Base.BasePage.Config.WebURL + "" + WebTable.Rows[0]["WebLOGO"].ToString().Substring(1);
                            else
                                str1 += Base.BasePage.ProcessAbsoluteUrl(WebTable.Rows[0]["WebLOGO"].ToString());
                            str1 += "\"></a>";
                            strInfo = strInfo.Replace(strArray[i].ToString(), str1);
                            break;
                        case "{PB_WEBURL}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), Config.WebURL);
                            break;
                        case "{PB_FLOOR}":
                            string str2 = "<table width=\"700px\" align=\"center\"><tr><td align=\"middle\"><font color=\"#ff0000\">" + WebTable.Rows[0]["WebName"].ToString() + "</font>";
                            str2 += "提醒您&nbsp;&nbsp;你的登录名是:<font color=\"#cc3300\">";
                            str2 += EMFunction("EM_FIOOR") + "</font>忘了密码？请";
                            str2 += "<a href=\"" + Config.WebURL + "/login/Retrieve_Password.aspx" + "\">点此找回</a></td></tr>";
                            str2 += "<tr><td align=\"middle\">如果您不想继续订阅此类邮件，请";
                            str2 += "<a href=\"" + Config.WebURL + "/Member/Index.aspx" + "\">点击这里</a></td></tr>";
                            str2 += "<tr><td align=\"middle\">如果您有任何问题,请<a href=\"" + Config.WebURL + "/search/solely.aspx?url=联系我们" + "\">点击这里联系我们</a></td></tr>";
                            str2 += "<tr><td align=\"middle\">服务热线:" + WebTable.Rows[0]["HotTel"].ToString() + "&nbsp;&nbsp;电子邮箱:" + WebTable.Rows[0]["Email"].ToString() + "</td></tr></table><br />";
                            strInfo = strInfo.Replace(strArray[i].ToString(), str2);
                            break;
                        default:
                            strInfo = "NOT FIND";
                            break;
                    }

                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

            WebTable.Clear();
            WebTable.Dispose();
            return strInfo;
        }
        /// <summary>
        /// 获取模板
        /// </summary>
        /// <param name="pathName">模板路径</param>
        /// <returns></returns>
        public static string GetEmailTemplate(string pathName)
        {
            StringBuilder builder = new StringBuilder();
            string str = "";
            using (StreamReader reader = new StreamReader(pathName, Encoding.Default))
            {
                StringBuilder builder2 = new StringBuilder();
                builder2.Append(reader.ReadToEnd());
                reader.Close();
                str =builder2.ToString();
            }

            return str;
        }
        /// <summary>
        /// 处理邮件通知私有标签
        /// </summary>
        /// <param name="Temp"></param>
        /// <returns></returns>
        public static string EmailSend(string Logname,int strTime)
        {
            string Restr = "";
            string strModeUrl = AppDomain.CurrentDomain.BaseDirectory.ToString() + "/Admin/Email/EmailTemplate/EmailSend.htm";
            Restr =GetEmailTemplate(strModeUrl);
            string strInfo_PB = "";
            RegexOptions options = RegexOptions.Singleline | RegexOptions.IgnoreCase;
            regex[0] = new Regex(@"{PB_\w+}", options);
            foreach (Match match in regex[0].Matches(Restr))
                if (!strInfo_PB.Contains(match.Value))
                    strInfo_PB = strInfo_PB + match.Value.ToString() + "|";
            if (strInfo_PB != "")
            {
                strInfo_PB = strInfo_PB.TrimEnd(new char[] { '|' });
                Restr =PBEmailFunction(Restr, strInfo_PB, Logname, strTime);
            }
            return Restr;
        }
        /// <summary>
        /// 处理邮件通知全局变量
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <summary>
        private static string PBEmailFunction(string strInfo, string str,string Logname,int strTime)
        {
            string[] strArray;
            strArray = str.Split('|');
            for (int i = 0; i < strArray.Length; i++)
            {
                try
                {
                    switch (strArray[i].ToUpper())
                    {
                        case "{PB_LOGINNAME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), Logname);
                            break;
                        case "{PB_CURRENTTIME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), strTime.ToString());
                            break;
                        default:
                            strInfo = "NOT FIND";
                            break;
                    }

                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

            return strInfo;
        }
        /// 处理邮件模版私有标签
        /// </summary>
        /// <param name="Temp"></param>
        /// <returns></returns>
        private string EMFunction(string StrModule)
        {

            string Restr = "";
            switch (StrModule.ToUpper())
            {
                case "EM_广告":                  //订阅商业资讯
                    Restr = EM_ProcessLable.EM_Newslist(strTypeId);//strTypeId
                    break;
                case "EM_PRODUCTINFO":           //网站供求信息统计
                    Restr = EM_ProcessLable.EM_ProductInfo();
                    break;
                case "EM_PRODUCTLIST":           //订阅供求信息
                    Restr = EM_ProcessLable.EM_Productlist(strUID);
                    break;
                case "EM_FIOOR":
                    Restr = EM_ProcessLable.EM_Floot(strUID);
                    break;
                default:
                    Restr = "NOT FIND";
                    break;
            }
            return Restr;
        }
        /// <summary>
        /// 获取邮件模版标签名称
        /// </summary>
        /// <param name=""></param>
        private string staticTitle(string str)
        {
            int no = str.Length - 2;
            return str.Substring(1, no);
        }
    }
}
