using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using isRoc.Core;
using isRoc.Core.UI;
using isRoc.Data;
using isRoc.Data.Entity;

namespace isRoc.Logic.Admin
{
    /// <summary>
    /// 文章管理类
    /// </summary>
    public class AdminPost
    {
        private SiteFun _fun = new SiteFun();
        private SiteDat _siteDat = new SiteDat();
        private AdminUI _admUi = new AdminUI();
        private HtmlUI _htmlUi = new HtmlUI();
        private _AdminCookie _ac = new _AdminCookie();

        /// <summary>
        /// 清除缓存
        /// </summary>
        private void ClearCache()
        {
            /*SiteCache cache = new SiteCache();
            _siteDat.RemoveDat(cache.FineArticle);
            _siteDat.RemoveDat(cache.HotArticle);
            _siteDat.RemoveDat(cache.RandomArticle);*/
            _siteDat.ClearDat();
        }

        /// <summary>
        /// 提交文章窗体
        /// </summary>
        /// <param name="mode">模式：A-文章，P-单页</param>
        /// <returns>返回发布文章控件代码</returns>
        public string Post(string mode)
        {
            StringBuilder sr = new StringBuilder();
            if (mode == "A" || mode == "P")
            {
                bool isArticle = mode == "A";
                SettingItem setting = new SettingData().GetSetting();
                string theme = new SettingData().GetTheme;
                string tmpFilePath = Path.Combine(SiteCfg.Router, "Common/Temp/post_cache.tmp");
                int id = _fun.ToInt(_fun.Query("id"));
                PostData artData = new PostData();
                ColumnData cData = new ColumnData();
                TagData tagData = new TagData();
                //取得默认值
                string[] myUserInfo = _ac.Get();
                UserItem myUser = new UserData().CheckUser(myUserInfo[0], _fun.Encryption(myUserInfo[1]), true);
                PostItem old = artData.GetPost(id);
                ColumnItem oldColumn = new ColumnData().GetColumn(old.ColumnID);
                if (old.ID == 0)
                {
                    //默认显示、可评论并自动审核，可发通告
                    old.Show = true;
                    old.SwitchComment = true;
                    old.AutoVerifyComment = true;
                    old.SwitchTrackback = true;
                }
                if (string.IsNullOrEmpty(old.Author)) { old.Author = myUser.Name; }
                if (_fun.IsPost)
                {
                    //处理文章数据
                    PostItem postVal = new PostItem();
                    string content = _fun.HtmlMatch(_fun.Post("content"));
                    string explain = content;
                    if (!string.IsNullOrEmpty(explain))
                    {
                        explain = Regex.Replace(explain, SiteCfg.PageBreakRegular, SiteCfg.PageBreakSymbol, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                        if (explain.IndexOf(SiteCfg.PageBreakSymbol) > 0)
                        {
                            explain = explain.Substring(0, explain.IndexOf(SiteCfg.PageBreakSymbol));
                            explain = _fun.HtmlMatch(explain);
                        }
                        explain = explain.Replace(SiteCfg.PageBreakSymbol, string.Empty);
                    }
                    postVal.ID = id;
                    postVal.ColumnID = _fun.ToInt(_fun.Post("cid"));
                    postVal.Title = _fun.Post("title");
                    postVal.Tags = _fun.Post("tags");
                    postVal.Local = _fun.Post("local");
                    postVal.Explain = explain;
                    postVal.Content = content;
                    postVal.Author = _fun.Post("author");
                    postVal.Publish = _fun.ToDate(_fun.Post("publish"));
                    postVal.Password = _fun.Post("pwd");
                    postVal.Vote = _fun.ToInt(_fun.Post("vote"));
                    postVal.Reader = _fun.ToInt(_fun.Post("reader"));
                    postVal.Fine = _fun.ToInt(_fun.Post("fine")) == 0 ? false : true;
                    postVal.Show = _fun.ToInt(_fun.Post("show")) == 0 ? false : true;
                    postVal.PostCount = old.PostCount;
                    postVal.SwitchComment = _fun.ToInt(_fun.Post("switchCmt")) == 0 ? false : true;
                    postVal.SwitchTrackback = _fun.ToInt(_fun.Post("switchTb")) == 0 ? false : true;
                    postVal.AutoVerifyComment = _fun.ToInt(_fun.Post("avcmt")) == 0 ? false : true;
                    postVal.AutoVerifyTrackback = _fun.ToInt(_fun.Post("avtb")) == 0 ? false : true;
                    postVal.Attachments = old.Attachments;
                    //分类
                    ColumnItem postColumn = new ColumnData().GetColumn(postVal.ColumnID);
                    if (string.IsNullOrEmpty(postVal.Title)) { sr.Append(_admUi.ErrorBox(_siteDat.GetLan("MsgNoTitle"))); }
                    else
                    {
                        if (!string.IsNullOrEmpty(postVal.Local)) { postVal.Local = postVal.Local.Replace(" ", "-"); }
                        if (!string.IsNullOrEmpty(postVal.Local) && (!_fun.IsLocal(postVal.Local) || artData.ExistsLocal(postVal.Local, postVal.ID))) { sr.Append(_admUi.ErrorBox(_siteDat.GetLan("MsgNoLocalOrExists"))); }
                        else
                        {
                            //处理上传图片的内容循环替换
                            if (!string.IsNullOrEmpty(postVal.Content))
                            {
                                string[] tmpFilesHandle = { postVal.Content, postVal.Explain };
                                string atts = new _AdminUpload().SaveAs(HttpContext.Current.Request.Files, ref tmpFilesHandle[0], ref tmpFilesHandle[1], _fun.ToInt(_fun.Post("ws")), Path.Combine(SiteCfg.Router, setting.Parameter.WatermarkPath));
                                postVal.Content = tmpFilesHandle[0];
                                postVal.Explain = tmpFilesHandle[1];
                                if (!string.IsNullOrEmpty(atts))
                                {
                                    if (string.IsNullOrEmpty(postVal.Attachments)) { postVal.Attachments = atts; }
                                    else { postVal.Attachments += "," + atts; }
                                }
                            }
                            //保存或新增文章数据处理
                            if (postVal.ID == 0)
                            {
                                artData.InsertPost(postVal, mode);
                                //标签处理
                                tagData.InsertTagList(postVal.Tags);
                                //分类统计
                                //cData.CountCategoryPost(postVal.Category.ID);
                                sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgArtInsertSucc"), "?act=post&mode=list&M=" + mode));
                            }
                            else
                            {
                                artData.UpdatePost(postVal);
                                //标签处理
                                tagData.InsertTagList(postVal.Tags);
                                //类统计
                                cData.CountColumnPost(oldColumn.ID);
                                cData.CountColumnPost(postColumn.ID);
                                //更新修改后的显示
                                sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgArtUpdateSucc"), "?act=post&mode=list&M=" + mode));
                            }
                            try { File.Delete(tmpFilePath); }
                            catch { }
                        }
                    }
                    //处理引用通告
                    TrackbackLogData tbld = new TrackbackLogData();
                    SettingBasicItem sbi = setting.Basic;
                    string tbUrls = _fun.Post("tbUrls");
                    if (!string.IsNullOrEmpty(tbUrls))
                    {
                        foreach (string vItem in tbUrls.Split('\n'))
                        {
                            if (!string.IsNullOrEmpty(vItem))
                            {
                                string[] tbState = new SiteTrackback().SendTrackback(vItem, string.Format(SitePath.ArticleLinkFormat, sbi.URL + SiteCfg.Path, postVal.Local), sbi.Name, postVal.Title, _fun.ClearHtml(postVal.Explain)).Split('|');
                                TrackbackLogItem tbVal = new TrackbackLogItem();
                                tbVal.Error = _fun.ToInt(tbState[0]) == 0 ? false : true;
                                tbVal.Message = tbState[1];
                                tbVal.URL = vItem;
                                tbld.InsertTrackbackLog(tbVal);
                            }
                        }
                    }
                    ClearCache();
                    old = postVal;
                }
                //设置分类数据
                DataList<ColumnItem> cateList = cData.SelectColumn(-1, 0, true);
                ArrayList values = new ArrayList();
                ArrayList captions = new ArrayList();
                for (int i = 0; i < cateList.Count; i++)
                {
                    values.Add(cateList[i].ID);
                    captions.Add(cateList[i].Name);
                }
                sr.Append(_admUi.AdminBoxStart(true));
                sr.Append(_htmlUi.FormStart(null, true));

                sr.Append(_htmlUi.TableStart("onCenter advancedBox"));
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Title")) + _htmlUi.CreateTd(_htmlUi.Input("title", 50, null, _fun.HtmlEncode(old.Title)) + (isArticle ? _htmlUi.CreateSelect("cid", values, captions, oldColumn.ID) : string.Empty)));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                if (Regex.IsMatch(old.Local, @"^\d+$")) { old.Local = string.Empty; }
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Local")) + _htmlUi.CreateTd(string.Format((isArticle ? SitePath.ArticleLinkFormat : SitePath.PageLinkFormat), null, _htmlUi.Input("local", 30, null, _fun.HtmlEncode(old.Local)))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Content")) + _htmlUi.CreateTd(_admUi.Editor("content", _fun.HtmlEncode(old.Content))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh() + _htmlUi.CreateTd((File.Exists(tmpFilePath) ? "<a id=\"reInsertContent\">" + _siteDat.GetLan("MsgClickArtReload") + "</a>" : string.Empty) + string.Format(_siteDat.GetLan("MsgArtAutoSaveState"), "<span id=\"autoSaveCountdown\">--</span>", "<a id=\"autoSaveButton\">--</a>", "<span id=\"autoSaveIs\"></span>")));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Attach") + ", <a id=\"addFilesA\">" + _siteDat.GetLan("Add") + "</a>") + _htmlUi.CreateTd(string.Format("<span id=\"filesMainBox\">{0}</span><a id=\"filesMainInsertA\">{1}</a><div id=\"filesAttBox\"></div>", _htmlUi.FileInput(null, "files"), _siteDat.GetLan("Insert"))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TableFinal());

                sr.Append(_htmlUi.TableStart("onCenter hidden advancedBox"));
                string attsHtml = string.Empty;
                DataList<AttachmentItem> attachments = new AttachmentData().SelectAttachment(old.Attachments);
                foreach (AttachmentItem att in attachments)
                {
                    attsHtml += _htmlUi.Link(att.Name, att.Path, att.Type, true) + string.Format(", {0}, {1}, {2}<br/>", att.Publish, att.Size, att.Type);
                }
                if (attachments.Count > 0)
                {
                    sr.Append(_htmlUi.TrStart());
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Attach")) + _htmlUi.CreateTd(attsHtml));
                    sr.Append(_htmlUi.TrFinal());
                }
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Tag")) + _htmlUi.CreateTd(_htmlUi.Input("tags", "tags", 50, null, _fun.HtmlEncode(old.Tags))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh() + _htmlUi.CreateTd(_htmlUi.Button("getInputTags", _siteDat.GetLan("BtnTagsNow")) + "<div id=\"getInputTagsDsp\"></div>"));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Author")) + _htmlUi.CreateTd(_htmlUi.Input("author", 10, null, _fun.HtmlEncode(old.Author))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Time")) + _htmlUi.CreateTd(_htmlUi.Input("timeInput", "publish", 20, null, old.Publish) + _htmlUi.Button("updateTime", _siteDat.GetLan("BtnUpdateTime"))));
                sr.Append(_htmlUi.TrFinal());
                if (isArticle)
                {
                    sr.Append(_htmlUi.TrStart());
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Pwd")) + _htmlUi.CreateTd(_htmlUi.Input("pwd", 30, null, old.Password)));
                    sr.Append(_htmlUi.TrFinal());
                }
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("VoteNum")) + _htmlUi.CreateTd(_htmlUi.Input("vote", 5, null, old.Vote)));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Reader")) + _htmlUi.CreateTd(_htmlUi.Input("reader", 5, null, old.Reader)));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Virtue")) + _htmlUi.CreateTd((isArticle ? _htmlUi.CheckBoxInput(_siteDat.GetLan("Top"), "fine", 1, old.Fine) : string.Empty) + _htmlUi.CheckBoxInput(_siteDat.GetLan("Show"), "show", 1, old.Show)));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                ArrayList wmValues = new ArrayList();
                ArrayList caps = new ArrayList();
                for (int wmI = 0; wmI <= 9; wmI++) { wmValues.Add(wmI); }
                caps.Add("--" + _siteDat.GetLan("WmPosition") + "--");
                caps.Add(_siteDat.GetLan("PTopLeft"));
                caps.Add(_siteDat.GetLan("PTopCen"));
                caps.Add(_siteDat.GetLan("PTopRight"));
                caps.Add(_siteDat.GetLan("PMdlLeft"));
                caps.Add(_siteDat.GetLan("PMdlCen"));
                caps.Add(_siteDat.GetLan("PMdlRight"));
                caps.Add(_siteDat.GetLan("PBtmLeft"));
                caps.Add(_siteDat.GetLan("PBtmCen"));
                caps.Add(_siteDat.GetLan("PBtmRight"));
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Switch")) + _htmlUi.CreateTd(_htmlUi.CheckBoxInput(_siteDat.GetLan("InsertCmt"), "switchCmt", 1, old.SwitchComment) + _htmlUi.CheckBoxInput(_siteDat.GetLan("InsertTb"), "switchTb", 1, old.SwitchTrackback) + _htmlUi.CreateSelect("ws", wmValues, caps, setting.Parameter.WatermarkSeat)));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("AutoVerify")) + _htmlUi.CreateTd(_htmlUi.CheckBoxInput(_siteDat.GetLan("VerifyCmt"), "avcmt", 1, old.AutoVerifyComment) + _htmlUi.CheckBoxInput(_siteDat.GetLan("VerifyTb"), "avtb", 1, old.AutoVerifyTrackback)));
                sr.Append(_htmlUi.TrFinal());
                if (isArticle)
                {
                    sr.Append(_htmlUi.TrStart());
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Trackback")) + _htmlUi.CreateTd(_htmlUi.Textarea("tbUrls", 5, 80, null)));
                    sr.Append(_htmlUi.TrFinal());
                }
                sr.Append(_htmlUi.TableFinal());

                sr.Append(_htmlUi.TableStart("onCenter"));
                sr.Append(_htmlUi.TrStart());
                sr.Append(_htmlUi.CreateTh() + _htmlUi.CreateTd(_htmlUi.SubmitButton() + _htmlUi.ResetButton() + _htmlUi.Button("advancedLink", _siteDat.GetLan("BtnAdvanced"))));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.TableFinal());

                sr.Append(_htmlUi.FormFinal());
                sr.Append(_admUi.AdminBoxFinal());
            }
            return sr.ToString();
        }

        /// <summary>
        /// 取得文章列表窗体
        /// </summary>
        /// <param name="mode">模式：A-文章，P-单页</param>
        /// <returns>返回文章列表代码</returns>
        public string List(string mode)
        {
            StringBuilder sr = new StringBuilder();
            int cid = _fun.ToInt(_fun.Query("cid"));
            string key = _fun.Query("key");
            //下面三行是分页设置
            int page = _fun.ToInt(_fun.Query("page"));
            if (page < 1) { page = 1; }
            int pageSize = 20;
            PostData pData = new PostData();
            DataList<PostItem> list = pData.SelectPost(cid, null, key, page, pageSize, 0, mode, true);
            if (list.Count > 0)
            {
                if (mode == "A" || mode == "P")
                {
                    bool isArticle = mode == "A";
                    if (_fun.IsPost)
                    {
                        int id = _fun.ToInt(_fun.Post("id"));
                        bool del = _fun.ToInt(_fun.Post("del")) == 0 ? false : true;
                        if (del)
                        {
                            PostItem tmpPost = pData.GetPost(id);
                            //删除附件
                            if (!string.IsNullOrEmpty(tmpPost.Attachments))
                            {
                                AttachmentData attData = new AttachmentData();
                                foreach (AttachmentItem delAtt in attData.SelectAttachment(tmpPost.Attachments))
                                {
                                    File.Delete(Path.Combine(SiteCfg.Router, delAtt.Path));
                                }
                                attData.DeleteAttachment(tmpPost.Attachments);
                            }
                            pData.DeletePost(id);
                            sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgArtDelSucc")));
                        }
                        else
                        {
                            bool fine = _fun.ToInt(_fun.Post("fine")) == 0 ? false : true;
                            bool show = _fun.ToInt(_fun.Post("show")) == 0 ? false : true;
                            pData.UpdatePostFineAndShow(id, fine, show);
                            sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgUpdateDat")));
                        }
                        ClearCache();
                    }
                    if (isArticle)
                    {
                        //设置分类数据
                        DataList<ColumnItem> cateList = new ColumnData().SelectColumn(-1, 0, false);
                        ArrayList values = new ArrayList();
                        ArrayList captions = new ArrayList();
                        values.Add(0);
                        captions.Add("--" + _siteDat.GetLan("Category") + "--");
                        for (int j = 0; j < cateList.Count; j++)
                        {
                            values.Add(cateList[j].ID);
                            captions.Add(cateList[j].Name);
                        }
                        //搜索
                        sr.Append(_admUi.AdminBoxStart(true));
                        sr.Append(_htmlUi.FormStart(false, null, false));
                        sr.Append(_htmlUi.TableStart("onCenter"));
                        sr.Append(_htmlUi.TrStart());
                        sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Search") + _htmlUi.HiddenInput("act", "post") + _htmlUi.HiddenInput("mode", "list") + _htmlUi.HiddenInput("m", mode)));
                        sr.Append(_htmlUi.CreateTd(_htmlUi.CreateSelect("cid", values, captions, cid) + _htmlUi.Input("key", 30, null, _fun.HtmlEncode(key)) + _htmlUi.SubmitButton(_siteDat.GetLan("Search"))));
                        sr.Append(_htmlUi.TrFinal());
                        sr.Append(_htmlUi.TableFinal());
                        sr.Append(_htmlUi.FormFinal());
                        sr.Append(_admUi.AdminBoxFinal());
                    }

                    //正常列表
                    sr.Append(_admUi.AdminBoxStart(true));
                    sr.Append(_htmlUi.TableStart());
                    sr.Append(_htmlUi.TrStart());
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Title")));
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Local")));
                    if (isArticle)
                    {
                        sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Category")));
                        sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Top")));
                    }
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Show")));
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Delete")));
                    sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Operate")));
                    sr.Append(_htmlUi.TrFinal());
                    int i = 1;
                    foreach (PostItem vItem in list)
                    {
                        i++;
                        sr.Append(_htmlUi.FormStart());
                        sr.Append(_htmlUi.TrStart(i % 2 == 0 ? " cRow" : null));
                        sr.Append(_htmlUi.CreateTd(_htmlUi.Link(_fun.HtmlEncode(_fun.StrCut(vItem.Title, 50)), string.Format("?act=post&amp;mode=post&amp;m={1}&amp;id={0}", vItem.ID, mode))));
                        sr.Append(_htmlUi.CreateTd(_fun.HtmlEncode(_fun.StrCut(vItem.Local, 30))));
                        if (isArticle)
                        {
                            sr.Append(_htmlUi.CreateTd(_fun.HtmlEncode(new ColumnData().GetColumn(vItem.ColumnID).Name)));
                            sr.Append(_htmlUi.CreateTd(_htmlUi.CheckBoxInput("fine", 1, vItem.Fine)));
                        }
                        sr.Append(_htmlUi.CreateTd(_htmlUi.CheckBoxInput("show", 1, vItem.Show)));
                        sr.Append(_htmlUi.CreateTd(_htmlUi.CheckBoxInput("del", 1, false)));
                        sr.Append(_htmlUi.CreateTd(_htmlUi.HiddenInput("id", vItem.ID) + _htmlUi.SubmitButton(_siteDat.GetLan("BtnSave"))));
                        sr.Append(_htmlUi.TrFinal());
                        sr.Append(_htmlUi.FormFinal());
                    }
                    sr.Append(_htmlUi.TrStart());
                    sr.Append(_htmlUi.CreateTd(new SitePages().Make(list.Number, page, pageSize, "?act=post&amp;mode=list&amp;cid=" + cid + "&amp;key=" + _fun.UrlEncode(key) + "&amp;m=" + mode + "&amp;page={0}"), (isArticle ? 7 : 5), null));
                    sr.Append(_htmlUi.TrFinal());
                    sr.Append(_htmlUi.TableFinal());
                    sr.Append(_admUi.AdminBoxFinal());
                }
            }
            else { sr.Append(Post(mode)); }
            return sr.ToString();
        }
    }
}
