using System;
using System.Collections;
using System.Collections.Generic;
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.Shop
{
    public partial class Goods_Add : System.Web.UI.Page
    {

        int ModelID;
        ShopManage MyClassBLL;
        ShopInfo model = new ShopInfo();
        /// <summary>
        /// 自定义字段
        /// </summary>
        protected bool ExtendField = false;


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

            InitEveryPost();

            if (!IsPostBack)
            {
                if (Request.QueryString["TempFlag"] == null && Request["ID"] == null)
                {
                    Response.Redirect(Request.RawUrl + "&TempFlag=" + Guid.NewGuid().ToString());
                }
                TB_UpDateTime.Text = DateTime.Now.ToString();

                BindDropDownList();


                if (Request["ID"] != null)//修改界面
                {

                    this.EidtUI();
                }
                else//添加界面
                {
                    AddUI();
                }

                ShopImgs_BindList();
            }
        }

        private void InitEveryPost()
        {
            if (Licenses.License.CurrentEdition == TopWinCMS.Licenses.Edition.免费开源版)
            {
                ErrClass.Redirect("该版本不支持此功能。");
            }

            ModelID = int.Parse(Request["ModelID"]);
            MyClassBLL = new ShopManage(ModelID);

            if (Request["ID"] != null)//修改界面
            {
                model = new ShopManage(ModelID).EditLoad(int.Parse(Request["ID"]));

                if (Request["ClassID"] == null)
                {
                    Response.Redirect("Shop_Add.aspx?ModelID=" + model.ModelID + "&ClassID=" + model.ClassID + "&ID=" + model.ID);
                }

                new FieldObject(ModelID).LoadUI(T_DefinedFile, model.ClassID.ToString(), out ExtendField);
                li_KuoZhanShuXing.Visible = ExtendField;
            }
            else
            {
                new FieldObject(ModelID).LoadUI(T_DefinedFile, Request["ClassID"], out ExtendField);
                li_KuoZhanShuXing.Visible = ExtendField;
            }
        }


        private void BindDropDownList()
        {
            new SpecialManage().BindDDL(DDL_SpecialID, Special_BindOption.NoLink, "<请选择专题>", ModelID);

            DDL_FontStyle.Attributes.Add("onchange", "LoadStyle();");
            new BrandManage().BindDDL(this.DDL_BrandID, "<请选择品牌>");
        }



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

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



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

            }

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

            BT_Edit.Visible = false;
        }
        #endregion

        #region 修改界面
        /// <summary>
        /// 修改界面
        /// </summary>
        private void EidtUI()
        {
            TB_GoodsNum.Text = model.GoodsNum;
            TB_BarCode.Text = model.BarCode;
            TB_GoodsName.Text = model.GoodsName;
            NTB_PriceMarket.Text = model.PriceMarket.ToString();
            NTB_PriceMember.Text = model.PriceMember.ToString();
            TB_Unit.Text = model.Unit;
            TB_Key.Text = model.Key;
            TB_PicUrl.Text = model.PicUrl;
            LB_BigPicUrl.Text = model.BigPicUrl;
            NTB_Stocks.Text = model.Stocks.ToString();
            NTB_AlarmNum.Text = model.AlarmNum.ToString();


            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;
            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);//对是否有权限进行内容审核
            CB_AllowComment.Checked = model.AllowComment == 1 ? true : false;
            CB_IsSlide.Checked = model.IsSlide == 1 ? true : false;
            CB_IsDraft.Checked = model.IsDraft == 1 ? true : false;

            DDL_BrandID.SelectedValue = model.BrandID.ToString();
            TB_Standard.Text = model.Standard;
            TB_Packaging.Text = model.Packaging;

            DDL_SpecialID.SelectedValue = model.SpecialID.ToString();
            DDL_Stars.SelectedValue = model.Stars.ToString();
            NTB_Hits.Text = model.Hits.ToString();
            TB_TemplateFileName.Text = model.TemplateFileName;


            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;
            TB_Brief.Text = model.Brief;

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

            #region 自定义字段
            new FieldManage().ExtendFieldData(model.ID, T_DefinedFile);
            #endregion
        }
        #endregion

        #region 添加
        private void add()
        {
            List<string> Fields = new List<string>();
            List<object> Values = new List<object>();
            foreach (TableRow tr in T_DefinedFile.Rows)
            {
                System.Web.UI.Control c = tr.Cells[1].Controls[0];
                if (c is TextBox)
                {
                    TextBox tb = c as TextBox;
                    Fields.Add(tb.ID);
                    Values.Add(tb.Text.Trim());
                }
                if (c is DropDownList)
                {
                    DropDownList ddl = c as DropDownList;
                    Fields.Add(ddl.ID);
                    Values.Add(ddl.SelectedValue);
                }
                if (c is RadioButtonList)
                {
                    RadioButtonList rbl = c as RadioButtonList;
                    Fields.Add(rbl.ID);
                    Values.Add(rbl.SelectedValue);
                }
                if (c is CheckBox)
                {
                    CheckBox cb = c as CheckBox;
                    Fields.Add(cb.ID);
                    Values.Add(cb.Checked);
                }
            }


            model.ModelID = ModelID;
            model.GoodsNum = TB_GoodsNum.Text;
            model.BarCode = TB_BarCode.Text;
            model.GoodsName = TB_GoodsName.Text.Trim();
            model.PriceMarket = decimal.Parse(NTB_PriceMarket.Text);
            model.PriceMember = decimal.Parse(NTB_PriceMember.Text);
            model.ClassID = int.Parse(Request["ClassID"].ToString());
            model.Unit = TB_Unit.Text;
            model.Key = TB_Key.Text.Trim();
            model.PicUrl = TB_PicUrl.Text.Trim();
            model.BigPicUrl = LB_BigPicUrl.Text.Trim();
            model.Stocks = int.Parse(NTB_Stocks.Text);
            model.AlarmNum = int.Parse(NTB_AlarmNum.Text);


            model.OnTop = CB_OnTop.Checked == true ? 1 : 0;
            model.Elite = CB_Elite.Checked == true ? 1 : 0;
            model.IncludePic = CB_IncludePic.Checked == true ? 1 : 0;
            model.Pass = CB_Pass.Checked == true ? 1 : 0;
            model.ContentPass = CB_ContentPass.Checked == true ? 1 : 0;
            model.AllowComment = CB_AllowComment.Checked == true ? 1 : 0;
            model.IsSlide = CB_IsSlide.Checked == true ? 1 : 0;
            model.IsDraft = 0;


            model.BrandID = int.Parse(DDL_BrandID.SelectedValue);
            model.Standard = TB_Standard.Text;
            model.Packaging = TB_Packaging.Text;
            model.Brand = "";
            model.SpecialID = int.Parse(DDL_SpecialID.SelectedValue);
            model.Stars = int.Parse(DDL_Stars.SelectedValue);
            model.Editor = AdminLoginInfo.UserName;
            model.Hits = int.Parse(NTB_Hits.Text.Trim());
            model.Brief = TB_Brief.Text.Trim();
            model.Content = DownPic(CE_Content.Text, CB_DownPic.Checked);
            model.UpdateTime = DateTime.Parse(TB_UpDateTime.Text);
            model.ColorStyle = TB_ColorStyle.Text.Trim();
            model.FontStyle = DDL_FontStyle.SelectedValue;
            model.TemplateFileName = TB_TemplateFileName.Text.Trim();

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

            int ShopID = MyClassBLL.Add(model, Request.QueryString["TempFlag"], Fields, Values, ref  Err);

            if (string.IsNullOrEmpty(Err) == false)
            {
                MsgBox.Alert(Err);
            }
            else
            {
                HttpContext.Current.Response.Redirect("../Common/SaveOK.aspx?ClassID=" + model.ClassID + "&ID=" + ShopID + "&SaveGoodsName=" + model.GoodsName + "&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(Request["ClassID"].ToString())).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 (UpFileHepler.Check(args.FileName, true) == false)
            {
                MsgBox.Alert("不允许上传这种类型文件", UpdatePanel1);
                args.Delete();
                return;
            }

            string FilePath = ClassManage.GetSavePath(int.Parse(Request["ClassID"].ToString()), 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(@"\", "/");

            MyJavascript.RegJS(UpdatePanel1, "HideAndDisplay(CurrentTab);");
        }

        protected void BT_UpLoad0_Click(object sender, EventArgs e)
        {
            if (UpFileHepler.Check(HttpServer.GetFileName(TB_YC.Text.Trim()), true) == false)
            {
                MsgBox.Alert("不允许上传这种类型文件", UpdatePanel1);

                return;
            }

            //读取这个栏目的图片保存路径
            string strPicPath = new BLL.ClassManage().EditLoad(int.Parse(Request["ClassID"].ToString())).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(@"\", "/");

            MyJavascript.RegJS(UpdatePanel1, "HideAndDisplay(CurrentTab);");
        }

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

            ShopInfo model = new ShopInfo();
            model.GoodsName = TB_GoodsName.Text.Trim();


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

        }

        protected void BT_ShopImgsAdd_Click(object sender, EventArgs e)
        {
            ShopImgsInfo model = new ShopImgsInfo();
            model.ID = 0;
            model.GoodsID = Request["ID"] == null ? 0 : int.Parse(Request["ID"]);
            model.Title = TB_ShopImgsTitle.Text.Trim();
            model.PicUrl = TB_ShopImgsPicUrl.Text.Trim();
            model.TempGUID = Request["TempFlag"] == null ? "" : Request["TempFlag"];
 
            string strErr = null;

            new ShopImgsManage().Add(model, ref strErr);

            if (string.IsNullOrEmpty(strErr) == false)
            {
                MsgBox.Alert(strErr, UpdatePanel1);
                MyJavascript.RegJS(UpdatePanel1, "HideAndDisplay(CurrentTab);");
            }
            else
            {
                TB_ShopImgsTitle.Text = "";
                TB_ShopImgsPicUrl.Text = "";
                ShopImgs_BindList();
            }
        }
        private void ShopImgs_BindList()
        {
            int GoodsID = Request["ID"] == null ? -1 : int.Parse(Request["ID"]);
            string TempGUID = Request["TempFlag"] == null ? "" : Request["TempFlag"];
            new ShopImgsManage().GetLists(GV_ShopImgs, TempGUID, GoodsID);
            MyJavascript.RegJS(UpdatePanel1, "HideAndDisplay(CurrentTab);");
        }

        protected void UL_ShopImgs_Uploader_FileUploaded(object sender, CuteEditor.UploaderEventArgs args)
        {
            if (UpFileHepler.Check(args.FileName, true) == false)
            {
                MsgBox.Alert("不允许上传这种类型文件", UpdatePanel1);
                args.Delete();
                return;
            }

            string FilePath = UL_ShopImgs_Uploader.TempDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + args.FileName;

            args.MoveTo(Server.MapPath(FilePath));

            FilePath = FilePath.Replace("~", "");
            TB_ShopImgsPicUrl.Text = FilePath;

            MyJavascript.RegJS(UpdatePanel1, "HideAndDisplay(CurrentTab);");

        }


    }
}