using System;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web;

namespace ynhtm.BLL
{
    using Common;
    using DBUtility;

    /// <summary>
    /// 文章操作。
    /// </summary>
    public class Post
    {
        public const string SQL_ORDER = "ORDER BY " + DAL.Post.POSTID + " DESC";

        void SetValue(Model.Post item)
        {
            item.IsPic = Regex.IsMatch(item.Content, @"<img ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            item.IsFace = !item.Face.IsNullOrWhiteSpace();
        }

        /// <summary>
        /// 插入链接实例到数据库。
        /// </summary>
        /// <param name="item">链接实例。</param>
        public void Insert(Model.Post item)
        {
            item.Url = item.Rewrite;
            this.SetValue(item);
            DAL.Post.Insert(item);
            //没有重写地址，更新地址
            if (item.Url.IsNullOrWhiteSpace())
            {
                item.Url = "/" + item.PostID;
                using (var db = DbBase.GetDb())
                    db.ExecuteNonQuery("UPDATE " + DAL.Post.SQL_TABLE + " SET " + DAL.Post.URL + " = @" + DAL.Post.URL + " WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID, db.CreateParameter(DAL.Post.POSTID, item.PostID), db.CreateParameter(DAL.Post.URL, item.Url));
            }
            using (var db = DbBase.GetDb())
                db.ExecuteNonQuery("UPDATE " + DAL.Setting.SQL_TABLE + " SET " + DAL.Setting.POSTCOUNT + " = " + DAL.Setting.POSTCOUNT + " + 1;UPDATE " + DAL.Category.SQL_TABLE + " SET " + DAL.Category.POSTCOUNT + " = " + DAL.Category.POSTCOUNT + " + 1 WHERE " + DAL.Category.CATEGORYID + " = @" + DAL.Category.CATEGORYID, db.CreateParameter(DAL.Category.CATEGORYID, item.CategoryID));
        }

        #region PostID

        /// <summary>
        /// 取得链接实例。
        /// </summary>
        /// <param name="postID">链接编号。</param>
        /// <returns>返回链接实例，没有将返回 null 。</returns>
        public Model.Post GetByPostID(int postID)
        {
            return DAL.Post.GetByPostID(postID);
        }

        /// <summary>
        /// 更新链接。
        /// </summary>
        /// <param name="item">链接实例。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int Update(Model.Post item)
        {
            item.Url = item.Rewrite.IifNullOrWhiteSpace("/" + item.PostID);
            this.SetValue(item);
            return DAL.Post.Update(item);
        }

        /// <summary>
        /// 删除链接。
        /// </summary>
        /// <param name="postID">链接编号。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int Delete(int postID)
        {
            using (var db = DbBase.GetDb())
                db.ExecuteNonQuery("UPDATE " + DAL.Setting.SQL_TABLE + " SET " + DAL.Setting.POSTCOUNT + " = " + DAL.Setting.POSTCOUNT + " - 1;UPDATE " + DAL.Category.SQL_TABLE + " SET " + DAL.Category.POSTCOUNT + " = " + DAL.Category.POSTCOUNT + " - 1 WHERE " + DAL.Category.CATEGORYID + " IN (SELECT " + DAL.Post.CATEGORYID + " FROM " + DAL.Post.SQL_TABLE + " WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID + ");" + DAL.Comment.SQL_DELETE + " WHERE " + DAL.Comment.POSTID + " = @" + DAL.Comment.POSTID, db.CreateParameter(DAL.Post.POSTID, postID));
            return DAL.Post.Delete(postID);
        }

        #endregion

        /// <summary>
        /// 取得文章分页集合。
        /// </summary>
        /// <param name="recordCount">记录总数。</param>
        /// <param name="pageSize">分页大小。</param>
        /// <param name="pageIndex">要返回的页数。</param>
        /// <param name="query">查询条件。</param>
        /// <param name="order">排序方式。</param>
        /// <returns>返回分页数据。</returns>
        public DataTable GetList(ref int recordCount, int pageSize, int pageIndex = 1, IQuery query = null, string order = SQL_ORDER)
        {
            using (var db = DbBase.GetDb())
                return db.GetPage(ref recordCount, DAL.Post.SQL_TABLE, order, pageSize, pageIndex, query, DAL.Post.SQL_FIELD);
        }

        /// <summary>
        /// 取得文章分页集合。
        /// </summary>
        /// <param name="pageSize">分页大小。</param>
        /// <param name="pageIndex">要返回的页数。</param>
        /// <param name="query">查询条件。</param>
        /// <param name="order">排序方式。</param>
        /// <returns>返回分页数据。</returns>
        public DataTable GetList(int pageSize, int pageIndex = 1, IQuery query = null, string order = SQL_ORDER)
        {
            using (var db = DbBase.GetDb())
                return db.GetPage(DAL.Post.SQL_TABLE, order, pageSize, pageIndex, query, DAL.Post.SQL_FIELD);
        }

        /// <summary>
        /// 返回文章的评论状态。
        /// </summary>
        /// <param name="postID">文章编号。</param>
        /// <returns>返回评论状态，true 表示可进行文章。</returns>
        public bool GetCommentEnabled(int postID)
        {
            using (var db = DbBase.GetDb())
                return (bool)db.ExecuteScalar("SELECT " + DAL.Post.COMMENTENABLED + " FROM " + DAL.Post.SQL_TABLE + " WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID, db.CreateParameter(DAL.Post.POSTID, postID));
        }

        /// <summary>
        /// 取得上一篇文章。
        /// </summary>
        /// <param name="postID">当前文章编号。</param>
        /// <param name="categoryID">文章所属栏目编号。</param>
        /// <returns>返回一个文章实例，如果不没有则返回 null。</returns>
        public Model.Post GetPrevItem(int postID, int? categoryID)
        {
            using (var db = DbBase.GetDb())
            {
                using (var reader = db.ExecuteReader(DAL.Post.SQL_SELECT + " WHERE " + DAL.Post.POSTID + " < @" + DAL.Post.POSTID + " AND " + DAL.Post.CATEGORYID + " = @" + DAL.Post.CATEGORYID + " AND " + DAL.Post.ENABLED + " = 1 ORDER BY " + DAL.Post.POSTID + " DESC", db.CreateParameter(DAL.Post.POSTID, postID), db.CreateParameter(DAL.Post.CATEGORYID, categoryID)))
                {
                    if (!reader.Read()) return null;
                    var result = new Model.Post();
                    DAL.Post.FillItem(reader, result);
                    return result;
                }
            }
        }

        /// <summary>
        /// 取得下一篇文章。
        /// </summary>
        /// <param name="postID">当前文章编号。</param>
        /// <param name="categoryID">文章所属栏目编号。</param>
        /// <returns>返回一个文章实例，如果不没有则返回 null。</returns>
        public Model.Post GetNextItem(int postID, int? categoryID)
        {
            using (var db = DbBase.GetDb())
            {
                using (var reader = db.ExecuteReader(DAL.Post.SQL_SELECT + " WHERE " + DAL.Post.POSTID + " > @" + DAL.Post.POSTID + " AND " + DAL.Post.CATEGORYID + " = @" + DAL.Post.CATEGORYID + " AND " + DAL.Post.ENABLED + " = 1 ORDER BY " + DAL.Post.POSTID + " ASC", db.CreateParameter(DAL.Post.POSTID, postID), db.CreateParameter(DAL.Post.CATEGORYID, categoryID)))
                {
                    if (!reader.Read()) return null;
                    var result = new Model.Post();
                    DAL.Post.FillItem(reader, result);
                    return result;
                }
            }
        }

        /// <summary>
        /// 切换文章发布状态。
        /// </summary>
        /// <param name="commentID">文章编号。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int EnabledToggle(int postID)
        {
            using (var db = DbBase.GetDb())
                return db.ExecuteNonQuery("UPDATE " + DAL.Post.SQL_TABLE + " SET " + DAL.Post.ENABLED + " = ABS(" + DAL.Post.ENABLED + " - 1) WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID, db.CreateParameter(DAL.Post.POSTID, postID));
        }

        /// <summary>
        /// 增加文章查看次数。
        /// </summary>
        /// <param name="jobID">文章编号。</param>
        /// <param name="request">客户端 Web 请求。</param>
        /// <param name="response">客户端 HTTP 响应的信息。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int IncViewCount(int postID, HttpRequest request, HttpResponse response)
        {
            var setting = new BLL.Setting();
            var settingItem = setting.Get();
            var name = "ynhtm.Post." + postID;
            var key = "View";
            var cookie = request.Cookies[name] ?? new HttpCookie(name) { Expires = DateTime.Parse(DateTime.Now.ToString("yyy-MM-dd 23:59:59")) };
            if (settingItem.TotalType == 2 && !cookie[key].IsNullOrEmpty()) return 0;
            cookie[key] = "1";
            response.AppendCookie(cookie);
            using (var db = DbBase.GetDb())
                return db.ExecuteNonQuery("UPDATE " + DAL.Post.SQL_TABLE + " SET " + DAL.Post.VIEWCOUNT + " = " + DAL.Post.VIEWCOUNT + " + 1 WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID, db.CreateParameter(DAL.Post.POSTID, postID));
        }

        /// <summary>
        /// 取得文章的查看次数。
        /// </summary>
        /// <param name="jobID">文章编号。</param>
        /// <returns>返回文章的查看次数。</returns>
        public int GetViewCount(int postID)
        {
            using (var db = DbBase.GetDb())
                return Convert.ToInt32(db.ExecuteScalar("SELECT " + DAL.Post.VIEWCOUNT + " FROM " + DAL.Post.SQL_TABLE + " WHERE " + DAL.Post.POSTID + " = @" + DAL.Post.POSTID, db.CreateParameter(DAL.Post.POSTID, postID)));
        }

        /// <summary>
        /// 取得 CSS 文字颜色和样式。
        /// </summary>
        /// <param name="color">文字颜色。</param>
        /// <param name="style">文字 FontStyle 样式。</param>
        /// <returns>返回 CSS 格式。</returns>
        public string GetCssStyle(Color color, FontStyle style)
        {
            string result = null;
            if (color != Color.Empty) result = "color:" + ColorTranslator.ToHtml(color) + ";";
            if (style != FontStyle.Regular)
            {
                if ((style & FontStyle.Bold) == FontStyle.Bold) result += "font-weight:bold;";
                if ((style & FontStyle.Italic) == FontStyle.Italic) result += "font-style:italic;";
                string decoration = null;
                if ((style & FontStyle.Strikeout) == FontStyle.Strikeout) decoration = " line-through";
                if ((style & FontStyle.Underline) == FontStyle.Underline) decoration += " underline";
                if (decoration != null) result += "text-decoration:" + decoration.Substring(1) + ";";
            }
            return result;
        }

        /// <summary>
        /// 取得 CSS 文字颜色和样式。
        /// </summary>
        /// <param name="color">文字颜色。</param>
        /// <param name="style">文字样式。</param>
        /// <returns>返回 CSS 格式样式。</returns>
        public string GetCssStyle(string color, int style)
        {
            if (color.IsNullOrWhiteSpace()) return this.GetCssStyle(Color.Empty, (FontStyle)style);
            return this.GetCssStyle(ColorTranslator.FromHtml(color), (FontStyle)style);
        }

        /// <summary>
        /// 取得文章 CSS 样式化后的标题。
        /// </summary>
        /// <param name="item">文章实例。</param>
        /// <returns>返回标题的 HTML 格式。</returns>
        public string GetStyleTitle(Model.Post item)
        {
            var css = this.GetCssStyle(item.TitleColor, item.TitleStyle);
            if (css.IsNullOrWhiteSpace()) return item.Title.HtmlEncode();
            return "<span style=\"" + css + "\">" + item.Title.HtmlEncode() + "</span>";
        }

        /// <summary>
        /// 统计文章数据。
        /// </summary>
        /// <returns>返回受到影响的行数。</returns>
        public int Sumup()
        {
            using (var db = DbBase.GetDb())
                return db.ExecuteNonQuery("UPDATE " + DAL.Post.SQL_TABLE + " SET " + DAL.Post.COMMENTCOUNT + " = (SELECT COUNT(0) FROM " + DAL.Comment.SQL_TABLE + " WHERE " + DAL.Comment.POSTID + " = " + DAL.Post.SQL_TABLE + "." + DAL.Post.POSTID + ")");
        }
    }
}
