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

using SnSee.Bean;

public partial class Admin_Product_ProductEdition : System.Web.UI.Page
{
    AdminBaseBean _AdminBeanLogin = null;
    protected Guid? ProductClassParentID;
    protected Guid? ProductBaseID;
    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.Product))
        {
            Response.Redirect("../ErrorTip.aspx?EMsg=该模块尚未开启，如需使用，请联系系统管理员！");
        }

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

        if (!ProductBaseID.HasValue)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您还未完成第一步：产品基本资料", "Product.aspx?ProductClassParentID" + ProductClassParentID);
            return;
        }

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

        EditionItem1.EditionID = EditionID;
        EditionItem1.ObjectID = ProductBaseID;
        EditionItem1.NavName = "ProductEdition";
        EditionItem1.UrlParameter = "&ProductClassParentID=" + ProductClassParentID;

        GetProductModuleConfig();

        if (ProductClassParentID.HasValue)
        {
            GetProductClassParent(ProductClassParentID.Value);
        }

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

            if (SnSee.Config.ProductConfig.AttributeOpen)
            {//如果开启产品参数
                rptAttributeList_DataBind();
            }

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

            if (ProductBaseID.HasValue)
            {
                boxDel.Visible = true;
                LoadProductList(EditionID.Value, ProductBaseID.Value);
            }
        }
        boxPageExplain.Visible = SnSee.Config.WebConfig.ViewAdminPageExplain;
    }

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

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

    /// <summary>
    /// 取得产品分类父级数据
    /// </summary>
    /// <param name="ID">父级分类ID</param>
    private void GetProductClassParent(Guid ID)
    {
        SnSee.Bean.ProductClassBean _ProductClassBean = (SnSee.Bean.ProductClassBean)SnSee.Factory.Factory.ProductClass.Select(ID);
        if (_ProductClassBean != null)
        {
            litTitle.Text = _ProductClassBean.ClassName + "管理 -> " + litTitle.Text;
        }
    }

    /// <summary>
    /// 载入参数列表
    /// </summary>
    private void rptAttributeList_DataBind()
    {
        rptAttributeList.DataSource = SnSee.Factory.Factory.ProductAttribute.SelectList(0, "State=1 And EditionID='{" + EditionID + "}'", "Order By SortOrder Asc, CreateTime Asc");
        rptAttributeList.DataBind();
    }
    protected void rptAttributeList_ItemDataBound(object source, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TextBox txtAttributeValue = (TextBox)e.Item.FindControl("txtAttributeValue");

            ProductAttributeBean _ProductAttributeBean = (ProductAttributeBean)e.Item.DataItem;
            if (_ProductAttributeBean != null && _ProductAttributeBean.AttributeType.HasValue)
            {
                switch (_ProductAttributeBean.AttributeType.Value)
                {
                    case 0://文本输入
                        txtAttributeValue.Visible = true;
                        #region 载入当前产品参数列表数据
                        if (ProductBaseID.HasValue)
                        {
                            ProductAttributeListBean _ProductAttributeListBean = (ProductAttributeListBean)SnSee.Factory.Factory.ProductAttributeList.Select("EditionID='{" + EditionID.Value + "}' And ProductBaseID='{" + ProductBaseID.Value + "}' And ProductAttributeID='{" + _ProductAttributeBean.ID.Value + "}'");
                            if (_ProductAttributeListBean != null)
                            {
                                txtAttributeValue.Text = _ProductAttributeListBean.AttributeValue;
                            }
                        }
                        #endregion
                        break;
                }
            }
        }
    }

    /// <summary>
    /// 取得产品模块配置
    /// </summary>
    private void GetProductModuleConfig()
    {
        boxProductOtherPic.Visible = SnSee.Config.ProductConfig.OtherPicOpen;
        pnlPrice.Visible = SnSee.Config.ProductConfig.PriceOpen;    //价格体系是否启用
        rptAttributeList.Visible = SnSee.Config.ProductConfig.AttributeOpen;    //参数
       // rptAttributeList.Visible = boxCustomAttribute.Visible = boxCustomAttribute2.Visible = SnSee.Config.ProductConfig.AttributeOpen;    //参数
        boxProductIntro.Visible = SnSee.Config.ProductConfig.IntroOpen;
    }

    /// <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="ProductID">产品ID</param>
    private void LoadProductList(Guid EditionID, Guid ProductBaseID)
    {
        ProductListBean _ProductListBean = (ProductListBean)SnSee.Factory.Factory.ProductList.Select("EditionID='{" + EditionID + "}' And ProductBaseID='{" + ProductBaseID + "}'");
        if (_ProductListBean != null)
        {
            dropClass.SelectedValue = _ProductListBean.ProductClassID.Value.ToString();
            txtProductName.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ProductListBean.Name);
            txtProductModel.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ProductListBean.Model);
            if (_ProductListBean.Price.HasValue && SnSee.Config.ProductConfig.PriceOpen)
            {
                txtPrice.Text = _ProductListBean.Price.Value.ToString();
            }
            txtSummary.Text = SnSee.Tool.EncodeTool.HtmlDecode(_ProductListBean.Summary);
            txtBody.Value = _ProductListBean.Body;
            if (_ProductListBean.SortOrder.HasValue)
            {
                txtSortOrder.Text = _ProductListBean.SortOrder.Value.ToString();
            }
            if (_ProductListBean.State.HasValue)
            {
                dropState.SelectedValue = _ProductListBean.State.Value.ToString();
            }
            if (!string.IsNullOrEmpty(_ProductListBean.UserLevelIDList) && cblUserLevelIDList.Items.Count > 0)
            {
                string[] arrUserLevelIDList = _ProductListBean.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)
    {
        string ProductName = SnSee.Tool.EncodeTool.HtmlEncode(txtProductName.Text);
        Guid? ProductClassID = SnSee.Tool.ConvertTool.GetGuid(dropClass.SelectedValue);
        decimal? Price = SnSee.Tool.ConvertTool.GetDecimal(txtPrice.Text);
        int? SortOrder = SnSee.Tool.ConvertTool.GetInt32(txtSortOrder.Text);
        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(ProductName) || !ProductClassID.HasValue)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您还未选择所属分类或未录入产品名称！");
            return;
        }

        if (!Price.HasValue && SnSee.Config.ProductConfig.PriceOpen)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您输入的销售价格不正确，请核查！");
            return;
        }

        if (!SortOrder.HasValue)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您输入的排序值不合格，只能输入整数！");
            return;
        }

        SnSee.Bean.ProductClassBean _ProductClassBean = (SnSee.Bean.ProductClassBean)SnSee.Factory.Factory.ProductClass.Select(ProductClassID.Value);
        if (_ProductClassBean != null && _ProductClassBean.IsChild.HasValue && !_ProductClassBean.IsChild.Value)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "您当前选择的产品分类不为最子级分类！");
            return;
        }

        ProductListBean _ProductListBean = new ProductListBean();
        _ProductListBean.ProductClassID = ProductClassID;
        _ProductListBean.Name = ProductName;
        _ProductListBean.Model = SnSee.Tool.EncodeTool.HtmlEncode(txtProductModel.Text);
        if (SnSee.Config.ProductConfig.PriceOpen)
        {
            _ProductListBean.Price = Price;
        }
        _ProductListBean.Summary = SnSee.Tool.EncodeTool.HtmlEncode(txtSummary.Text);
        _ProductListBean.Body = txtBody.Value;
        _ProductListBean.SortOrder = SortOrder;
        _ProductListBean.State = SnSee.Tool.ConvertTool.GetInt32(dropState.SelectedValue);
        _ProductListBean.UserLevelIDList = UserLevelIDList;

        string ReturnText = "";

        ProductListBean _ProductListBeanCheck = null;
        if (ProductBaseID.HasValue)
        {
            _ProductListBeanCheck = (ProductListBean)SnSee.Factory.Factory.ProductList.Select("EditionID='{" + EditionID.Value + "}' And ProductBaseID='{" + ProductBaseID.Value + "}'");
        }

        if (_ProductListBeanCheck == null || !ProductBaseID.HasValue)
        {//不存在数据,进行增加
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0101", true);
            _ProductListBean.ProductBaseID = ProductBaseID;
            _ProductListBean.EditionID = EditionID;
            if (!SnSee.Factory.Factory.ProductList.Insert(_ProductListBean))
            {
                _Return = false;
            }
            ReturnText = "增加";
        }
        else
        {//已存在数据,进行更新
            SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0103", true);
            if (!SnSee.Factory.Factory.ProductList.Update(_ProductListBean, "EditionID='{" + EditionID.Value + "}' And ProductBaseID='{" + ProductBaseID.Value + "}'"))
            {
                _Return = false;
            }
            ReturnText = "编辑";
        }

        #region 产品参数
        if (SnSee.Config.ProductConfig.AttributeOpen && _Return)
        {
            Literal litAttributeID;
            TextBox txtAttributeValue;
            Guid? AttributeID = null;
            string AttributeValue = "";

            SnSee.Interface.IProductAttributeList _IProductAttributeList = SnSee.Factory.Factory.ProductAttributeList; SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0102", true);
            _IProductAttributeList.Delete("ProductBaseID='{" + ProductBaseID.Value + "}' And EditionID='{" + EditionID.Value + "}'", false);//为了不重复数据,删除原参数数据
            for (int i = 0; i < rptAttributeList.Items.Count; i++)
            {
                ProductAttributeListBean _ProductAttributeListBean = new ProductAttributeListBean();
                litAttributeID = (Literal)rptAttributeList.Items[i].FindControl("litAttributeID");
                txtAttributeValue = (TextBox)rptAttributeList.Items[i].FindControl("txtAttributeValue");

                if (litAttributeID != null)
                {
                    AttributeID = SnSee.Tool.ConvertTool.GetGuid(litAttributeID.Text);
                }
                if (txtAttributeValue != null)
                {
                    AttributeValue = txtAttributeValue.Text;
                }

                if (AttributeID.HasValue)
                {
                    _ProductAttributeListBean.EditionID = EditionID;
                    _ProductAttributeListBean.ProductBaseID = ProductBaseID;
                    _ProductAttributeListBean.ProductAttributeID = AttributeID;
                    _ProductAttributeListBean.AttributeValue = AttributeValue;
                    _ProductAttributeListBean.State = 1; SnSee.Module.Admin.Admin.ManageIsExist(_AdminBeanLogin, "B0101", true);
                    if (!_IProductAttributeList.Insert(_ProductAttributeListBean, false))
                    {
                        _Return = false;
                    }
                }

            }
            _IProductAttributeList.Dispose();
        }
        #endregion

        if (_Return)
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，产品" + ReturnText + "成功！", "ProductList.aspx?ProductClassParentID=" + ProductClassParentID + "&EditionID=" + 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, "B0102", true);
        if (ProductBaseID.HasValue)
        {
            ProductListBean _ProductListBean = new ProductListBean();
            _ProductListBean.State = 0;
            if (SnSee.Factory.Factory.ProductList.Update(_ProductListBean, "ProductBaseID='{" + ProductBaseID.Value + "}'"))
            {
                SnSee.Tool.MessageTool.MessageBox(this.Page, "恭喜您，操作成功！", "ProductList.aspx?ProductClassParentID=" + ProductClassParentID + "&EditionID=" + EditionID);
            }
        }
        else
        {
            SnSee.Tool.MessageTool.MessageBox(this.Page, "数据错误，无法进行删除！", Request.RawUrl);
        }
    }
}