using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Article_Article : System.Web.UI.Page
{
    SnSee.Bean.AdminBaseBean _AdminBeanLogin = null;
    protected Guid? ArticleBaseID;
    protected Guid? EditionID;

    protected void Page_Load(object sender, EventArgs e)
    {
        SnSee.Module.Admin.Admin.AdminIsLogin(out _AdminBeanLogin, true);

        if (!SnSee.Module.Admin.Admin.ModuleIsOpen(SnSee.Config.SystemModule.Article))
        {
            Response.Redirect("../ErrorTip.aspx?EMsg=该模块尚未开启，如需使用，请联系系统管理员！");
        }

        SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0604", true);
        ArticleBaseID = SnSee.Tool.ConvertTool.GetGuid(Request["ID"]);
        EditionID = SnSee.Tool.ConvertTool.GetGuid(Request["EditionID"]);

        if (!EditionID.HasValue)
        {
            EditionID = SnSee.Module.Systems.Edition.GetFirstEditionID();
        }

        EditionItem1.EditionID = EditionID;
        EditionItem1.ObjectID = ArticleBaseID;
        EditionItem1.NavName = "Article";

        if (!IsPostBack)
        {
            GetArticleModuleConfig();
            if (EditionID.HasValue)
            {
                dropClass_DataBind(EditionID.Value);
            }

            if (SnSee.Module.Admin.Admin.ModuleIsOpen(SnSee.Config.SystemModule.User))
            {//如果开启用户模块
                boxUserLevelIDList.Visible = true;
                cblUserLevelIDList_DataBind();
            }

            if (ArticleBaseID.HasValue)
            {
                boxDel.Visible = true;
                litTitle.Text = "编辑资讯";
                EditionItem1.IsViewCellEditionID = true;
                LoadArticleBase(ArticleBaseID.Value);
            }
        }
        boxPageExplain.Visible = SnSee.Config.WebConfig.ViewAdminPageExplain;
    }

    /// <summary>
    /// 取得资讯模块配置
    /// </summary>
    private void GetArticleModuleConfig()
    {
        boxTitleImage.Visible = SnSee.Config.ArticleConfig.TitleImageOpen;
        chkIsTitleImageMake.Visible = SnSee.Config.ArticleConfig.TitleImageMake;
        chkIsTitleImageMake.Checked = SnSee.Config.ArticleConfig.TitleImageMake;
        litTitleImageSize.Visible = SnSee.Config.ArticleConfig.TitleImageMake;
        litTitleImageSize.Text = "(" + SnSee.Config.ArticleConfig.TitleImageWidth + "×" + SnSee.Config.ArticleConfig.TitleImageHeight + ")";
    }

    /// <summary>
    /// 载入当前语言版本分类数据
    /// </summary>
    private void dropClass_DataBind(Guid EditionID)
    {
        dropClass.DataSource = SnSee.Module.Article.ArticleClassTree.GetClassTreeList(null, "State=1 And EditionID='{" + EditionID + "}'", "Order by SortOrder Asc, CreateTime Asc");
        dropClass.DataBind();

        dropClass.Items.Insert(0, new ListItem("根级", ""));
    }

    /// <summary>
    /// 取得用户等级
    /// </summary>
    private void cblUserLevelIDList_DataBind()
    {
        cblUserLevelIDList.DataSource = SnSee.Factory.Factory.UserLevel.SelectList(0, "State=1", "Order By SortOrder Asc");
        cblUserLevelIDList.DataBind();
    }

    /// <summary>
    /// 载入内容
    /// </summary>
    /// <param name="EditionID">版本ID</param>
    /// <param name="ArticleID">资讯ID</param>
    private void LoadArticleBase(Guid ArticleBaseID)
    {
        SnSee.Bean.ArticleBaseBean _ArticleBaseBean = (SnSee.Bean.ArticleBaseBean)SnSee.Factory.Factory.ArticleBase.Select(ArticleBaseID);
        if (_ArticleBaseBean != null)
        {
            dropClass.SelectedValue = _ArticleBaseBean.ArticleClassID.Value.ToString();
            txtTitle.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ArticleBaseBean.Title);
            txtSummary.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ArticleBaseBean.Summary);
            txtBody.Value = _ArticleBaseBean.Body;
            txtSortOrder.Text = _ArticleBaseBean.SortOrder.HasValue ? _ArticleBaseBean.SortOrder.Value.ToString() : "";
            dropState.SelectedValue = _ArticleBaseBean.State.HasValue ? _ArticleBaseBean.State.Value.ToString() : "0";
            if (!string.IsNullOrEmpty(_ArticleBaseBean.TitleImageUrl))
            {
                imgTitleImage.Visible = true;
                imgTitleImage.ImageUrl = _ArticleBaseBean.TitleImageUrl;
            }

            if (!string.IsNullOrEmpty(_ArticleBaseBean.UserLevelIDList) && cblUserLevelIDList.Items.Count > 0)
            {
                string[] arrUserLevelIDList = _ArticleBaseBean.UserLevelIDList.Split(new char[] { ',' });
                if (arrUserLevelIDList != null && arrUserLevelIDList.Length > 0)
                {
                    for (int i = 0; i < arrUserLevelIDList.Length; i++)
                    {
                        for (int j = 0; j < cblUserLevelIDList.Items.Count; j++)
                        {
                            if (cblUserLevelIDList.Items[j].Value.ToLower() == arrUserLevelIDList[i].ToLower().Replace("{", "").Replace("}", ""))
                            {
                                cblUserLevelIDList.Items[j].Selected = true;
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtnOk_Click(object sender, EventArgs e)
    {
        int? SortOrder = SnSee.Tool.ConvertTool.GetInt32(txtSortOrder.Text);
        if (!SortOrder.HasValue)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您输入的排序值不合格，只能输入整数！");
            return;
        }

        string Title = SnSee.Tool.EncodeTool.HtmlEncode(txtTitle.Text);
        Guid? ArticleClassID = SnSee.Tool.ConvertTool.GetGuid(dropClass.SelectedValue);
        string UserLevelIDList = "";
        if (cblUserLevelIDList.Items.Count > 0)
        {
            for (int i = 0; i < cblUserLevelIDList.Items.Count; i++)
            {
                if (cblUserLevelIDList.Items[i].Selected)
                {
                    UserLevelIDList += "{" + cblUserLevelIDList.Items[i].Value + "},";
                }
            }
            if (!string.IsNullOrEmpty(UserLevelIDList))
            {
                UserLevelIDList = UserLevelIDList.TrimEnd(new char[] { ',' });
            }
        }
        bool _Return = true;

        if (string.IsNullOrEmpty(Title) || !ArticleClassID.HasValue)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您还未选择所属分类或未填写标题！");
            return;
        }

        SnSee.Bean.ArticleBaseBean _ArticleBaseBean = new SnSee.Bean.ArticleBaseBean();
        _ArticleBaseBean.ArticleClassID = ArticleClassID;
        _ArticleBaseBean.Title = Title;
        _ArticleBaseBean.Summary = SnSee.Tool.EncodeTool.HtmlEncode(txtSummary.Text);
        _ArticleBaseBean.Body = txtBody.Value;
        _ArticleBaseBean.SortOrder = SortOrder;
        _ArticleBaseBean.State = SnSee.Tool.ConvertTool.GetInt32(dropState.SelectedValue);
        _ArticleBaseBean.UserLevelIDList = UserLevelIDList;

        #region 标题图片处理
        if (!ArticleBaseID.HasValue)
        {//不存在数据,进行增加
            if ((fileTitleImage.PostedFile == null || fileTitleImage.PostedFile.ContentLength <= 0) && SnSee.Config.ArticleConfig.TitleImageOpen && SnSee.Config.ArticleConfig.TitleImageMust)
            {
                SnSee.Tool.MessageTool.MessageBox(this.Page, "您还未选择标题图片！");
                return;
            }
        }

        bool IsTitleImage = true;
        bool IsUpTitleImage = false;
        if (fileTitleImage.PostedFile != null && fileTitleImage.PostedFile.ContentLength > 0 && SnSee.Config.ArticleConfig.TitleImageOpen)
        {
            SnSee.Bean.FileUploadBean _FileUploadBean = null;
            if (SnSee.Config.ArticleConfig.TitleImageOpen && chkIsTitleImageMake.Checked)
            {
                _FileUploadBean = new SnSee.Bean.FileUploadBean();
                _FileUploadBean.Width = SnSee.Config.ArticleConfig.TitleImageWidth;
                _FileUploadBean.Height = SnSee.Config.ArticleConfig.TitleImageHeight;
                _FileUploadBean.IsDispose = true;
            }

            string FilePath = SnSee.Config.WebConfig.UploadFilePath + "/" + SnSee.Module.File.FileInfo.GetFilePath();//文件目录路径
            string FileName = Guid.NewGuid().ToString();  //文件名
            string FileExName = System.IO.Path.GetExtension(fileTitleImage.PostedFile.FileName);

            IsTitleImage = SnSee.Module.File.FileInfo.Upload(_FileUploadBean, fileTitleImage.PostedFile.InputStream, FilePath, FileName, FileExName, true, fileTitleImage.PostedFile.ContentType);
            if (!IsTitleImage)
            {
                SnSee.Tool.MessageTool.MessageBox(this.Page, "标题图片上传失败。请检查后重试！");
                return;
            }
            _ArticleBaseBean.TitleImageUrl = FilePath + "/" + FileName + FileExName;
            _ArticleBaseBean.TitleImageUrl = _ArticleBaseBean.TitleImageUrl.Replace("//", "/");
            IsUpTitleImage = true;//已经成功上传标题图片
        }
        #endregion

        string ReturnText = "";
        if (!ArticleBaseID.HasValue)
        {//不存在数据,进行增加
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0601", true);
            if (!SnSee.Factory.Factory.ArticleBase.Insert(_ArticleBaseBean))
            {
                _Return = false;
            }
            ReturnText = "增加";
        }
        else
        {//已存在数据,进行更新
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0603", true);
            //如果有原标题图片，在重新指定上传标题图片时，删除原标题图片-取得原数据
            SnSee.Bean.ArticleBaseBean _ArticleBaseBeanTitleImg = null;
            if (IsUpTitleImage)
            {
                _ArticleBaseBeanTitleImg = (SnSee.Bean.ArticleBaseBean)SnSee.Factory.Factory.ArticleBase.Select(ArticleBaseID.Value);
            }

            if (!SnSee.Factory.Factory.ArticleBase.Update(_ArticleBaseBean, ArticleBaseID.Value))
            {
                _Return = false;
            }
            else
            {
                //如果有原标题图片，在重新指定上传标题图片时，删除原标题图片-执行图片删除
                if (IsUpTitleImage)
                {
                    if (_ArticleBaseBeanTitleImg != null && !string.IsNullOrEmpty(_ArticleBaseBeanTitleImg.TitleImageUrl))
                    {
                        SnSee.Module.File.FileInfo.DeleteFile(_ArticleBaseBeanTitleImg.TitleImageUrl);
                    }
                }
            }
            ReturnText = "编辑";
        }

        if (_Return)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，资讯" + ReturnText + "成功！", "ArticleList.aspx?EID=" + EditionID);
        }
        else
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "资讯" + ReturnText + "失败，请核查后重试！");
        }
    }

    /// <summary>
    /// 当前资讯放入回收站
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtnDel_Click(object sender, EventArgs e)
    {
        SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0602", true);
        if (ArticleBaseID.HasValue)
        {
            SnSee.Bean.ArticleBaseBean _ArticleBaseBean = new SnSee.Bean.ArticleBaseBean();
            _ArticleBaseBean.State = 0;
            if (SnSee.Factory.Factory.ArticleBase.Update(_ArticleBaseBean, ArticleBaseID.Value))
            {
                SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，操作成功！", "ArticleList.aspx?EditionID=" + EditionID);
            }
        }
        else
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "数据错误，无法进行删除！", Request.RawUrl);
        }
    }
}