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_Product_ProductClassSet : System.Web.UI.Page
{
    AdminBaseBean _AdminBeanLogin = null;
    private Guid? EditionID;
    private Guid? ProductClassID;
    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.Product))
        {
            Response.Redirect("../ErrorTip.aspx?EMsg=该模块尚未开启，如需使用，请联系系统管理员！");
        }
        SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0105", true);
        ActionType = Request["AC"];
        EditionID = SnSee.Tool.ConvertTool.GetGuid(Request["EditionID"]);
        if (!EditionID.HasValue)
        {
            EditionID = SnSee.Module.Systems.Edition.GetFirstEditionID();
        }

        ProductClassID = SnSee.Tool.ConvertTool.GetGuid(Request["ID"]);
        EditionItem1.NavName = "ProductClassSet";
        EditionItem1.EditionID = EditionID;
        EditionItem1.ObjectID = ProductClassID;
        EditionItem1.NavDir = "Product";

        if (!IsPostBack)
        {
            rptUserLevel_DataBind();
            if (EditionID.HasValue)
            {
                LoadEdition(EditionID.Value);
                dropClass_DataBind(EditionID.Value);
                if (EditionID.HasValue && ProductClassID.HasValue && !string.IsNullOrEmpty(ActionType) && ActionType.ToLower() == "edit")
                {
                    GetProductClassData(EditionID.Value, ProductClassID.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 GetProductClassData(Guid EditionID, Guid ID)
    {
        lbtnAdd.Text = "快速编辑";
        ProductClassBean _ProductClassBean = (ProductClassBean)SnSee.Factory.Factory.ProductClass.Select("EditionID='{" + EditionID + "}' and ID='{" + ID + "}'");
        if (_ProductClassBean != null)
        {
            if (_ProductClassBean.ParentID.HasValue)
            {
                dropClass.SelectedValue = _ProductClassBean.ParentID.Value.ToString();
            }
            txtClassName.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ProductClassBean.ClassName);
            txtClassKey.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ProductClassBean.ClassKey);
            if (_ProductClassBean.State.HasValue)
            {
                dropState.SelectedValue = _ProductClassBean.State.Value.ToString();
            }
            if (_ProductClassBean.SortOrder.HasValue)
            {
                txtSortOrder.Text = _ProductClassBean.SortOrder.Value.ToString();
            }
            if (_ProductClassBean.IsChild.HasValue)
            {
                chkIsChild.Checked = _ProductClassBean.IsChild.Value;
            }
            if (_ProductClassBean.IsDefault.HasValue)
            {
                chkIsDefault.Checked = _ProductClassBean.IsDefault.Value;
            }
            if (_ProductClassBean.IsMenuView.HasValue)
            {
                chkIsMenuView.Checked = _ProductClassBean.IsMenuView.Value;
            }
            #region 用户查看等级
            if (!string.IsNullOrEmpty(_ProductClassBean.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 && _ProductClassBean.UserLevelIDList.Contains(UserLevelID.Value.ToString()))
                    {
                        chkIsSelect.Checked = true;
                    }
                    else
                    {
                        chkIsSelect.Checked = false;
                    }
                }
            }
            #endregion
        }
    }

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

    /// <summary>
    /// 载入当前语言版本分类数据
    /// </summary>
    private void dropClass_DataBind(Guid EditionID)
    {
        DataTable dt = null;
        if (ProductClassID.HasValue)
        {
            dt = SnSee.Module.Product.ProductClassTree.GetClassTreeList(null, ProductClassID.Value, "EditionID='{" + EditionID + "}' And (IsChild=0 Or IsChild Is Null)", "Order by SortOrder asc");
        }
        else
        {
            dt = SnSee.Module.Product.ProductClassTree.GetClassTreeList(null, "EditionID='{" + EditionID + "}' And (IsChild=0 Or IsChild Is Null)", "Order by SortOrder asc");
        }

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

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

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

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

                if (SnSee.Factory.Factory.ProductClass.Delete(AcProductClassID.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");

            litUserLevelList.Text = "";
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (drv != null)
            {
                if (drv["ParentID"] != null && !string.IsNullOrEmpty(drv["ParentID"].ToString()))
                {
                    ProductClassBean _ProductClassBeanLoad = (ProductClassBean)SnSee.Factory.Factory.ProductClass.Select(new Guid(drv["ParentID"].ToString()));
                    if (_ProductClassBeanLoad != null && litClass != null)
                    {
                        litClass.Text = _ProductClassBeanLoad.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.Checked;
        bool? IsDefault = chkIsDefault.Checked;
        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 (ProductClassID.HasValue)
        {
            Where += " And ClassKey<>'" + ClassKey + "'";
        }
        ProductClassBean _ProductClassBeanCheck = (ProductClassBean)SnSee.Factory.Factory.ProductClass.Select(Where);
        if (_ProductClassBeanCheck != null)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "已存在相同的版本标识，请更换另一个后重试操作！");
            return;
        }

        ProductClassBean _ProductClassBean = new ProductClassBean();
        _ProductClassBean.EditionID = EditionID;
        _ProductClassBean.ClassName = ClassName;
        _ProductClassBean.ClassKey = ClassKey;
        _ProductClassBean.State = State;
        _ProductClassBean.IsChild = IsChild;
        _ProductClassBean.IsDefault = IsDefault;
        _ProductClassBean.IsMenuView = IsMenuView;
        _ProductClassBean.SortOrder = SortOrder;
        _ProductClassBean.Depth = 1;
        _ProductClassBean.ParentID = ParentID;

        #region 用户查看等级
        _ProductClassBean.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)
            {
                _ProductClassBean.UserLevelIDList += "{" + UserLevelID.Value + "},";
            }
        }
        _ProductClassBean.UserLevelIDList = _ProductClassBean.UserLevelIDList.TrimEnd(new char[] { ',' });
        #endregion

        bool _Return = false;
        if (ProductClassID.HasValue && !string.IsNullOrEmpty(ActionType) && ActionType.ToLower() == "edit")
        {//编辑
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0103", true);
            _Return = SnSee.Factory.Factory.ProductClass.Update(_ProductClassBean, ProductClassID.Value);
            if (_Return)
            {
                _Return = SnSee.Module.Product.ProductClass.SetProductClassDepth(ProductClassID.Value, ParentID); //更新分类路径
            }
        }
        else
        {//增加 
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0101", true);

            //更新分类路径
            if (ParentID.HasValue)
            {
                ProductClassBean _ProductClassBeanParent = (ProductClassBean)SnSee.Factory.Factory.ProductClass.Select(ParentID.Value);
                if (_ProductClassBeanParent != null)
                {
                    _ProductClassBean.Depth = _ProductClassBeanParent.Depth + 1;
                    if (string.IsNullOrEmpty(_ProductClassBeanParent.DepthPath))
                    {
                        _ProductClassBean.DepthPath = "{" + ParentID.Value.ToString() + "}";
                    }
                    else
                    {
                        _ProductClassBean.DepthPath = _ProductClassBeanParent.DepthPath + ",{" + ParentID.Value + "}";
                    }
                }
            }
            _Return = SnSee.Factory.Factory.ProductClass.Insert(_ProductClassBean);
        }

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