using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//
using System.Data;
using System.Data.SqlClient;
using DotNet.FrameWork.Data;
using System.Web.SessionState;
using System.Net;
using System.Xml;
using DotNet.FrameWork.Common.Encrypt;
using HaTeam.Dd.Model;

namespace HteamDd.Web.ashx
{
    /// <summary>
    /// Dd_psw_mail 的摘要说明
    /// </summary>
    public class Dd_psw_mail : IHttpHandler,IRequiresSessionState
    {
        XmlDocument xmldocument = new XmlDocument();
        public string seandfrom = "", password = "",email;
        string strPath = GetWebSiteUrl.GetWebUrl;
        public void ProcessRequest(HttpContext context)
        {
            string re_email = context.Request.Params["user_email"].ToString();
            try
            {
                string get_call = "select User_BlogName,User_ID from Dd_User where User_Email=@email";
                SqlParameter parm = new SqlParameter("@email", re_email);
                DataSet ds = DbHelperSQL.GetDataSet(get_call,parm);
                DataRow dr = ds.Tables[0].Rows[0];
                if (set_status(re_email) != -1)
                {
                    if (re_email!="")
                    {
                        email = re_email;//用户邮箱
                        updateXml(context);
                        ReadXml(context);
                    }
                    else
                    {
                        email = "immaster@haitian.com.cn";//不清楚
                    }
                    string sendfrom = seandfrom;//发件人邮箱
                    string senderaccount = "haitian";
                    string pwd = password;
                    string receiver = email;//用户注册时用的邮箱账号
                    string subject = "你好";
                    string ip = Get_UserIP();
                    string name = dr["User_BlogName"].ToString();//博客名称
                    DateTime time = System.DateTime.Now;
                    string user_id= dr["User_ID"].ToString();
                    string body = "<strong style=font-size:16px;" + ">Hi," + name + "</strong><br />欢迎加入海天大家庭!!!<br />你申请了重设海客网密码，请点击下面的链接，然后根据页面提示完成密码重设：<br /><font color=" + "red" + ">为保证您的账号能够正常使用，请点击链接：</font><br/><a title=\"激活登陆账号\" href=\"";
                    string link = strPath + "/web/Dd_password/Dd_psw_ret.aspx?action=tdc%BDF%lhhy%ghdifs%dfgr&userguid=" + user_id + "&time=" + time;
                    body = body + link + "\">" + strPath + Encrypt.EncryptPassword(link, "MD5") + Encrypt.EncryptPassword(link, "SHA1") + "</a>";
                    string server = "smtp.163.com";
                    try
                    {
                        SendMail(context,sendfrom, senderaccount, pwd, receiver, subject, body, server);
                    }
                    catch
                    {
                        SendMail(context,"haitianxw001@163.com", senderaccount, "haitianxw1", receiver, subject, body, server);
                        context.Response.Write("send_error");
                    }

                    context.Response.Write("success");                   
                }
                else
                {
                    context.Response.Write("error");
                }
               
            }
            catch
            {
                context.Response.Write("user_isnot");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 获取用户的IP
        /// </summary>
        /// <returns></returns>
        private string Get_UserIP()
        {
            string client_ip = "";
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
            foreach (System.Net.IPAddress ip in ipEntry.AddressList)
            {
                client_ip = ip.ToString();
            }
            return client_ip;
        }

        /// <summary>
        /// 发送邮件的同时修改用户的状态
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private int set_status(string email)
        {
            try
            {
                string user_status = "update Dd_User set User_isSet=1 where User_Email=@email";
                SqlParameter pam = new SqlParameter("@email", email);
                return DbHelperSQL.ExecuteSql(user_status, pam);
            }
            catch
            {
                return -1;
            }
        }
    
        /// <summary>
        /// 方法功能:发送邮件到指定联系人
        /// </summary>
        /// <param name="sendfrom">发送方的邮箱</param>
        /// <param name="senderaccount">发送方的名称</param>
        /// <param name="pwd">发送方的邮箱密码</param>
        /// <param name="receiver">接收方的邮箱</param>
        /// <param name="subject">邮件的主题</param>
        /// <param name="body">邮件的内容</param>
        /// <param name="mailserver">邮箱服务器</param>
        /// <returns>返回整数表示发送状态</returns>        
        public void SendMail(HttpContext context, string sendfrom, string senderaccount, string pwd, string receiver, string subject, string body, string mailserver)
        {

            jmail.MessageClass MyMail = new jmail.MessageClass();
            string SendTo = receiver;　　//收件人
            string FromMail = sendfrom;//发件人
            string Title = subject; //邮件主题
            string Body = body;   //邮件主体
            string ShowName = "HTEMS";//显示名字
            //取email的@前面部分为用户名,即ustbwuyi1,当然也可以自己设置.
            string MailUserName = FromMail.Substring(0, FromMail.IndexOf("@"));
            string MailPassword = pwd;
            if (SendTo != "")
            {
                // 字符集
                MyMail.Charset = "GB2312";
                MyMail.ContentType = "text/html";
                //附件的编码格式
                MyMail.Encoding = "BASE64";
                ////是否将信头编码成iso-8859-1字符集
                MyMail.ISOEncodeHeaders = false;
                //发送人邮件地址
                MyMail.From = FromMail;
                //发送人姓名
                MyMail.FromName = ShowName;
                // 邮件主题
                MyMail.Subject = Title;
                //身份验证的用户名
                MyMail.MailServerUserName = MailUserName;
                //用户密码
                MyMail.MailServerPassWord = MailPassword;
                //邮件内容
                MyMail.Body = Body;
                try
                {

                    MyMail.AddRecipient(SendTo, "", "");
                    MyMail.Send(mailserver, false);
                }
                catch (Exception ex)
                {
                    context.Response.Write("send_email_error");
                    context.Response.End();
                }
            }

        }
        /// <summary>
        /// 每天自动修改XMLEmail.xml的初始值
        /// </summary>
        /// 
        public void updateXml(HttpContext context)
        {
            xmldocument.Load(context.Server.MapPath("XMLEmail.xml"));
            XmlNodeList nodelist = xmldocument.SelectSingleNode("Emailstore").ChildNodes;
            foreach (XmlNode xn in nodelist)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("Description") != DateTime.Now.Date.ToString())
                {
                    xe.SetAttribute("Description", DateTime.Now.Date.ToString());
                    XmlNodeList nodeschild = xe.ChildNodes;
                    foreach (XmlNode xn1 in nodeschild)
                    {
                        XmlElement xe1 = (XmlElement)xn1;
                        if (xe1.Name == "count")
                        {
                            xe1.InnerText = "0";
                        }
                        if (xe1.Name == "available")
                        {
                            xe1.InnerText = "true";
                        }
                    }
                }
            }
            xmldocument.Save(context.Server.MapPath("XMLEmail.xml"));
        }
        /// <summary>
        /// 获取XMLEmail.xml的文件值取出邮箱名和密码并赋值给全局变量
        /// </summary>
        public void ReadXml(HttpContext context)
        {
            xmldocument.Load(context.Server.MapPath("XMLEmail.xml"));
            XmlNodeList nodelist = xmldocument.SelectSingleNode("Emailstore").ChildNodes;
            foreach (XmlNode xn in nodelist)
            {
                XmlElement xe = (XmlElement)xn;
                int count = int.Parse(xn["count"].InnerText);
                if (xn["available"].InnerText == "true" && count < 200)
                {
                    seandfrom = xe.GetAttribute("emailName");
                    password = xe.GetAttribute("password");
                    count += 1;
                    xn["count"].InnerText = count.ToString();
                    break;
                }
                else
                {
                    xn["available"].InnerText = "false";
                }
            }
            xmldocument.Save(context.Server.MapPath("XMLEmail.xml"));
        }


    }
}