using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using TopWinCMS.BLL;
using TopWinCMS.Common;
using TopWinCMS.Model;
using TopWinCMS.Model.Enum;
namespace TopWinCMS.WebUI.Admin.Product
{
    public partial class Product_Add : System.Web.UI.Page
    { 
        int iModelID;
        ProductManage MyClassBLL;
        ProductInfo model = new ProductInfo();
        /// <summary>
        /// 自定义字段
        /// </summary>
        protected bool ExtendField = false;


        protected void Page_Load(object sender, System.EventArgs e)
        {

            InitEveryPost();

            if (!IsPostBack)
            {
                TB_UpDateTime.Text = DateTime.Now.ToString();

                Check();
                BindDropDownList();
                FieldEnabale();

                if (Request["ID"] != null)//修改界面
                {
                    EidtUI();
                }
                else//添加界面
                {
                    AddUI();
                }
            }
        }

        private void InitEveryPost()
        {
            if (Licenses.License.CurrentEdition == TopWinCMS.Licenses.Edition.免费开源版)
            {
                ErrClass.Redirect("该版本不支持此功能。");
            }
           
            iModelID = int.Parse( Request["ModelID"]);
            MyClassBLL = new ProductManage(iModelID);

            new FieldObject(iModelID).LoadUI(T_DefinedFile, out ExtendField);
        }

        #region 检测权限
        /// <summary>
        /// 检测权限
        /// </summary>
        private void Check()
        {
            if (Request["ID"] != null)//修改界面
            {
                RightsCheck.CheckWorkRight("ContenEdit", true);

            }
            else//添加界面
            {
                RightsCheck.CheckWorkRight("ContenAdd", true);

                CB_ContentPass.Checked = RightsCheck.HasRight("ContentPass", true);
                CB_Pass.Checked = RightsCheck.HasRight("BriefPass", true);
            }
        }
        #endregion

        private void BindDropDownList()
        {
            new ClassManage().BindDDL(DDL_ClassID, Class_BindOption.NoLink, "<请选择栏目>", iModelID );

            new SpecialManage().BindDDL(DDL_SpecialID, Special_BindOption.NoLink, "<请选择专题>", iModelID );

            new MemberRoleManage().BindDropDownList(DDL_Rank, "游客");

            DDL_FontStyle.Attributes.Add("onchange", "LoadStyle();");
        }

        private void FieldEnabale()
        {
            tr_ProductPrice.Visible = FieldControl.Enabale("ProductPrice");
            tr_Hits.Visible = FieldControl.Enabale("Hits");
            tr_Key.Visible = FieldControl.Enabale("Key");

            tr_PicUrl.Visible = FieldControl.Enabale("PicUrl");
            //tr_PicUr_Other.Visible = tr_PicUrl.Visible;
            tr_PointNum.Visible = FieldControl.Enabale("PointNum");
            tr_Rank.Visible = FieldControl.Enabale("Rank");
            tr_SpecialID.Visible = FieldControl.Enabale("SpecialID");

            tr_Stars.Visible = FieldControl.Enabale("Stars");
            tr_TemplateFileName.Visible = FieldControl.Enabale("TemplateFileName");

            tr_UpDateTime.Visible = FieldControl.Enabale("UpDateTime");
            tr_Standard.Visible = FieldControl.Enabale("Standard");
            tr_Packaging.Visible = FieldControl.Enabale("Packaging");
            tr_Brand.Visible = FieldControl.Enabale("Brand");
            //////////////////////////////////////////

            CB_OnTop.Visible = FieldControl.Enabale("OnTop");
            CB_Elite.Visible = FieldControl.Enabale("Elite");

            if (FieldControl.Enabale("IncludePic") == false)
            {
                CB_IncludePic.Visible = false;
                CB_IncludePic.Checked = true;
            }
            if (FieldControl.Enabale("Pass") == false)
            {
                CB_Pass.Visible = false;
                CB_Pass.Checked = true;
            }

            if (FieldControl.Enabale("ColorStyle") == false)
            {
                imgColorStyle.Visible = false;
                TB_ColorStyle.Text = "";
            }
            if (FieldControl.Enabale("AllowComment") == false)
            {
                CB_AllowComment.Visible = false;
                CB_AllowComment.Checked = true;
            }
            CB_IsSlide.Visible = FieldControl.Enabale("IsSlide");

            DDL_FontStyle.Visible = FieldControl.Enabale("FontStyle");

            //改变选项卡

        }

        protected string AutoTitle()
        {
            if (Request["ID"] != null)//修改界面
            {
                return "修改" + ModelManage.GetContentName(iModelID);

            }
            else//添加界面
            {
                return "添加" + ModelManage.GetContentName(iModelID);
            }
        }


        #region 添加界面
        /// <summary>
        /// 添加界面
        /// </summary>
        private void AddUI()
        {
            if (Session["Key"] != null || Session["SelectClassID"] != null)
            {
                TB_Key.Text = Session["Key"].ToString();
                DDL_ClassID.SelectedValue = Session["SelectClassID"].ToString();
            }

            TB_TemplateFileName.Text = BLL.HTMLBuilder.Templates.DefaultTemplate.ProductShow_aspx;

            BT_Edit.Visible = false;
        }
        #endregion

        #region 修改界面
        /// <summary>
        /// 修改界面
        /// </summary>
        private void EidtUI()
        {
            model = new ProductManage(iModelID).EditLoad(int.Parse( Request["ID"]));
            DDL_ClassID.SelectedValue = model.ClassID.ToString();
            DDL_SpecialID.SelectedValue = model.SpecialID.ToString();
            TB_ProductName.Text = model.ProductName;
            NTB_ProductPrice.Text = model.ProductPrice.ToString();
            TB_Standard.Text = model.Standard;
            TB_Packaging.Text = model.Packaging;
            TB_Brand.Text = model.Brand;
            TB_Key.Text = model.Key;

            CB_OnTop.Checked = model.OnTop == 1 ? true : false;
            CB_Elite.Checked = model.Elite == 1 ? true : false;
            CE_Content.Text = model.Content;
            CB_IncludePic.Checked = model.IncludePic == 1 ? true : false;
            TB_PicUrl.Text = model.PicUrl;
            LB_BigPicUrl.Text = model.BigPicUrl;
            DDL_Stars.SelectedValue = model.Stars.ToString();
            CB_Pass.Checked = (model.Pass == 1 ? true : false);
            CB_Pass.Enabled = RightsCheck.HasRight("BriefPass", true); //对是否有权限进行审核

            CB_ContentPass.Checked = model.ContentPass == 1 ? true : false;
            CB_ContentPass.Enabled = RightsCheck.HasRight("ContentPass", true);//对是否有权限进行内容审核

            DDL_Rank.SelectedValue = model.Rank.ToString();
            NTB_PointNum.Text = model.PointNum.ToString();
            NTB_Hits.Text = model.Hits.ToString();

            TB_ColorStyle.Text = model.ColorStyle;
            string StrScript;
            StrScript = ("<script language=javascript>");
            StrScript += ("LoadStyle();");
            StrScript += ("</script>");
            this.ClientScript.RegisterStartupScript(this.GetType(), "LoadStyle", StrScript.ToString());


            DDL_FontStyle.SelectedValue = model.FontStyle;
            CB_AllowComment.Checked = model.AllowComment == 1 ? true : false;
            TB_Brief.Text = model.Brief;
            TB_TemplateFileName.Text = model.TemplateFileName;
            CB_IsSlide.Checked = model.IsSlide == 1 ? true : false;
            CB_IsDraft.Checked = model.IsDraft == 1 ? true : false;

            BT_Add.Visible = false;
            BT_Edit.Visible = true;
            BT_Edit.Text = "修改" + ModelManage.GetContentName(iModelID);

           
            #region 自定义字段
            string strErr = null;
            new FieldManage().ExtendFieldData(iModelID, false, Request["ID"], T_DefinedFile, ref strErr);
            if (string.IsNullOrEmpty(strErr) == false)
                MsgBox.Alert(strErr.Replace("'", "\\'"), this);
            #endregion
        }
        #endregion

        #region 添加
        private void add()
        {
            model.ModelID = iModelID;
            model.SpecialID = int.Parse(DDL_SpecialID.SelectedValue);
            model.ClassID = int.Parse(DDL_ClassID.SelectedValue);
            model.ProductName = TB_ProductName.Text.Trim();
            model.ProductPrice = decimal.Parse(NTB_ProductPrice.Text);

            model.Standard = TB_Standard.Text;
            model.Packaging = TB_Packaging.Text;
            model.Brand = TB_Brand.Text;

            model.Editor = AdminLoginInfo.UserName;
            model.Key = TB_Key.Text.Trim();
            model.OnTop = CB_OnTop.Checked == true ? 1 : 0;
            model.Elite = CB_Elite.Checked == true ? 1 : 0;
            model.Content = DownPic(CE_Content.Text, CB_DownPic.Checked);
            model.IncludePic = CB_IncludePic.Checked == true ? 1 : 0;
            model.PicUrl = TB_PicUrl.Text.Trim();
            model.BigPicUrl = LB_BigPicUrl.Text.Trim();
            model.Stars = int.Parse(DDL_Stars.SelectedValue);
            model.Pass = CB_Pass.Checked == true ? 1 : 0;
            model.Rank = int.Parse(DDL_Rank.SelectedValue);
            model.PointNum = int.Parse(NTB_PointNum.Text.Trim());
            model.Hits = int.Parse(NTB_Hits.Text.Trim());
            model.UpdateTime = DateTime.Parse(TB_UpDateTime.Text);
            model.ColorStyle = TB_ColorStyle.Text.Trim();
            model.FontStyle = DDL_FontStyle.SelectedValue;
            model.AllowComment = CB_AllowComment.Checked == true ? 1 : 0;
            model.Brief = TB_Brief.Text.Trim();
            model.ContentPass = CB_ContentPass.Checked == true ? 1 : 0;
            model.TemplateFileName = TB_TemplateFileName.Text.Trim();

            model.IsSlide = CB_IsSlide.Checked == true ? 1 : 0;
            model.IsDraft = 0;


            if (Request["ID"] == null)
            {
                model.ID = 0;
            }
            else
            {
                model.ID = int.Parse(Request["ID"]);
            }
            string Err = null;

            int ProductID = MyClassBLL.Add(model, ref  Err);

            if (string.IsNullOrEmpty(Err) == false)
            {
                MsgBox.Alert(Err);
            }
            else
            {
                HttpContext.Current.Response.Redirect("../Common/SaveOK.aspx?ClassID=" + model.ClassID + "&ID=" + ProductID + "&SaveProductName=" + model.ProductName + "&SaveKey=" + model.Key + "&ModelID=" + model.ModelID);
            }
        }
        #endregion

        protected void BT_Add_Click(object sender, EventArgs e)
        {
            add();
        }

        protected void BT_Edit_Click(object sender, EventArgs e)
        {
            add();
        }

        #region 下载图片
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="DownPic"></param>
        /// <returns></returns>
        private string DownPic(string strContent, bool DownPic)
        {
            if (DownPic == true)
            {
                //读取这个栏目的图片保存路径
                string strPicPath = new BLL.ClassManage().EditLoad(int.Parse(DDL_ClassID.SelectedValue)).PicPath;
                if (string.IsNullOrEmpty(strPicPath) == true)
                {
                    strPicPath = Config.UP;
                }
                return new TopWinCMS.GatherEngine.Utilities().DownPic(strContent, DownPic, CB_DrawWatherMark.Checked, strPicPath);
            }
            else
            {
                return strContent;
            }
        }
        #endregion

        protected void FileUploader1_FileUploaded(object sender, CuteEditor.UploaderEventArgs args)
        {
            if (DDL_ClassID.SelectedValue == "0")
            {
                MsgBox.Alert("请选择栏目", UpdatePanel1);
                return;
            }
            if (UpFileHepler.Check(args.FileName, true) == false)
            {
                MsgBox.Alert("不允许上传这种类型文件", UpdatePanel1);
                args.Delete();
                return;
            }

            string FilePath = ClassManage.GetSavePath(int.Parse(DDL_ClassID.SelectedValue), args.FileName, true);
            args.MoveTo(FilePath);

            Thumbnails T = new Thumbnails(FilePath);
            string str = null;
            FileInfo fi = new FileInfo(FilePath);
            string NewFilePath = string.Concat(fi.DirectoryName, @"\", Guid.NewGuid().ToString(), fi.Extension);

            if (CB_BiLi.Checked)
            {
                T.ReducedImage(int.Parse(TB_PicW.Text), int.Parse(TB_PicH.Text), NewFilePath, ref str);
            }
            else
            {

                T.ReducedImage(int.Parse(TB_PicW.Text), int.Parse(TB_PicH.Text), NewFilePath);
            }



            NewFilePath = NewFilePath.Replace(Server.MapPath("~/"), "/");
            NewFilePath = NewFilePath.Replace(@"\", "/");
            this.TB_PicUrl.Text = NewFilePath.Replace(@"\", "/");

            NewFilePath = fi.FullName;
            NewFilePath = NewFilePath.Replace(Server.MapPath("~/"), "/");
            this.LB_BigPicUrl.Text = NewFilePath.Replace(@"\", "/");

        }

        protected void BT_UpLoad0_Click(object sender, EventArgs e)
        {
            if (DDL_ClassID.SelectedValue == "0")
            {
                MsgBox.Alert("请选择栏目", UpdatePanel1);
                return;
            }
            if (UpFileHepler.Check(HttpServer.GetFileName(TB_YC.Text.Trim()), true) == false)
            {
                MsgBox.Alert("不允许上传这种类型文件", UpdatePanel1);

                return;
            }

            //读取这个栏目的图片保存路径
            string strPicPath = new BLL.ClassManage().EditLoad(int.Parse(DDL_ClassID.SelectedValue)).PicPath;
            if (string.IsNullOrEmpty(strPicPath) == true)
            {
                strPicPath = Config.UP;
            }
            string vPicUrl = "";
            string pPicUrl = "";
            new TopWinCMS.GatherEngine.Utilities().DownPic(TB_YC.Text.Trim(), false, strPicPath, ref vPicUrl, ref pPicUrl);


            Thumbnails T = new Thumbnails(pPicUrl);
            string str = null;
            FileInfo fi = new FileInfo(pPicUrl);
            string NewFilePath = string.Concat(fi.DirectoryName, @"\", Guid.NewGuid().ToString(), fi.Extension);

            if (CB_BiLi.Checked)
            {
                T.ReducedImage(int.Parse(TB_PicW.Text), int.Parse(TB_PicH.Text), NewFilePath, ref str);
            }
            else
            {

                T.ReducedImage(int.Parse(TB_PicW.Text), int.Parse(TB_PicH.Text), NewFilePath);
            }


            this.TB_PicUrl.Text = NewFilePath.Replace(Server.MapPath(@"~\"), @"/").Replace(@"\", "/");


            this.LB_BigPicUrl.Text = vPicUrl.Replace(@"\", "/");
        }

        protected void TB_CheckProductName_Click(object sender, EventArgs e)
        {
            if (this.TB_ProductName.Text.Trim().Length == 0)
            {
                MsgBox.Alert("请先输入", UpdatePanel1);
                return;
            }

            ProductInfo model = new ProductInfo();
            model.ProductName = TB_ProductName.Text.Trim();


            if (new ProductManage(iModelID).Exists(model) == false)
            {
                MsgBox.Alert("没有重名", UpdatePanel1);
            }
        }
    }
}