using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text;
using System.Data.SqlClient;
using nspProduct;

namespace nspLable.Function.Systems
{
    /// <summary>
    /// Products 的摘要说明
    /// </summary>
    public class clsProducts
    {
        public clsProducts()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }


        /// <summary>
        /// 处理产品索引首页私有标签
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string PR_ProductIndex(string Restr, string str)
        {
            // 分解传递过来的数据，取得模板内所有的私有标签
            string[] strArray;
            strArray = str.Split('|');
            int ID = 0;
            // ID = Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]);
            // if (ID <= 0) throw new Exception(Function.ErrInfo(1));
            // Expo.TExpoType Items = new Expo.RExpoType().GateItem(ID);
            System.Collections.Hashtable DataHash = new System.Collections.Hashtable();
            DataHash["{PR_TITLE}"] = "产品索引首页";
            DataHash["{PR_METAKEYWORDS}"] = "关键字";
            DataHash["{PR_METADESCRIPTION}"] = "描述";
            try
            {
                for (int i = 0; i < strArray.Length; i++)
                {

                    Restr = Restr.Replace(strArray[i].ToString(), DataHash["{PR_TITLE}"].ToString());
                    //switch (strArray[i].ToString().ToUpper())
                    //{
                    //    case "{PR_TITLE}":
                    //        Restr = Restr.Replace(strArray[i].ToString(), "产品索引首页");
                    //        break;
                    //    case "{PR_METAKEYWORDS}":              //MATE关键字
                    //        Restr = Restr.Replace(strArray[i].ToString(), "");
                    //        break;
                    //    case "{PR_METADESCRIPTION}":          //MATE
                    //        Restr = Restr.Replace(strArray[i].ToString(), "");
                    //        break;
                    //    default:
                    //        break;
                    //}
                }
            }
            catch (Exception e)
            {
                //Restr = e.Message.ToString();
                return Restr;
            }
            return Restr;
        }


        /// <summary>
        /// 处理产品索引分类页私有标签
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string PR_ProductTrade(string Restr, string str)
        {
            // 分解传递过来的数据，取得模板内所有的私有标签
            string[] strArray;
            strArray = str.Split('|');
            int ID = 0;
            if (HttpContext.Current.Request.QueryString["id"] != null && HttpContext.Current.Request.QueryString["id"] != "")
            {
                ID = Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);
            }
            // ID = Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]);
            // if (ID <= 0) throw new Exception(Function.ErrInfo(1));
            // Expo.TExpoType Items = new Expo.RExpoType().GateItem(ID);
            System.Collections.Hashtable DataHash = new System.Collections.Hashtable();
            DataHash["{PR_TITLE}"] = "产品索引首页";
            DataHash["{PR_METAKEYWORDS}"] = "关键字";
            DataHash["{PR_METADESCRIPTION}"] = "描述";
            try
            {
                for (int i = 0; i < strArray.Length; i++)
                {
                    switch (strArray[i].ToString().ToUpper())
                    {
                        case "{PR_TITLE}":
                            Restr = Restr.Replace(strArray[i].ToString(), "产品索引首页");
                            break;
                        case "{PR_METAKEYWORDS}":              //MATE关键字
                            Restr = Restr.Replace(strArray[i].ToString(), "");
                            break;
                        case "{PR_METADESCRIPTION}":          //MATE
                            Restr = Restr.Replace(strArray[i].ToString(), "");
                            break;
                        case "{PR_PRODUCTLIST}":          //MATE
                            Restr = Restr.Replace(strArray[i].ToString(), PR_ProductList());
                            break;
                        case "{PR_LOWERTYPE}":
                            Restr = Restr.Replace(strArray[i].ToString(), systemic.lowerType(ID, "Product")); ;
                            break;
                        case "{PR_TYPELINK}":
                            string strTypeLink = "";
                            strTypeLink = TypeLink(ID.ToString(), "Trade");
                            Restr = Restr.Replace(strArray[i].ToString(), strTypeLink);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Restr = e.Message.ToString();
                return Restr;
            }
            return Restr;
        }


        /// <summary>
        /// 处理产品索引详细页私有标签
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string PR_ProductDetail(string Restr, string str)
        {
            // 分解传递过来的数据，取得模板内所有的私有标签
            string[] strArray;
            strArray = str.Split('|');
            int ID = 0;
            if (HttpContext.Current.Request.QueryString["id"] != null && HttpContext.Current.Request.QueryString["id"] != "")
            {
                ID = Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]);
            }
            if (ID <= 0) throw new Exception(Function.ErrInfo(1));
            clsTProduct Items = new clsRProduct().GetItems(ID);
            System.Collections.Hashtable DataHash = new System.Collections.Hashtable();
            DataHash["{PR_TITLE}"] = "产品索引首页";
            DataHash["{PR_METAKEYWORDS}"] = "关键字";
            DataHash["{PR_METADESCRIPTION}"] = "描述";
            DataHash["{PR_ PICTURE}"] = "描述";
            DataHash["{PR_INFO}"] = "描述";
            DataHash["{PR_SUPPLIERLIST}"] = "描述";
            try
            {
                for (int i = 0; i < strArray.Length - 1; i++)
                {
                    // Restr = Restr.Replace(strArray[i].ToString(), DataHash[strArray[i].ToUpper()].ToString());
                    switch (strArray[i].ToString().ToUpper())
                    {
                        case "{PR_NAME}":
                            Restr = Restr.Replace(strArray[i].ToString(), Items.Name);
                            break;
                        case "{PR_METAKEYWORDS}":              //MATE关键字
                            Restr = Restr.Replace(strArray[i].ToString(), Base.XMLProcess.Read("Xml/Meta.xml", "/config/meta[@typeid='expo_trade']/keywords"));
                            break;
                        case "{PR_METADESCRIPTION}":          //MATE
                            Restr = Restr.Replace(strArray[i].ToString(), Base.XMLProcess.Read("Xml/Meta.xml", "/config/meta[@typeid='expo_trade']/descriptions"));
                            break;
                        case "{PR_PICTURE}":
                            Restr = Restr.Replace(strArray[i].ToString(), "<img src=\"" + Function.ProcessImageUrl(Items.Picture) + "\">");
                            break;
                        case "{PR_INFO}":
                            Restr = Restr.Replace(strArray[i].ToString(), Items.Detail);
                            break;
                        case "{PR_SUPPLIERLIST}":
                            Restr = Restr.Replace(strArray[i].ToString(), SupplierList(Items.ID.ToString()));
                            break;
                        case "{PR_TYPELINK}":
                            string strTypeLink = "";
                            strTypeLink = TypeLink(ID.ToString(), "Detail");
                            Restr = Restr.Replace(strArray[i].ToString(), strTypeLink);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Restr = e.Message + str + Restr;
                return Restr;
            }
            return Restr;
        }
        ///   <summary>    
        ///   将指定字符串按指定长度进行剪切，    
        ///   </summary>    
        ///   <param   name= "oldStr "> 需要截断的字符串 </param>    
        ///   <param   name= "maxLength "> 字符串的最大长度 </param>    
        ///   <param   name= "endWith "> 超过长度的后缀 </param>    
        ///   <returns> 如果超过长度，返回截断后的新字符串加上后缀，否则，返回原字符串 </returns>   
        //public static string StringTruncat(string oldStr, int maxLength, string endWith)
        //{
        //    if (string.IsNullOrEmpty(oldStr))
        //        //   throw   new   NullReferenceException( "原字符串不能为空 ");    
        //        return oldStr + endWith;
        //    if (maxLength < 1)
        //        throw new Exception("返回的字符串长度必须大于[0] ");
        //    if (oldStr.Length > maxLength)
        //    {
        //        string strTmp = oldStr.Substring(0, maxLength);
        //        if (string.IsNullOrEmpty(endWith))
        //            return strTmp;
        //        else
        //            return strTmp + endWith;
        //    }
        //    return oldStr;
        //} 


        /// <summary>
        /// 产品索引列表
        /// </summary>
        /// <param name="TypeID"></param>
        /// <returns></returns>
        private static String PR_ProductList()
        {
            string strWhere = "";
            string strTypeID = "0";
            if (HttpContext.Current.Request.QueryString["id"] != null && HttpContext.Current.Request.QueryString["id"] != "")
            {
                if (Base.Common.CheckNum(HttpContext.Current.Request.QueryString["ID"]))
                {
                    strTypeID = HttpContext.Current.Request.QueryString["ID"];
                    strWhere = " TypeID like '%" + strTypeID + "%'";
                }
            }
            // 取得用户设置的参数
            string[] strContent;
            // strContent = Array.Info.Split(new char[] { '|' });

            int PageID = 1;
            if (HttpContext.Current.Request.QueryString["Page"] != null && HttpContext.Current.Request.QueryString["Page"] != "")
            {
                if (Base.Common.CheckNum(HttpContext.Current.Request.QueryString["Page"]))
                {
                    PageID = Convert.ToInt32(HttpContext.Current.Request.QueryString["Page"]);
                }
            }
            // 定义全局变量，最后返回
            StringBuilder ReBulider = new StringBuilder();

            int PageSize = 10;
            string strTable = "W_Products";

            // 获取求购信息
            DataTable Lists = Pagination.GetDataTable(strWhere, strTable, 1, "AddDate", "*", PageSize, PageID, 0);
            if (Lists.Rows.Count < 0)
            {
                ReBulider.Append("暂无此类产品");
            }
            else
            {
                for (int i = 0; i < Lists.Rows.Count; i++)
                {
                    ReBulider.Append("<div class=\"product_list\">\r\n");
                    ReBulider.Append("<div class=\"induction\">\r\n");
                    ReBulider.Append("<dl>\r\n");
                    ReBulider.Append("<dt><span class=\"C_raght\"><a href=\"Detail-" + Lists.Rows[i]["id"] + Base.BasePage.Config.Rewrite + "\" target=\"_blank\">更多供应商</a></span>");
                    ReBulider.Append("<a href=\"Detail-" + Lists.Rows[i]["id"] + Base.BasePage.Config.Rewrite + "\" target=\"_blank\" class=\"a2\">" + Lists.Rows[i]["Name"] + "</a></dt>\r\n");
                    ReBulider.Append("<dd class=\"img\"><img src=\"" + Lists.Rows[i]["Picture"] + "\" width=\"90\" height=\"90\"></dd>\r\n");

                    ReBulider.Append("<dd class=\"text\">" + Function.GetString(Lists.Rows[i]["Detail"].ToString(), 200) + "..." + "</dd>\r\n");
                    ReBulider.Append("</dl>\r\n");
                    ReBulider.Append("</div>\r\n");
                    ReBulider.Append("<div class=\"incompany\"><span class=\"C_raght\"><a href=\"../Member/index.aspx\" target=\"_blank\">立即加入</a></span>推荐供应商</div>\r\n");
                    ReBulider.Append("<div class=\"incompany_cont\">" + SupplierList(Lists.Rows[i]["id"].ToString()) + "</div>\r\n");
                    ReBulider.Append("</div>\r\n");
                    if (i > 9) break; //如果超过显示的条数则跳出。
                }
            }
            string strUrl = "{PB_WebURL}Product/Trade";
            if (PageID <= 0) PageID = 1;
            if (strTypeID != "0")
            {
                strUrl += "-" + strTypeID;
            }
            strUrl += "-p";

            string Pages = Pagination.GoToPager(PageID, PageSize, strUrl, strWhere, strTable);
            ReBulider.Append(Pages);


            return ReBulider.ToString();
        }

        /// <summary>
        /// 供应商列表
        /// </summary>
        /// <returns></returns>
        private static string SupplierList(string strProductID)
        {
            string strWhere = "";
            strWhere = "ProductID=" + strProductID;
            StringBuilder strBuilder = new StringBuilder();
            try
            {
                DataTable Lists = Pagination.GetDataTable(strWhere, "W_UsersProducts inner join U_UserInfo on W_UsersProducts.UserID=U_UserInfo.UserID", 1, "Sort", "U_UserInfo.UserID,U_UserInfo.LoginName,U_UserInfo.CompanyName", 9, 1, 0);
                int intCount = Lists.Rows.Count;
                int intRow = 0;
                int intCell = 3;
                intRow = intCount % intCell == 0 ? intCount / intCell : intCount / intCell + 1;
                strBuilder.Append("<table width='100%'  border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" + "\r\n ");
                for (int i = 0; i < intRow; i++)
                {
                    strBuilder.Append("<tr>");
                    for (int j = 0; j < intCell; j++)
                    {
                        int m = i * intCell + j;
                        if (m > 9 || m >= intCount) break; //如果超过显示的条数则跳出。
                        strBuilder.Append("<td><a href=\"/Shop/index/");
                        strBuilder.Append(Lists.Rows[m]["LoginName"] + Base.BasePage.Config.Rewrite);
                        strBuilder.Append("\">" + Lists.Rows[m]["CompanyName"].ToString() + "</a></td>");
                    }
                    strBuilder.Append("</tr>");
                }
                strBuilder.Append("</table>");
                return strBuilder.ToString();
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }



        /// <summary>
        /// 行业类别链表
        /// </summary>
        /// <param name="strType">行业ID字符串</param>
        /// <param name="param">Trade:分类页, Detail:详细页</param>
        /// <returns></returns>
        private static string TypeLink(string strTypeLink, string param)
        {
            if (strTypeLink[strTypeLink.Length - 1] == ',')
            {
                strTypeLink = strTypeLink.Substring(0, strTypeLink.Length - 1);
            }
            try
            {
                DataTable TypeData = new DataTable();
                if (param == "Detail")
                {
                    TypeData = Function.GetDataTable("Type,ID", "where ID in(" + strTypeLink + ") ", "W_IndustryType", " order by SuperiorsFlag  ");
                }
                else
                {
                    SqlParameter[] param1 = new SqlParameter[] 
                    {  
                        new SqlParameter("@ID",Convert.ToInt32(strTypeLink))
                    };
                    TypeData = SqlOperate.SqlHelper.ExecuteTable(CommandType.StoredProcedure, "SP_W_TypeLink", param1);
                }
                string strType = "";
                string str = "<a href=\"trade-";

                if (TypeData.Rows.Count > 0)
                {
                    for (int i = 0; i < TypeData.Rows.Count; i++)
                    {
                        strType += " > " + str;
                        strType += TypeData.Rows[i]["id"].ToString();
                        strType += Base.BasePage.Config.Rewrite + "\">";
                        strType += TypeData.Rows[i]["Type"].ToString();
                        strType += "</a>";
                    }
                }
                return strType;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

    }
}