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

using SnSee.Bean;
using SnSee.Factory;

public partial class Admin_Article_ArticleClassSet : System.Web.UI.Page
{
    AdminBaseBean _AdminBeanLogin = null;
    private Guid? EditionID;
    private Guid? ArticleClassID;
    private string ActionType;

    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, "A0605", true);

        ActionType = Request["AC"];
        EditionID = SnSee.Tool.ConvertTool.GetGuid(Request["EditionID"]);
        if (!EditionID.HasValue)
        {
            EditionID = SnSee.Module.Systems.Edition.GetFirstEditionID();
        }

        ArticleClassID = SnSee.Tool.ConvertTool.GetGuid(Request["ID"]);
        EditionItem1.NavName = "ArticleClassSet";
        EditionItem1.EditionID = EditionID;
        EditionItem1.ObjectID = ArticleClassID;

        if (!IsPostBack)
        {
            rptUserLevel_DataBind();
            if (EditionID.HasValue)
            {
                LoadEdition(EditionID.Value);
                dropClass_DataBind(EditionID.Value);
                if (EditionID.HasValue && ArticleClassID.HasValue && !string.IsNullOrEmpty(ActionType) && ActionType.ToLower() == "edit")
                {
                    GetArticleClassData(EditionID.Value, ArticleClassID.Value);
                }
            }
            rptList_DataBind();
        }
        boxPageExplain.Visible = SnSee.Config.WebConfig.ViewAdminPageExplain;
        boxUser1.Visible = SnSee.Config.ModuleConfig.SystemModuleUserOpen;
        boxUser2.Visible = SnSee.Config.ModuleConfig.SystemModuleUserOpen;
        boxUser3.Visible = SnSee.Config.ModuleConfig.SystemModuleUserOpen;
    }

    private void LoadEdition(Guid EditiionID)
    {
        EditionBean _EditionBean = (EditionBean)SnSee.Factory.Factory.Edition.Select(EditiionID);
        if (_EditionBean != null)
        {
            litTitle.Text = _EditionBean.EditionName;
            litTitle3.Text = _EditionBean.EditionName;
        }
    }

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

    /// <summary>
    /// 载入指定ID的版本的分类数据
    /// </summary>
    /// <param name="EditiionID">语言版本ID</param>
    /// <param name="ID">分类ID</param>
    private void GetArticleClassData(Guid EditionID, Guid ID)
    {
        lbtnAdd.Text = "确定编辑";
        ArticleClassBean _ArticleClassBean = (ArticleClassBean)SnSee.Factory.Factory.ArticleClass.Select("EditionID='{" + EditionID + "}' and ID='{" + ID + "}'");
        if (_ArticleClassBean != null)
        {
            if (_ArticleClassBean.ParentID.HasValue)
            {
                dropClass.SelectedValue = _ArticleClassBean.ParentID.Value.ToString();
            }
            txtClassName.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ArticleClassBean.ClassName);
            txtClassKey.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ArticleClassBean.ClassKey);
            dropState.SelectedValue = _ArticleClassBean.State.Value.ToString();
            txtSortOrder.Text = _ArticleClassBean.SortOrder.Value.ToString();
            if (_ArticleClassBean.IsChild.HasValue)
            {
                chkIsChild.Checked = _ArticleClassBean.IsChild.Value;
            }
            #region 用户查看等级
            if (!string.IsNullOrEmpty(_ArticleClassBean.UserLevelIDList))
            {
                CheckBox chkIsSelect;
                Literal litID;
                Guid? UserLevelID = null;

                foreach (RepeaterItem row in rptUserLevel.Items)
                {
                    chkIsSelect = (CheckBox)row.FindControl("chkIsSelect");
                    litID = (Literal)row.FindControl("litID");
                    UserLevelID = SnSee.Tool.ConvertTool.GetGuid(litID.Text);

                    if (UserLevelID.HasValue && _ArticleClassBean.UserLevelIDList.Contains(UserLevelID.Value.ToString()))
                    {
                        chkIsSelect.Checked = true;
                    }
                    else
                    {
                        chkIsSelect.Checked = false;
                    }
                }
            }
            #endregion
        }
    }

    /// <summary>
    /// 载入当前版本资讯分类列表
    /// </summary>
    private void rptList_DataBind()
    {
        rptList.DataSource = SnSee.Module.Article.ArticleClassTree.GetClassTreeList(null, "EditionID='{" + EditionID + "}'", "Order by SortOrder asc");
        rptList.DataBind();
    }

    /// <summary>
    /// 载入当前语言版本分类数据
    /// </summary>
    private void dropClass_DataBind(Guid EditionID)
    {
        DataTable dt = null;
        if (ArticleClassID.HasValue)
        {
            dt = SnSee.Module.Article.ArticleClassTree.GetClassTreeList(null, ArticleClassID.Value, "EditionID='{" + EditionID + "}'", "Order by SortOrder asc");
        }
        else
        {
            dt = SnSee.Module.Article.ArticleClassTree.GetClassTreeList(null, "EditionID='{" + EditionID + "}'", "Order by SortOrder asc");
        }

        dropClass.DataSource = dt;
        dropClass.DataBind();

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

    protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        Guid? AcArticleClassID = SnSee.Tool.ConvertTool.GetGuid(e.CommandArgument);
        if (!AcArticleClassID.HasValue)
        {
            return;
        }

        switch (e.CommandName)
        {
            case "Del_CommandName"://删除
                SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0602", true);
                List<object> _ArticleBaseBeanList = SnSee.Factory.Factory.ArticleBase.SelectList(0, "ArticleClassID='{" + AcArticleClassID.Value + "}'", "");
                if (_ArticleBaseBeanList != null && _ArticleBaseBeanList.Count > 0)
                {
                    SnSee.Tool.MessageTool.MessageBox(this.Page, "当前资讯分类存在相关资讯，不能进行删除，请将当前分类中的相关资讯清除掉后再执行此操作！", Request.Url.ToString());
                }


                if (SnSee.Factory.Factory.ArticleClass.Delete(AcArticleClassID.Value))
                {
                    SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，操作成功！", Request.Url.ToString());
                }
                else
                {
                    SnSee.Tool.MessageTool.MessageBox(this.Page, "操作失败，请重试！", Request.Url.ToString());
                }
                break;
        }
    }

    protected void rptList_ItemDataBound(object source, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Literal litClass = (Literal)e.Item.FindControl("litClass");
            Literal litUserLevelList = (Literal)e.Item.FindControl("litUserLevelList");
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (drv != null)
            {
                if (drv["ParentID"] != null && !string.IsNullOrEmpty(drv["ParentID"].ToString()))
                {
                    ArticleClassBean _ArticleClassBeanLoad = (ArticleClassBean)SnSee.Factory.Factory.ArticleClass.Select(new Guid(drv["ParentID"].ToString()));
                    if (_ArticleClassBeanLoad != null && litClass != null)
                    {
                        litClass.Text = _ArticleClassBeanLoad.ClassName;
                    }
                }
                if (drv["UserLevelIDList"] != null && !string.IsNullOrEmpty(drv["UserLevelIDList"].ToString()))
                {
                    string[] arrUserLevel = drv["UserLevelIDList"].ToString().Split(new char[] { ',' });
                    Guid? UserLevelID = null;
                    if (arrUserLevel != null && arrUserLevel.Length > 0)
                    {
                        for (int i = 0; i < arrUserLevel.Length; i++)
                        {
                            UserLevelID = SnSee.Tool.ConvertTool.GetGuid(arrUserLevel[i]);
                            if (UserLevelID.HasValue)
                            {
                                UserLevelBean _UserLevelBean = (UserLevelBean)SnSee.Factory.Factory.UserLevel.Select(UserLevelID.Value);
                                if (_UserLevelBean != null)
                                {
                                    litUserLevelList.Text += _UserLevelBean.LevelName + ",";
                                }
                            }
                        }
                        litUserLevelList.Text = litUserLevelList.Text.TrimEnd(new char[] { ',' });
                    }
                }
            }
        }
    }

    /// <summary>
    /// 确认添加
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtnAdd_Click(object sender, EventArgs e)
    {
        Guid? ParentID = SnSee.Tool.ConvertTool.GetGuid(dropClass.SelectedValue);
        string ClassName = SnSee.Tool.EncodeTool.HtmlEncode(txtClassName.Text);
        string ClassKey = SnSee.Tool.EncodeTool.HtmlEncode(txtClassKey.Text);
        int? State = SnSee.Tool.ConvertTool.GetInt32(dropState.SelectedValue);
        int? SortOrder = SnSee.Tool.ConvertTool.GetInt32(txtSortOrder.Text);
        bool? IsChild = chkIsChild.Enabled;
        bool? IsMenuView = chkIsMenuView.Checked;

        if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(ClassKey))
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您还未输入语言版本名称或版本标识！");
            return;
        }

        if (!State.HasValue)
        {
            State = 1;
        }
        if (!SortOrder.HasValue)
        {
            SortOrder = 0;
        }

        string Where = "ClassKey='" + ClassKey + "'";
        if (ArticleClassID.HasValue)
        {
            Where += " And ClassKey<>'" + ClassKey + "'";
        }
        ArticleClassBean _ArticleClassBeanCheck = (ArticleClassBean)SnSee.Factory.Factory.ArticleClass.Select(Where);
        if (_ArticleClassBeanCheck != null)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "已存在相同的版本标识，请更换另一个后重试操作！");
            return;
        }

        ArticleClassBean _ArticleClassBean = new ArticleClassBean();
        _ArticleClassBean.EditionID = EditionID;
        _ArticleClassBean.ClassName = ClassName;
        _ArticleClassBean.ClassKey = ClassKey;
        _ArticleClassBean.IsChild = IsChild;
        _ArticleClassBean.IsMenuView = IsMenuView;
        _ArticleClassBean.State = State;
        _ArticleClassBean.SortOrder = SortOrder;
        _ArticleClassBean.Depth = 1;
        #region 用户查看等级
        _ArticleClassBean.UserLevelIDList = "";
        CheckBox chkIsSelect;
        Literal litID;
        Guid? UserLevelID = null;

        foreach (RepeaterItem row in rptUserLevel.Items)
        {
            chkIsSelect = (CheckBox)row.FindControl("chkIsSelect");
            litID = (Literal)row.FindControl("litID");
            UserLevelID = SnSee.Tool.ConvertTool.GetGuid(litID.Text);

            if (chkIsSelect.Checked && UserLevelID.HasValue)
            {
                _ArticleClassBean.UserLevelIDList += "{" + UserLevelID.Value + "},";
            }
        }
        _ArticleClassBean.UserLevelIDList = _ArticleClassBean.UserLevelIDList.TrimEnd(new char[] { ',' });
        #endregion

        bool _Return = false;
        if (ArticleClassID.HasValue && !string.IsNullOrEmpty(ActionType) && ActionType.ToLower() == "edit")
        {//编辑
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0603", true);
            _Return = SnSee.Factory.Factory.ArticleClass.Update(_ArticleClassBean, ArticleClassID.Value);
            if (_Return)
            {
                _Return = SnSee.Module.Article.ArticleClass.SetArticleClassDepth(ArticleClassID.Value, ParentID); //更新分类路径
            }
        }
        else
        {//增加
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "A0601", true);
            //更新分类路径
            if (ParentID.HasValue)
            {
                ArticleClassBean _ArticleClassBeanParent = (ArticleClassBean)SnSee.Factory.Factory.ArticleClass.Select(ParentID.Value);
                if (_ArticleClassBeanParent != null)
                {
                    _ArticleClassBean.Depth = _ArticleClassBeanParent.Depth + 1;
                    if (string.IsNullOrEmpty(_ArticleClassBeanParent.DepthPath))
                    {
                        _ArticleClassBean.DepthPath = "{" + ParentID.Value.ToString() + "}";
                    }
                    else
                    {
                        _ArticleClassBean.DepthPath = _ArticleClassBeanParent.DepthPath + ",{" + ParentID.Value + "}";
                    }
                }
            }
            _Return = SnSee.Factory.Factory.ArticleClass.Insert(_ArticleClassBean);
        }

        if (_Return)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，操作成功！", Request.Url.ToString());
        }
        else
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "操作失败，请重试！", Request.Url.ToString());
        }
    }
}