using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace InfoCenter
{
    public partial class InfoCenterApi : System.Web.UI.Page
    {
        public string directUrl = string.Empty;
        public string iframe = string.Empty;
        public string script = string.Empty;
        public string type = string.Empty;
        public string apiType = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            //获取动作
            string action = GetRequest("action");
            string key = GetRequest("ic_key");
            string app = GetRequest("ic_app");
            string code = GetRequest("ic_code");
            string reurl = GetRequest("ic_url");
            type = GetRequest("ic_typ");
            apiType = GetRequest("ic_apitype");
            //Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile("v5shopv5mall", "MD5"));
            //判断请求是否合法
            string verifyCode = GetVerifyCode();
            if (verifyCode != code || key == "")
            {
                return;
            }
            //页面跳转
            directUrl = reurl;
            if (apiType == "")
            {
                //根据动作判断触发事件
                ExecuteByAction(action, key, app);
            }
            else
            {
                //返回需要同步的数据
                string resultData = ReturnApiData(action, key, app);
                Response.Write(resultData);
                Response.End();
            }
        }


        ///// <summary>
        ///// 获取真实URL地址
        ///// </summary>
        ///// <returns></returns>
        //public static string GetTrueUrl()
        //{
        //    string TrueUrl = string.Empty;
        //    string TheUrl = HttpContext.Current.Request.Url.ToString();
        //    string[] UrlArray = TheUrl.Split('?')[0].Split('/');

        //    TrueUrl = TheUrl.Split('?')[0].Replace(UrlArray[UrlArray.Length - 1], "");

        //    return TrueUrl;
        //}


        /// <summary>
        /// 读取页面生成静态页面
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="fna"></param>
        /// <returns></returns>
        private string GetUrlHtml(string url)
        {
            bool ok;
            //准备生成
            string strHtml;
            StreamReader sr = null; //用来读取流
            StreamWriter sw = null; //用来写文件
            Encoding code = Encoding.GetEncoding("utf-8"); //定义编码 
            //构造web请求，发送请求，获取响应
            WebRequest HttpWebRequest = null;
            WebResponse HttpWebResponse = null;
            HttpWebRequest = WebRequest.Create(url);
            try
            {
                HttpWebResponse = HttpWebRequest.GetResponse();
                //获得流
                sr = new StreamReader(HttpWebResponse.GetResponseStream(), code);
                strHtml = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                strHtml = "";
            }

            return strHtml;
        }


        /// <summary>
        /// 返回需要的数据
        /// </summary>
        private string ReturnApiData(string action, string key, string app)
        {
            StringBuilder builder = new StringBuilder();
            //根据key和action获取相应配置文件
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("config/" + key + "_ActionList.config"));
            XmlNode root = xmlDoc.SelectSingleNode("InfoCenter/Action[@Name='" + action + "']");
            //如果节点不存在则直接退出
            if (root == null)
                return "null";
            //遍历该节点下面的子节点
            foreach (XmlNode rootChild in root.ChildNodes)
            {
                ////不请求自己的同步方法
                //if (rootChild.Attributes["app"].Value.ToLower() != app.ToLower())
                //{
                string appUrl = GetTrueUrl() + rootChild.InnerText + "?" + collectQuery();
                //发送同步请求
                builder.Append(GetUrlHtml(appUrl));
                //}
            }

            return builder.ToString();
        }

        /// <summary>
        /// 获取同步验证码
        /// </summary>
        /// <returns></returns>
        private string GetVerifyCode()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("config/apikey.config"));
            XmlNode rootPub = xmlDoc.SelectSingleNode("apiKey/pubKey");
            if (rootPub == null)
                return "";

            XmlNode rootSelf = xmlDoc.SelectSingleNode("apiKey/selfKey");
            if (rootSelf == null)
                return "";

            return MD5(rootPub.InnerText + rootSelf.InnerText);
        }

        /// <summary> 
        /// MD5 加密函数 
        /// </summary> 
        /// <param name="str"></param> 
        /// <param name="code"></param> 
        /// <returns></returns> 
        public static string MD5(string str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }

        /// <summary>
        /// 获取传递过来的参数
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetRequest(string key)
        {
            return Request.QueryString[key] == null ? "" : Request.QueryString[key].ToString();
        }

        /// <summary>
        /// 根据动作判断触发事件
        /// </summary>
        private void ExecuteByAction(string action, string key, string app)
        {
            //根据key和action获取相应配置文件
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("config/" + key + "_ActionList.config"));
            XmlNode root = xmlDoc.SelectSingleNode("InfoCenter/Action[@Name='" + action + "']");

            //如果节点不存在则直接退出
            if (root == null)
                return;

            //遍历该节点下面的子节点
            foreach (XmlNode rootChild in root.ChildNodes)
            {
                //不请求自己的同步方法
                if (rootChild.Attributes["app"].Value.ToLower() != app.ToLower())
                {
                    string appUrl = GetTrueUrl() + rootChild.InnerText + "?" + collectQuery();
                    //发送同步请求
                    if (type == "script")
                    {
                        script += "var new_script=document.createElement('script'); new_script.src='" + appUrl + "'; document.getElementsByTagName('head')[0].appendChild(new_script);";
                    }
                    else if (type == "webrequest")
                    {
                        //发送webrequest请求
                        RequestAppUrl(appUrl);
                    }
                    else
                    {
                        script += "<script src=\"" + appUrl + "\" reload=\"1\"></script>";
                    }
                }
            }

            if (directUrl.Trim() != "")
            {
                if (directUrl.ToLower().IndexOf("http") != -1 || directUrl.Substring(0, 1) == "/")
                {
                    script = "页面加载中..." + script + "<script>setTimeout('dir()', 1500); function dir(){window.location.href='" + directUrl + "';}</script>";
                }
                else
                {
                    script = "页面加载中..." + script + "<script>setTimeout('dir()', 1500); function dir(){window.location.href='/" + directUrl + "';}</script>";
                }
            }
        }

        /// <summary>
        /// 根据同步地址发送QUERYSTRING请求
        /// </summary>
        /// <param name="appUrl"></param>
        private void RequestAppUrl(string appUrl)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(appUrl);
            myReq.BeginGetResponse(new AsyncCallback(RespCallback), new object());
        }

        /// <summary>
        /// 获取真实URL地址
        /// </summary>
        /// <returns></returns>
        public static string GetTrueUrl()
        {
            string TrueUrl = string.Empty;
            string TheUrl = HttpContext.Current.Request.Url.ToString();
            string[] UrlArray = TheUrl.Split('?')[0].Split('/');

            TrueUrl = TheUrl.Split('?')[0].Replace(UrlArray[UrlArray.Length - 1], "");

            return TrueUrl;
        }

        /// <summary>
        /// 返回处理函数
        /// </summary>
        /// <param name="ar"></param>
        private static void RespCallback(IAsyncResult ar) { }

        /// <summary>
        /// 合并传递的QUERYSTRING字符串
        /// </summary>
        /// <returns></returns>
        private string collectQuery()
        {
            StringBuilder queryString = new StringBuilder();
            int i = 0;

            foreach (string query in Request.QueryString)
            {
                if (i == 0)
                {
                    queryString.Append(query + "=" + HttpUtility.HtmlEncode(Request.QueryString[query]));
                    i = 1;
                }
                else
                {
                    queryString.Append("&" + query + "=" + HttpUtility.HtmlEncode(Request.QueryString[query]));
                }
            }

            return queryString.ToString();
        }

        ///// <summary>
        ///// 读取页面生成静态页面
        ///// </summary>
        ///// <param name="url">地址</param>
        ///// <param name="fna"></param>
        ///// <returns></returns>
        //private string GetUrlHtml(string url)
        //{
        //    bool ok;
        //    //准备生成
        //    string strHtml;
        //    StreamReader sr = null; //用来读取流
        //    StreamWriter sw = null; //用来写文件
        //    Encoding code = Encoding.GetEncoding("utf-8"); //定义编码 
        //    //构造web请求，发送请求，获取响应
        //    WebRequest HttpWebRequest = null;
        //    WebResponse HttpWebResponse = null;
        //    HttpWebRequest = WebRequest.Create(url);
        //    try
        //    {
        //        HttpWebResponse = HttpWebRequest.GetResponse();
        //        //获得流
        //        sr = new StreamReader(HttpWebResponse.GetResponseStream(), code);
        //        strHtml = sr.ReadToEnd();
        //    }
        //    catch (Exception ex)
        //    {
        //        strHtml = "";
        //    }

        //    return strHtml;
        //}
    }
}