using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using TopWinCMS.BLL;
using TopWinCMS.Common;
using TopWinCMS.Model;
using TopWinCMS.Model.Enum;

namespace TopWinCMS.WebUI.Admin
{
    /// <summary>
    /// Admin_Article_Add 的摘要说明。
    /// </summary>
    public partial class Admin_Article_Add : System.Web.UI.Page
    {

        ArticleInfo model = new ArticleInfo();

        int iModelID;
        /// <summary>
        /// 自定义字段
        /// </summary>
        protected bool ExtendField = false;

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

            if (!IsPostBack)
            {
                Check();

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

                TB_UpDateTime.Text = DateTime.Now.ToString();
                LB_AnnexRemark.Text = "允许上传的格式：" + ModelManage.GetInfo(iModelID).AdminFileTypes;

                BindDropDownList();
                FieldEnabale();

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

            }
        }

        private void InitEveryPost()
        {
            iModelID = int.Parse(Request["ModelID"]);

            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

        #region  绑定DropDownList
        /// <summary>
        /// 绑定DropDownList
        /// </summary>
        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, "游客");

            ContentPropertyManage CP = new ContentPropertyManage();
            CP.BindDDL(this.DDL_Author, iModelID, 1, "<请选择作者>");
            CP.BindDDL(this.DDL_From, iModelID, 2, "<请选择来源>");

            DDL_Author.Attributes.Add("onchange", "GetAuthor();");
            DDL_From.Attributes.Add("onchange", "GetFrom();");
            DDL_FontStyle.Attributes.Add("onchange", "LoadStyle();");
        }
        #endregion

        private void FieldEnabale()
        {
            tr_Author.Visible = FieldControl.Enabale("Author");
            tr_From.Visible = FieldControl.Enabale("From");
            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_Title1.Visible = FieldControl.Enabale("Title1");
            tr_UpDateTime.Visible = FieldControl.Enabale("UpDateTime");

            //////////////////////////////////////////

            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 string.Concat("修改", ModelManage.GetContentName(iModelID));

            }
            else//添加界面
            {
                return string.Concat("添加", 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();
            }

            HF_AnnexFlag.Value = Request.QueryString["TempFlag"];

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

            BT_ArticleAdd.Visible = true;
            BT_ArticleAdd.Text = string.Concat("添加", ModelManage.GetContentName(iModelID));

            BT_ArticleEdit.Visible = false;

            new AnnexManage().BindList(GV_AnnexList, null, HF_AnnexFlag.Value);

        }
        #endregion

        #region 修改界面
        /// <summary>
        /// 修改界面
        /// </summary>
        private void EidtUI()
        {
            model = new ArticleManage(iModelID).EditLoad(int.Parse(Request["ID"]));
            DDL_ClassID.SelectedValue = model.ClassID.ToString();
            DDL_SpecialID.SelectedValue = model.SpecialID.ToString();
            TB_Title.Text = model.Title;
            TB_Title1.Text = model.Title1;
            TB_Author.Text = model.Author;
            TB_From.Text = model.From;

            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;
            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_ArticleAdd.Visible = false;
            BT_ArticleEdit.Visible = true;
            BT_ArticleEdit.Text = string.Concat("修改", ModelManage.GetContentName(iModelID));

            new AnnexManage().BindList(GV_AnnexList, Request["ID"], null);

            #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 添加修改
        /// <summary>
        /// 添加修改
        /// </summary>
        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 = iModelID;
            model.SpecialID = int.Parse(DDL_SpecialID.SelectedValue);
            model.Title = TB_Title.Text.Trim();
            model.Title1 = TB_Title1.Text.Trim();
            model.Author = TB_Author.Text.Trim();
            model.From = TB_From.Text.Trim();
            model.Editor = AdminLoginInfo.UserName;
            model.Key = TB_Key.Text.Trim();
            if (model.Key.Length == 0)
                model.Key = DDL_ClassID.SelectedItem.Text;

            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.ClassID = int.Parse(DDL_ClassID.SelectedValue);
            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 = CB_IsDraft.Checked == true ? 1 : 0;


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


            string Err = null;
            int ArticleID = new ArticleManage(iModelID).Add(model, HF_AnnexFlag.Value, Fields, Values, ref Err);
            if (string.IsNullOrEmpty(Err) == false)
            {
                MsgBox.Alert(Err, UpdatePanel1);
            }
            else
            {
                Response.Redirect(string.Concat("../Common/SaveOK.aspx?ClassID=", model.ClassID, "&ID=", ArticleID, "&SaveTitle=", model.Title, "&SaveAuthor=", model.Author, "&SaveFrom=", model.From, "&SaveKey=", model.Key, "&ModelID=", model.ModelID));
            }
        }
        #endregion

        protected void BT_ArticleEdit_Click(object sender, EventArgs e)
        {
            Add();
        }

        protected void BT_ArticleAdd_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 GV_AnnexList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteAnnex")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string ID = ID = GV_AnnexList.DataKeys[index].Values["ID"].ToString();
                string DownURL = GV_AnnexList.DataKeys[index].Values["DownURL"].ToString();
                new AnnexManage().Delete(ID, DownURL);
                new AnnexManage().BindList(GV_AnnexList, Request["ID"], HF_AnnexFlag.Value);
            }
        }

        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);
            }

            fi.Delete();

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

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

            AnnexInfo model = new AnnexInfo();

            model.FileName = args.FileName;

            string strSaveFile = Config.UP;
            strSaveFile = strSaveFile.Replace("/", "\\");;
            if (strSaveFile.EndsWith("/") == false)
            {
                strSaveFile += "/";
            }
            strSaveFile += System.DateTime.Now.ToString("yyyyMM") + "/";
            strSaveFile += args.FileGuid;
            strSaveFile += args.FileName;

            model.DownURL = strSaveFile;

            string strDir = Path.GetDirectoryName(Server.MapPath(strSaveFile));
            if (Directory.Exists(strDir) == false)
            {
                Directory.CreateDirectory(strDir);
            }
            args.MoveTo(Server.MapPath(strSaveFile));

            model.DownURL = model.DownURL.Replace("~/", "/");

            model.ContentID = Request.QueryString["ID"];

            model.ModelID = iModelID.ToString();
            model.TempFlag = HF_AnnexFlag.Value;

            AnnexManage A = new AnnexManage();

            A.Add(model);

            A.BindList(GV_AnnexList, model.ContentID, HF_AnnexFlag.Value);
        }

        protected void DDL_ClassID_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        protected void BT_CheckTitle_Click(object sender, EventArgs e)
        {
            if (TB_Title.Text.Trim().Length == 0)
            {
                MsgBox.Alert("请先输入", UpdatePanel1);
                return;
            }
            int i;
            if (new ArticleManage(iModelID).Exists(TB_Title.Text.Trim(), out i) == false)
            {
                MsgBox.Alert("没有重名", UpdatePanel1);
            }
        }
    }
}