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 nspLable.Manage;
using System.Text;
using Base;
using nspKnow;

namespace nspLable.Function.Systems
{
    /// <summary>
    /// Know 的摘要说明
    /// </summary>
    public class clsKnow : nspLable.Function.Systems.systemic
    {
        /// <summary>
        ///  知道问题列表
        /// </summary>
        /// <param name="Array">
        /// State 问题状态
        /// TitleSize 标题长度
        /// Num 显示条数
        /// </param>
        /// <returns></returns>
        public static string DIY_KnowProblemsList(TSystemLable Array, string strModel)
        {
            StringBuilder ReBulider = new StringBuilder();
            // 分解的参数信息
            string[] strContent;
            strContent = Array.Info.Split(new char[] { '|' });

            //初始化参数,
            if (strContent.Length != 3) throw new Exception("0"); ; //如果参数不够则跳出
            string State = strContent[0].ToString();
            int TitleSize = Convert.ToInt32(strContent[1].ToString());
            int Num = Convert.ToInt32(strContent[2].ToString());
            string Title = "", type = "";
            string strUrl = "{PB_WebURL}Know/Trade";

            StringBuilder strWhere = new StringBuilder();
            string strSelect;
            string TypeID = "0";
            string table = "W_KnowProblems as a inner join W_KnowType b on a.TypeID=b.ID";
            strSelect = "a.ID,a.UserName,a.Caption,a.AddDate,a.AnswerCount,a.State,b.Name";
            int PageSize = Num;        //每页显示几条
            int PageIndex = 1;        //第几页
            if (HttpContext.Current.Request.QueryString["Page"] != null || HttpContext.Current.Request.QueryString["Page"] != "")
                PageIndex = Convert.ToInt32(HttpContext.Current.Request.QueryString["Page"]);
            if (PageIndex < 1) PageIndex = 1;
            strWhere.Append("1=1 ");
            switch (State)
            {
                case "0":
                    break;
                case "1":   //已解
                    strWhere.Append("and State = 1");
                    break;
                case "2":   //待解
                    strWhere.Append("and State = 0");
                    break;
                default:    // 自行匹配
                    if (HttpContext.Current.Request.QueryString["Type"] != null && HttpContext.Current.Request.QueryString["Type"] != "")
                    {
                        type = HttpContext.Current.Request.QueryString["Type"].ToString();
                        if (type == "1")
                        {
                            strWhere.Append(" and  State=1");
                            strUrl += "-01";
                        }
                        else if (type == "2")
                        {
                            strWhere.Append(" and State=0");
                            strUrl += "-02";
                        }
                    }
                    break;
            }
            if (Function.CheckQueryStringisInt("ID"))
            {
                string strSql = "";
                TypeID = HttpContext.Current.Request.QueryString["ID"];
                DataTable dt = Function.GetDataTable("SELECT ID FROM W_KnowType WHERE ParentID=" + TypeID);
                if (dt.Rows.Count != 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        strSql += dt.Rows[i]["ID"].ToString() + ",";
                    }
                    strSql += TypeID;
                    strWhere.Append("and TypeID in (" + strSql + ")");
                }
                else
                    strWhere.Append("and TypeID=" + TypeID);
                if (TypeID != "0")
                    strUrl += "-" + TypeID;
            }
            else
            {
                if (HttpContext.Current.Request.QueryString["ID"] == "01")
                {
                    strWhere.Append(" and State=1");
                    strUrl += "-01";
                }
                else if (HttpContext.Current.Request.QueryString["ID"] == "02")
                {
                    strWhere.Append(" and State=0");
                    strUrl += "-02";
                }
            }
            if (HttpContext.Current.Request.Form["keywords"] != null && HttpContext.Current.Request.Form["keywords"] != "")
            {
                Title = HttpContext.Current.Request.Form["keywords"];
                strWhere.Append("and  a.Caption like '%" + Title + "%'");
            }
            DataTable Lists = Pagination.GetDataTable(strWhere.ToString(), table, 1, "a.AddDate", strSelect, PageSize, PageIndex, 0);
            if (Lists.Rows.Count < 0)
            {
                ReBulider.Append("暂无此类产品");
            }
            else
            {
                string strInfo = Array.Content.ToString();
                string[] strAtttibute = Function.GetAttribute(strInfo);
                for (int i = 0; i < Lists.Rows.Count; i++)
                {
                    strInfo = Array.Content.ToString();
                    for (int j = 0; j < strAtttibute.Length; j++)
                    {
                        switch (strAtttibute[j].ToString())
                        {
                            case "{PR:WS_Type}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Lists.Rows[i]["Name"].ToString());
                                break;
                            case "{PR:WS_ID}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Lists.Rows[i]["ID"].ToString());
                                break;
                            case "{PR:WS_Caption}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), new Common().GetString(Lists.Rows[i]["Caption"].ToString(), 0, TitleSize));
                                break;
                            case "{PR:WS_AddDate}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Function.DateTransform(Lists.Rows[i]["AddDate"].ToString(), "yyyy-mm-dd"));
                                break;
                            case "{PR:WS_UserName}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Lists.Rows[i]["UserName"].ToString());
                                break;
                            case "{PR:WS_WebUrl}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Base.BasePage.Config.WebURL + "Know/Detail-" + Lists.Rows[i]["ID"] + Base.BasePage.Config.Rewrite);
                                break;
                            case "{PR:WS_State}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), "<img src='" + Base.BasePage.Config.WebURL + "Images/state_0.gif" + "'/>");
                                break;
                            case "{PR:WS_AnswerCount}":
                                strInfo = strInfo.Replace(strAtttibute[j].ToString(), Lists.Rows[i]["AnswerCount"].ToString());
                                break;
                        }
                    }
                    ReBulider.Append(strInfo);
                }
            }
            strUrl += "-p";
            if (strModel == "Know_Trade")
            {
                string strPagion = Pagination.GoToPager(PageIndex, PageSize, strUrl, strWhere.ToString(), table);
                ReBulider.Append(strPagion);
            }

            return ReBulider.ToString();


        }

        /// <summary>
        /// 知道问题详细内容标签
        /// </summary>
        /// <param name="Array"></param>
        /// <returns></returns>
        public static string DIY_KnowProblemsInfo(TSystemLable Array)
        {
            int intID = 0;
            if (intID < 0) throw new Exception(Function.ErrInfo(1));
            intID = Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]); //取得问题 ID
            string strContent = Array.Content.ToString();

            KnowProblem tProblem = new KnowProblem().GetItem(intID);
            string[] strAtttibute = Function.GetAttribute(strContent);   // 查询属性
            StringBuilder strBuilde = new StringBuilder();
            if (strAtttibute.Length != 0)
            {
                for (int i = 0; i < strAtttibute.Length; i++)
                {
                    switch (strAtttibute[i].ToString())
                    {
                        case "{PR:WS_Type}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.TypeID.ToString());
                            break;
                        case "{PR:WS_ID}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.ID.ToString());
                            break;
                        case "{PR:WS_Caption}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.Caption.ToString());
                            break;
                        case "{PR:WS_AddDate}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.AddDate.ToString());
                            break;
                        case "{PR:WS_UserName}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.UserName.ToString());
                            break;
                        case "{PR:WS_Detail}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), tProblem.Detail.ToString());
                            break;
                        case "{PR:WS_WebUrl}":
                            strContent = strContent.Replace(strAtttibute[i].ToString(), Base.BasePage.Config.WebURL + "Know/MyAnswer-" + intID + Base.BasePage.Config.Rewrite);
                            break;
                        case "{PR:WS_State}":
                            if (tProblem.State == true)
                                strContent = strContent.Replace(strAtttibute[i].ToString(), "已解决问题");
                            else
                                strContent = strContent.Replace(strAtttibute[i].ToString(), "待解决问题");
                            break;
                    }
                }
            }
            return strContent;
        }

        /// <summary>
        /// 问题答复
        /// </summary>
        /// <param name="Array"></param>
        /// <returns></returns>
        public static string DIY_KnowAnswerInfo(TSystemLable Array)
        {
            string strInfo = Array.Info;
            int intID = 0;
            intID = Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]); //取得问题ID
            if (intID < 0) throw new Exception(Function.ErrInfo(1));
            string strContent = Array.Content.ToString();
            string strWhere = "";
            string strTable = "W_KnowProblems as a inner join W_KnowAnswer as b on a.ID=b.ProblemsID";
            string strSelect = "a.UserID,a.Caption,a.State as finish,a.AnswerCount,b.AddDate,b.Detail,b.State,b.ID,b.UserName,b.IP";
            strWhere += "where b.ProblemsID=" + intID;
            strWhere += " and b.State=" + strInfo;
            DataTable dt = Function.GetDataTable(strSelect, strWhere, strTable, "order by b.AddDate desc");
            if (dt.Rows.Count < 0)
            {
                strContent = "暂无此类产品";
            }
            string strBody = "";
            string[] strAtttibute = Function.GetAttribute(strContent);   // 查询属性
            if (strAtttibute.Length != 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < strAtttibute.Length - 1; j++)
                    {
                        switch (strAtttibute[j].ToString())
                        {

                            case "{PR:WS_ID}":
                                strContent += strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["ID"].ToString());
                                break;
                            case "{PR:WS_AddDate}":
                                strContent = strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["AddDate"].ToString());
                                break;
                            case "{PR:WS_UserName}":
                                if (dt.Rows[i]["UserName"].ToString() != "")
                                    strContent = strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["UserName"].ToString());
                                else
                                    strContent = strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["IP"].ToString());
                                break;
                            case "{PR:WS_Detail}":
                                strContent = strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["Detail"].ToString());
                                break;
                            case "{PR:WS_State}":
                                if (dt.Rows[i]["UserID"].ToString() == GetRequest.GetCookie("UserID"))
                                {
                                    if (dt.Rows[i]["State"].ToString() == "False" && dt.Rows[i]["finish"].ToString() == "False")
                                    {

                                        StringBuilder strState = new StringBuilder();
                                        strState.Append(@"<form method='post' action='{PB_WebURL}Know/KnowAccept");
                                        strState.Append(Base.BasePage.Config.Rewrite);
                                        strState.Append(@"'>");
                                        strState.Append(@"<input type='hidden' name='ProblemsID' value='" + intID + "'><input type='hidden' name='AnswerID' value='" + dt.Rows[i]["ID"].ToString() + "'><input type='hidden' name='state' value='" + dt.Rows[i]["State"].ToString() + "'><input type='submit' name='subState' value='采纳为正确答案'>");
                                        strState.Append(@"</form>");
                                        strContent = strContent.Replace(strAtttibute[j].ToString(), strState.ToString());
                                    }

                                }
                                if (dt.Rows[i]["State"].ToString() == "True")
                                    strContent = strContent.Replace(strAtttibute[j].ToString(), "<img src='" + Base.BasePage.Config.WebURL + "Images/best_0.gif" + "'/>");
                                else
                                    strContent = strContent.Replace(strAtttibute[j].ToString(), "");
                                break;
                            case "{PR:WS_AnswerCount}":
                                strContent = strContent.Replace(strAtttibute[j].ToString(), dt.Rows[i]["AnswerCount"].ToString());
                                break;
                        }
                    }
                    strBody += strContent;
                    strContent = Array.Content.ToString();
                }
            }
            return strBody;
        }

        /// <summary>
        /// 处理知道类别页的私有变量
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string PR_KnowTrade(string Restr, string str)
        {
            // 分解传递过来的数据，取得模板内所有的私有标签
            string[] strArray;
            strArray = str.Split('|');
            DataTable dt = new DataTable();
            if (Function.CheckQueryStringisInt("ID"))
            {
                string strSql = "";
                string TypeID = HttpContext.Current.Request.QueryString["ID"];
                dt = Function.GetDataTable("SELECT Name FROM W_KnowType WHERE ID=" + TypeID);
            }
            try
            {
                for (int i = 0; i < strArray.Length; i++)
                {
                    switch (strArray[i].ToString().ToUpper())
                    {
                        case "{PR_KNOWTYPE}":
                            Restr = Restr.Replace(strArray[i].ToString(), KnowTypeList());
                            break;
                        case "{PR_SEARCH}":
                            Restr = Restr.Replace(strArray[i].ToString(), GetSearchTemp());
                            break;
                        case "{PR_SUBANSWER}":
                            Restr = Restr.Replace(strArray[i].ToString(), GetAnswerTemp());
                            break;
                        case "{PR_KEYWORD}":
                            if (dt.Rows.Count > 0)
                                Restr = Restr.Replace(strArray[i].ToString(), dt.Rows[0]["Name"].ToString());
                            else
                                Restr = Restr.Replace(strArray[i].ToString(), "");
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Restr = e.Message.ToString();
            }
            return Restr;
        }

        /// <summary>
        /// 知道详细页私有变量处理方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string PR_KnowDetail(string Restr, string str)
        {
            // 分解传递过来的数据，取得模板内所有的私有标签
            string[] strArray;
            strArray = str.Split('|');
            if (Function.CheckQueryStringisInt("ID"))
            {
                int id = int.Parse(HttpContext.Current.Request.QueryString["ID"].ToString());
                KnowProblem Items = new KnowProblem().GetItem(id);
                try
                {
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        switch (strArray[i].ToString().ToUpper())
                        {
                            case "{PR_KNOWTYPE}":
                                Restr = Restr.Replace(strArray[i].ToString(), KnowTypeList());
                                break;
                            case "{PR_SEARCH}":
                                Restr = Restr.Replace(strArray[i].ToString(), GetSearchTemp());
                                break;
                            case "{PR_SUBANSWER}":
                                Restr = Restr.Replace(strArray[i].ToString(), GetAnswerTemp());
                                break;
                            case "{PR_KEYWORD}":
                                Restr = Restr.Replace(strArray[i].ToString(), Items.Caption);
                                break;
                            default:
                                break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Restr = e.Message.ToString();
                }
            }
            return Restr;
        }

        /// <summary>
        /// 知道分类
        /// </summary>
        /// <param>
        /// WhichType：     知道类别
        /// BigNum：        显示大类数量
        /// BigClass：      大类样式
        /// RowsNum：       每行显示几条
        /// BackColor：     背景交替颜色
        /// ShowSmall：     是否显示小类（0：显示，1：不显示）
        /// SmallNum：      小类个数
        /// SmallRowsNum：  小类每行显示几条
        /// SmallSize：     小类字数
        /// SmallClass：    小类样式
        /// </param>
        /// <returns></returns>
        public static string KnowTypeList()
        {
            string WhichType = "Know";
            int BigNum = 20;
            string BigClass = "";
            int RowsNum = 1;
            string BackColor = "";
            int ShowSmall = 0;
            int SmallNum = 10;
            int SmallRowsNum = 10;
            int SmallSize = 6;
            string SmallClass = "";
            string More = "0";

            //需要取得的数据
            string strSelect = "";
            //读取几条信息
            if (BigNum <= 0)
                strSelect = "top 1  ID,Name,ParentID";
            else
                strSelect = " top " + BigNum + " ID,Name,ParentID ";
            //查询条件
            string strWhere = "";
            strWhere += " where  ParentID=0";
            //要查询的表
            string strTableName = "W_KnowType";
            //排序方式
            string strOrder = "";
            strOrder += " order by AddDate asc";
            //返回查询结果
            DataTable Lists = Function.GetDataTable(strSelect, strWhere.ToString(), strTableName, strOrder);
            StringBuilder strBuilder = new StringBuilder();
            //是否存在行业
            if (Lists.Rows.Count > 0)
            {
                int intCount = Lists.Rows.Count;
                int intRow = 0;
                int intCell = RowsNum;
                intRow = intCount % intCell == 0 ? intCount / intCell : intCount / intCell + 1;

                for (int i = 0; i < intRow; i++)
                {
                    if ((i + 1) % 2 == 0)
                        strBuilder.Append("<div class=" + BackColor + ">" + "\r\n ");
                    strBuilder.Append("<div class=\"classknow\">" + "\r\n ");
                    for (int j = 0; j < intCell; j++)
                    {
                        int ic = i * intCell + j;
                        if (ic > BigNum || ic >= Lists.Rows.Count) break; //如果超过显示的条数则跳出。
                        if (j == 0)
                            strBuilder.Append(@"<dl><dt>" + "\r\n ");
                        else
                            strBuilder.Append("<dl class=\"classleft\"><dt>");
                        switch (WhichType)
                        {
                            case "Know":
                                strBuilder.Append("<a href=\"{PB_WebURL}Know/Trade-");
                                break;
                            default:
                                strBuilder.Append("<a href=\"{PB_WebURL}Know/Trade-");
                                break;
                        }
                        strBuilder.Append(Lists.Rows[ic]["ID"].ToString());
                        strBuilder.Append(Base.BasePage.Config.Rewrite + "\">");
                        strBuilder.Append(Lists.Rows[ic]["Name"].ToString());
                        strBuilder.Append("</a> " + "\r\n ");


                        //显示下级分类
                        if (ShowSmall == 0)
                        {
                            strBuilder.Append("</dt>" + "\r\n " + "<dd>");
                            strBuilder.Append(SmallKnowType(Lists.Rows[ic]["ID"].ToString(), WhichType, SmallNum, SmallRowsNum, SmallSize, SmallClass, More));
                            strBuilder.Append("</dd>");
                        }
                        strBuilder.Append("</dl>");
                    }
                    strBuilder.Append("</div>" + "\r\n ");
                    if ((i + 1) % 2 == 0)
                        strBuilder.Append("</div>" + "\r\n ");
                }
            }
            else
            {
                strBuilder.Append(@"暂无行业分类");
            }
            return strBuilder.ToString();
        }

        /// <summary>
        ///  知道下级分类
        /// </summary>
        /// <param Nam="ID">上级ID</param>
        /// <param Nam="WhitchType">供应、求购、公司</param>
        /// <param Nam="SmallNum">数量</param>
        /// <param Nam="SmallRowsNum">每行显示条数</param>
        /// <param Nam="SmallSize">显示的字数</param>
        /// <param Nam="SmallClass">Class样式</param>
        /// <param Nam="More">是否显示"更多"</param>
        /// <returns></returns>
        private static string SmallKnowType(string ID, string WhichType, int SmallNum, int SmallRowsNum, int SmallSize, string SmallClass, string More)
        {
            int intID = Convert.ToInt32(ID);

            //需要取得的数据
            string strSelect = "";
            //读取几条信息

            strSelect = "ID,Name,ParentID";

            //查询条件
            string strWhere = "";
            strWhere += " where ParentID=";
            strWhere += intID;
            //要查询的表
            string strTableName = "W_KnowType";
            //排序方式
            string strOrder = "";
            strOrder += " order by AddDate asc";
            //返回查询结果
            DataTable Lists = Function.GetDataTable(strSelect, strWhere, strTableName, strOrder);

            //设置类别的字数
            int intRowsNum = 0;
            if (SmallRowsNum > 0) intRowsNum = SmallRowsNum;
            //设置类别的字数
            int intSize = 0;
            intSize = intSize < SmallSize ? 0 : SmallSize;
            StringBuilder strBuilder = new StringBuilder();
            if (Lists.Rows.Count <= 0)
            {
                return (strBuilder.Append("暂无下级 ")).ToString();
            }
            else
            {
                for (int i = 0; i < Lists.Rows.Count; i++)
                {
                    switch (WhichType)
                    {
                        case "Know":
                            strBuilder.Append("<a href=\"{PB_WebURL}Know/Trade-");
                            break;
                        default:
                            strBuilder.Append("<a href=\"{PB_WebURL}Know/Trade-");
                            break;
                    }
                    strBuilder.Append(Lists.Rows[i]["ID"].ToString());
                    strBuilder.Append(Base.BasePage.Config.Rewrite + "\">");
                    strBuilder.Append(Lists.Rows[i]["Name"].ToString());
                    strBuilder.Append("</a>");
                    strBuilder.Append(" | " + "\r\n ");
                }
            }
            int Length = 0;
            if (More == "1")
            {
                if (Lists.Rows.Count > 0)
                {
                    strBuilder.Append("<a href=\"{PB_WebURL}Know/Trade-");
                    strBuilder.Append(Base.BasePage.Config.Rewrite + "\">");
                    strBuilder.Append("更多</span></a> " + "\r\n ");
                }
                Length = strBuilder.ToString().Length;
            }
            else
            {
                Length = strBuilder.ToString().Length - 6;
            }
            return strBuilder.ToString(0, Length);

        }

        /// <summary>
        ///  获得搜索模板内容
        /// </summary>
        /// <returns></returns>
        private static string GetSearchTemp()
        {
            string strdir = Base.XMLProcess.Read("xml/Label.config", "configuration/label[@type='Search_Question']", "path");
            string Path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "xml/" + strdir;
            string Content = Function.GetFile(Path);
            return Content;
        }

        /// <summary>
        ///  获得回答模板内容
        /// </summary>
        /// <returns></returns>
        private static string GetAnswerTemp()
        {
            string strdir = Base.XMLProcess.Read("xml/Label.config", "configuration/label[@type='Submit_Answer']", "path");
            string Path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "xml/" + strdir;
            string Content = Function.GetFile(Path);
            int KnowID = 0;
            if (GetRequest.isNum(HttpContext.Current.Request.QueryString["ID"].ToString()))
                KnowID = int.Parse(HttpContext.Current.Request.QueryString["ID"].ToString());
            KnowProblem kl = new KnowProblem().GetItem(KnowID);
            if (kl != null)
            {
                Content = Content.Replace("{PR:WS_QUESTIONTITLE}", kl.Caption);
                Content = Content.Replace("{PR:WS_UserID}", Base.GetRequest.GetCookie("UserID"));
                Content = Content.Replace("{PR:WS_ANSWERUSER}", Base.GetRequest.GetCookie("LoginName") != null ? Base.GetRequest.GetCookie("LoginName") : "匿名");
                Content = Content.Replace("{PR:WS_ANSWERIP}", Base.GetRequest.GetIP());
                Content = Content.Replace("{PR:WS_ProblemsID}", KnowID.ToString());
            }

            return Content;
        }
    }
}
