using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using nspLable.Manage;
using nspLable.Function.Systems;
using Base.Core;
using System.Data.SqlClient;
/// <summary>
/// Tempinc 的摘要说明
/// </summary>
namespace nspLable.Function.Systems
{
    public class Tempinc: Base.BasePage
    {
        Regex[] regex = new Regex[5];
        private static string Model;

        public Tempinc(string StrModule)
        {
            this._StrModule = StrModule;
            Model = StrModule;
            RegexOptions options;
            options = RegexOptions.Singleline | RegexOptions.IgnoreCase;
            regex[0] = new Regex(@"{[WS][SY]_\w+}", options);
            regex[1] = new Regex(@"{PB_\w+}", options);
            regex[2] = new Regex(@"{PR_\w+}", options);
            regex[3] = new Regex(@"../../../", options);
        }
        private string _StrModule;//Purchase_Trade Supply_Trade
        public string StrModule
        {
            get { return this._StrModule; }
        }


        /// <summary>
        /// 获取模板
        /// </summary>
        /// <param name="pathName">模板路径</param>
        /// <returns></returns>
        public string GetTemplate(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 = Hope_HtmlResult(builder2.ToString());
            }

            return str;
        }


        /// <summary>
        /// 外部调用函数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Hope_HtmlResult(string str)
        {
            string resultHtml = "";
            resultHtml = Hope_htmlAll(str);
            resultHtml = Hope_htmlAll(resultHtml);  //使用三层，考虑资源问题
            return resultHtml;
        }


        /// <summary>
        /// 标签处理方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string Hope_htmlAll(string str)
        {
            string Restr = "";
            Restr = str;
            string strInfo_PB = "";
            string strInfo_PR = "";
            string strInfo_SY = "";
            string[] arrInfo;
            try
            {
                //foreach (Match match in regex[3].Matches(Restr))
                //{
                //    Restr=Restr.Replace(match.Groups[0].ToString(), "{PB_WEBURL}");
                //}
                Restr = Restr.Replace("../../../", "{PB_WebUrl}");


                //处理私有标签
                foreach (Match match in regex[2].Matches(Restr))
                {
                    strInfo_PR = strInfo_PR + match.Groups[0].ToString() + "|";
                }
                if (strInfo_PR != "")
                    Restr = PRFunction(Restr, strInfo_PR);


                foreach (Match match in regex[0].Matches(Restr))
                {
                    //string Fun = tempTitle(match0.Groups[i].ToString());
                    //ReStr = str.Replace(match0.Groups[i].ToString(), eval(Fun));
                    strInfo_SY = strInfo_SY + match.Groups[0].ToString() + "|";
                }
                arrInfo = strInfo_SY.Split('|');
                for (int i = 0; i < arrInfo.Length - 1; i++)
                {
                    Restr = Restr.Replace(arrInfo[i], eval(staticTitle(arrInfo[i].ToString())));
                }


                //处理公共标签
                foreach (Match match in regex[1].Matches(Restr))
                    strInfo_PB = strInfo_PB + match.Value.ToString() + "|";
                if (strInfo_PB != "")
                    Restr = PBFunction(Restr, strInfo_PB);

            }
            catch (Exception e)
            {
                throw e;
            }

            return Restr;
        }


        /// <summary>
        /// 替换函数标签
        /// </summary>
        /// <param name="funTitle"></param>
        /// <param name="arry"></param>
        /// <returns></returns>
        private string eval(string str)
        {

            string Restr = "";
            TSystemLable Temp = new TSystemLable();
            try
            {
                switch (str.Substring(0, 3).ToUpper())
                {
                    case "WS_":   //处理用户自定义标签
                        Restr = WSFunction(str);
                        break;
                    case "SY_":   //处理系统标签
                        Temp = Get_Function(str);
                        if (Temp.ID == 0) throw new Exception("{" + str + "}");
                        Restr = SYFunction(Temp);
                        break;
                }
            }
            catch (Exception e)
            {
                Restr = e.Message.ToString();
            }
            return Restr;
        }


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


            for (int i = 0; i < strArray.Length; i++)
            {
                try
                {
                    switch (strArray[i].ToUpper())
                    {
                        case "{PB_WEBURL}":
                            strInfo = strInfo.Replace(strArray[i].ToString(),WebTable.Rows[0]["weburl"].ToString());
                            break;
                        case "{PB_WEBNAME}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["WebName"].ToString());
                            break;
                        case "{PB_ATAREA}":          //地区列表
                            strInfo = strInfo.Replace(strArray[i].ToString(), systemic.SY_AtArea(StrModule));                 
                            break;
                        case "{PB_WEBTEL}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["HotTel"].ToString());
                            break;
                        case "{PB_WEBLOGO}":
                            string str1 = "<img src=\"";
                            str1 += Function.ProcessImageUrl(WebTable.Rows[0]["WebLOGO"].ToString());
                            str1 += "\">";
                            strInfo = strInfo.Replace(strArray[i].ToString(), str1);
                            break;
                        case "{PB_KEYWORD}":
                            string ss = "";
                            if (StrModule.Contains("_"))
                            {
                                ss = StrModule.Substring(0, StrModule.IndexOf("_"));
                            }
                            else
                            {
                                ss = "Supply";
                            }
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.Append("<span id='search_result'>&nbsp;&nbsp;正在更新....</span>");
                            strBuilder.Append("<script type='text/javascript'> AjaxSearch('search_result','" + ss + "')</script>");
                            strInfo = strInfo.Replace(strArray[i].ToString(), strBuilder.ToString());
                            break;
                        case "{PB_SEARCHINFO}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), "<script type=\"text/javascript\" src=\"{PB_WebURL}js/Search.js\" ></script>");
                            break;
                        case "{PB_METAKEYWORDS}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), GetMetaKeyWords(StrModule,1));
                            break;
                        case "{PB_METADESCRIPTION}":
                            strInfo = strInfo.Replace(strArray[i].ToString(), GetMetaKeyWords(StrModule, 2));
                            break;
                        case "{PB_SYSTEMTEL}"://普通电话
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["SystemTel"].ToString());
                            break;
                        case "{PB_HOTTEL}":   //热线电话
                            strInfo = strInfo.Replace(strArray[i].ToString(), WebTable.Rows[0]["HotTel"].ToString());
                            break;
                    }

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

            return strInfo;
        }

        /// <summary>
        /// 取得META信息
        /// </summary>
        /// <param name="Model"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetMetaKeyWords(string Model,int type)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlData"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT a.ID,a.Keywords,a.Descriptions,b.Type FROM [W_MetaInfo] as a inner join [W_MetaType] b on a.TypeID=b.id and b.type=@Type", con);
            cmd.Parameters.AddWithValue("@Type",Model);
            con.Open();
            SqlDataReader sr = cmd.ExecuteReader();
            if (sr.Read())
            {
                if (type==1)
                {
                    return sr["Keywords"].ToString();
                }
                else
                {
                    return sr["Descriptions"].ToString();
                }
               
            }
            con.Close();
            return "";
        }



        /// <summary>
        /// 处理私有变量
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string PRFunction(string strInfo, string str)
        {
            string Restr = "";
            try
            {
                switch (StrModule.ToUpper())
                {

                    case "NEWS_INDEX":              //资讯首页
                        Restr = clsNewslable.PR_NewsIndex(strInfo, str);
                        break;
                    case "NEWS_TRADE":              //资讯分类页
                        Restr = clsNewslable.PR_NewsTrade(strInfo, str);
                        break;
                    case "NEWS_DETAIL":             //资讯详细页
                        Restr = clsNewslable.PR_NewsDetail(strInfo, str);
                        break;
                    case "NEWS_RESTORE":             //资讯详细页
                        Restr = clsNewslable.PR_NewsRestore(strInfo, str);
                        break;
                    case "PURCHASE_INDEX":          //求购首页
                        Restr = clsProductLable.PR_PurchaseIndex(strInfo, str);
                        break;
                    case "PURCHASE_TRADE":          //求购分类页
                        Restr = clsProductLable.PR_PurchaseTrade(strInfo, str);
                        break;
                    case "PURCHASE_DETAIL":         //求购详细页
                        Restr = clsProductLable.PR_PurchaseDetail(strInfo, str);
                        break;
                    case "SUPPLY_INDEX":            //供应首页
                        Restr = clsProductLable.PR_SupplyIndex(strInfo, str);
                        break;
                    case "SUPPLY_TRADE":            //供应分类页
                        Restr = clsProductLable.PR_SupplyTrade(strInfo, str);
                        break;
                    case "SUPPLY_DETAIL":           //供应详细页
                        Restr = clsProductLable.PR_SupplyDetail(strInfo, str);
                        break;
                    case "CORPORATION_INDEX":       //公司库首页
                        Restr = clsUserlable.PR_CorporationIndex(strInfo, str);
                        break;
                    case "COMPANY_TRADE":           //公司库首页
                        Restr = clsUserlable.PR_CorporationTrade(strInfo, str);
                        break;
                    case "CORPORATION_DETAIL":      //公司库首页
                        Restr = clsUserlable.PR_CorporationDetail(strInfo, str);
                        break;
                    case "EXPO_INDEX":             //展会首页
                        Restr = clsExpoLable.PR_ExpoIndex(strInfo, str);
                        break;
                    case "EXPO_TRADE":             //展会分类页
                        Restr = clsExpoLable.PR_ExpoTrade(strInfo, str);
                        break;
                    case "EXPO_DETAIL":            //展会分类页
                        Restr = clsExpoLable.PR_ExpoDetail(strInfo, str);
                        break;
                    case "AGENT_INDEX":            //招商加盟首页
                        Restr = clsAgentLable.PR_AgentIndex(strInfo, str);
                        break;
                    case "AGENT_TRADE":           //招商分类页
                        Restr = clsAgentLable.PR_AgentWTrade(strInfo, str);
                        break;
                    case "AGENT_DETAIL":          //招商详细页
                        Restr = clsAgentLable.PR_AgentSDetail(strInfo, str);
                        break;
                    case "PRODUCT_TRADE":          //产品库分类页
                        Restr = clsProducts.PR_ProductTrade(strInfo, str);
                        break;
                    case "PRODUCT_DETAIL":          //产品库详细页
                        Restr = clsProducts.PR_ProductDetail(strInfo, str);
                        break;
                    case "SOLELY":          //加盟详细页
                        Restr =  systemic.PR_SOLELY(strInfo, str);
                        break;
                    default:
                        Restr = strInfo;
                        break;

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Restr;
        }


        /// <summary>
        /// 处理用户标签
        /// </summary>
        /// <param name="str">标签名称</param>
        /// <returns></returns>
        private string WSFunction(string str)
        {
            string Restr = "";
            TUserLable Temp = new RUserLable().GateItem(str);
            if (Temp.Info == null || Temp.Info == "")
                return "{" + str + "}";
            else
                Restr = Temp.Info.ToString();
            return Restr;
        }


        /// <summary>
        /// 处理系统标签
        /// </summary>
        /// <param name="Temp"></param>
        /// <returns></returns>
        private string SYFunction(TSystemLable Temp)
        {
            string Mode = "";
            Mode = this.StrModule;
            string Restr = "";
            switch (Temp.Title.ToString().ToUpper())
            {
                case "DIY_NEWSINFO":            //资讯详细信息
                    Restr = clsNewslable.DIY_NewsInfo(Temp);
                    break;
                case "SY_RELATEDNEWS":          //相关资讯
                    Restr = clsNewslable.SY_RelatedNews(Temp);
                    break;
                case "SY_NEWSLIST_PIC":         //资讯图文列表
                    Restr = clsNewslable.SY_NewsList_Pic(Temp);
                    break;
                case "SY_DIGGLIST":         //资讯图文列表
                    Restr = clsNewslable.SY_DiggList(Temp, Mode);
                    break;
                case "SY_NEWSINFOTYPE":         //资讯类别
                    Restr = clsNewslable.SY_NewsType(Temp);
                    break;
                case "SY_NEWSLIST_STR":         //资讯文字列表
                    Restr = clsNewslable.SY_NewsList_Str(Temp);
                    break;
                case "DIY_NEWSLIST":          //自定义供应信息
                    Restr = clsNewslable.DIY_NewsList(Temp, Mode);
                    break;
                case "DIY_SUPPLYINFO":          //自定义供应信息
                    Restr = clsProductLable.DIY_SupplyInfo(Temp);
                    break;
                case "DIY_PRODUCTINFO":          //自定义求购信息
                    Restr = clsProductLable.DIY_ProductInfo(Temp);
                    break;
                case "SY_WEBLOGO":              //网站LOGO
                    Restr = systemic.SY_WebLogo(Temp);
                    break;
                case "SY_PRODUCTLIST_PIC":      //产品图文列表
                    Restr = clsProductLable.SY_Productlist_Pic(Temp);
                    break;
                case "SY_PRODUCTLIST_STR":      //产品图文列表
                    Restr = clsProductLable.SY_Productlist_Str(Temp);
                    break;
                case "SY_POSTS":                //网站公告
                    Restr = systemic.SY_Posts(Temp);
                    break;
                case "SY_LINKS":                //友情链接
                    Restr = systemic.SY_Links(Temp);
                    break;
                case "DIY_USERINFO":            //会员信息
                    Restr = clsUserlable.DIY_UserInfo(Temp, Mode);
                    break;
                case "DIY_PURCHASELIST":        //求购详细信息列表
                    Restr = clsProductLable.DIY_Purchaselist(Temp, Mode);
                    break;
                case "DIY_SUPPLYLIST":          //求购详细信息列表
                    Restr = clsProductLable.DIY_Supplylist(Temp, Mode);
                    break;
                case "SY_COMPANYLIST_PIC":      //求购详细信息列表
                    Restr = clsUserlable.SY_Companylist_Pic(Temp);
                    break;
                case "SY_INDUSTRY":             //求购详细信息列表
                    Restr = systemic.SY_Industry(Temp);
                    break;
                case "SY_EXPO_PIC":             //展会图文列表
                    Restr = clsExpoLable.SY_Expo_Pic(Temp);
                    break;
                case "SY_EXPO_STR":             //展会图文列表
                    Restr = clsExpoLable.SY_Expo_Str(Temp);
                    break;
                case "DIY_EXPOINFO":             //展会图文列表
                    Restr = clsExpoLable.DIY_ExpoInfo(Temp);
                    break;
                case "SY_EXPONEWS_PIC":         //展会资讯图文列表
                    Restr = clsExpoLable.SY_ExpoNews_Pic(Temp);
                    break;
                case "SY_EXPONEWS_STR":         //展会资讯文字列表
                    Restr = clsExpoLable.SY_ExpoNews_Str(Temp);
                    break;
                case "DIY_EXPOLIST":            //展会图文列表
                    Restr = clsExpoLable.DIY_ExpoList(Temp);
                    break;
                case "DIY_EXPOTRADELIST":       //展会图文列表
                    Restr = clsExpoLable.DIY_ExpoTradelist(Temp, Mode);
                    break;
                case "DETAILNEWPRODUCT":        //供应详细页
                    Restr = clsProductLable.SY_DetailNewProduct(Temp);
                    break;
                case "SY_AGENTLIST_PIC":        //创业加盟图文
                    Restr = clsAgentLable.SY_AgentList_Pic(Temp);
                    break;
                case "SY_AGENTLIST_STR":       //创业加盟文字
                    Restr = clsAgentLable.SY_AgentList_Str(Temp);
                    break;
                case "SY_DETAILNEWPRODUCT":       //创业加盟文字
                    Restr = clsProductLable.SY_DetailNewProduct(Temp);
                    break;
                case "SY_COMPANYLIST_STR":       //创业加盟文字
                    Restr = clsUserlable.SY_CompanyList_Str(Temp);
                    break;
                //case "DIY_SAGENTLIST":       //创业加盟文字
                //    Restr = clsAgentLable.DIY_STradelist(Temp, Mode);
                //    break;
                case "DIY_WAGENTLIST":       //创业加盟文字
                    Restr = clsAgentLable.DIY_Tradelist(Temp, Mode);
                    break;
                //case "DIY_SAGENTINFO":       //创业加盟
                //    Restr = clsAgentLable.DIY_SAgentInfo(Temp);
                //    break;
                case "DIY_SAGENTINFO":       //愿做代理
                    Restr = clsAgentLable.DIY_WAgentInfo(Temp);
                    break;
                case "DIY_COMPANYLIST":
                    Restr = clsUserlable.DIY_Companylist(Temp, Mode);
                    break;
                default:
                    Restr = "不存在此类型标签";
                    break;
            }
            return Restr;
        }


        /// <summary>
        /// 获取方法名称
        /// </summary>
        /// <param name="parame"></param>
        /// <returns></returns>
        private string tempTitle(string parame)
        {
            int nstart = parame.IndexOf("(");
            return parame.Substring(0, nstart);
        }


        /// <summary>
        /// 获取参数列表
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string tempInfo(string str)
        {
            int nstart = str.IndexOf("(");
            int nend = str.IndexOf(")");
            return str.Substring(nstart + 1, nend - nstart - 1);
        }


        /// <summary>
        /// 获取标签名称
        /// </summary>
        /// <param name=""></param>
        private string staticTitle(string str)
        {
            int no = str.Length - 2;
            return str.Substring(1, no);
        }


        /// <summary>
        /// 取得系统标签所需信息
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private TSystemLable Get_Function(string str)
        {
            TSystemLable Temp = new RSystemLable().GateItem(str);
            return Temp;
        }
    }
}