using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using TopWinCMS.BLL;
using TopWinCMS.Common;
using TopWinCMS.Model;
using TopWinCMS.Model.Enum;
namespace TopWinCMS.WebUI.Admin
{
    /// <summary>
    /// Admin_Soft_Add 的摘要说明。
    /// </summary>
    public partial class Admin_Soft_Add : TopWinCMS.WebFactory.PageBase
    {
        protected System.Web.UI.WebControls.CheckBoxList CheckBoxList2;
        protected string serverlistJS = "";

        SoftManage MyClassBLL;
        ClassManage MySoftClassBLL = new ClassManage();
        SoftInfo model = new SoftInfo();

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


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


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

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

            iModelID = int.Parse(Request["ModelID"]);

            MyClassBLL = new SoftManage(iModelID);

            DataSet ds = new SoftServerManage().BindDDL(DownLoadServer, "", iModelID);
            serverlistJS += "<select name=\"DownLoadServer\" size=\"1\">";
            string strlist = "";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                strlist += string.Format("<option value=\"{0}\">{1}</option>", dr["ID"], dr["ServerName"]);
            }
            serverlistJS += strlist + "</select>";
            serverlistJS = "str+=''+'" + serverlistJS;
            serverlistJS += "<input type=\"text\" name=\"FileName\" size=\"50\" value=\"\"><br />';";


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

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

        private void BindDropDownList()
        {
            new MemberRoleManage().BindDropDownList(DDL_Rank, "游客");
            MySoftClassBLL.BindDDL(DDL_SoftClass, Class_BindOption.NoLink, "<请选择栏目>", iModelID);

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

            ContentPropertyManage CP = new ContentPropertyManage();
            CP.BindDDL(this.DDL_Author, iModelID, 3, "<请选择>");
            CP.BindDDL(this.DDL_Email, iModelID, 4, "<请选择>");
            CP.BindDDL(this.DDL_DecompressPassword, iModelID, 5, "<请选择>");

            DDL_Author.Attributes.Add("onchange", "GetAuthor();");
            DDL_Email.Attributes.Add("onchange", "GetEmail();");
            DDL_DecompressPassword.Attributes.Add("onchange", "GetDecompressPassword();");


        }

        #region 初始化界面
        private void InitUI()
        {
            tr_Author.Visible = FieldControl.Enabale("Author");
            tr_BlackGuard.Visible = FieldControl.Enabale("BlackGuard");
            tr_Brief.Visible = FieldControl.Enabale("Brief");
            tr_CopyrightType.Visible = FieldControl.Enabale("CopyrightType");
            tr_DecompressPassword.Visible = FieldControl.Enabale("DecompressPassword");
            tr_DemoUrl.Visible = FieldControl.Enabale("DemoUrl");
            tr_Email.Visible = FieldControl.Enabale("Email");
            tr_Hits.Visible = FieldControl.Enabale("Hits");
            tr_Homepage.Visible = FieldControl.Enabale("Homepage");
            tr_TemplateFileName.Visible = FieldControl.Enabale("TemplateFileName");
            tr_PicUrl.Visible = FieldControl.Enabale("PicUrl");

            tr_PointNum.Visible = FieldControl.Enabale("PointNum");
            tr_Rank.Visible = FieldControl.Enabale("Rank");
            NTB_PointNum.Visible = FieldControl.Enabale("PointNum");
            tr_RunAtSystem.Visible = FieldControl.Enabale("RunAtSystem");
            tr_SoftLanguage.Visible = FieldControl.Enabale("SoftLanguage");
            tr_SoftSize.Visible = FieldControl.Enabale("SoftSize");
            tr_SoftType.Visible = FieldControl.Enabale("SoftType");
            tr_SoftVersion.Visible = FieldControl.Enabale("SoftVersion");
            tr_Stars.Visible = FieldControl.Enabale("Stars");
            tr_UpDateTime.Visible = FieldControl.Enabale("UpDateTime");

            tr_SpecialID.Visible = FieldControl.Enabale("SpecialID");

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

            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");
        }
        #endregion

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

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

        #region 添加界面
        /// <summary>
        /// 修改界面
        /// </summary>
        private void AddUI()
        {


            BT_SoftAdd.Visible = true;
            BT_SoftAdd.Attributes.Add("onclick", "return CheckForm();");
            BT_SoftEdit.Visible = false;
            TR_SoftDownList_Edit.Visible = false;


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

            //加载默认值
            CB_Pass.Checked = true;

            string[] arrStr = SoftConfig.RunAtSystem.Split(',');
            foreach (ListItem CB in CBL_RunAtSystem.Items)
            {
                foreach (string str in arrStr)
                {
                    if (CB.Value == str)
                    {
                        CB.Selected = true;
                    }
                }
            }


        }
        #endregion

        #region 修改界面
        /// <summary>
        /// 修改界面
        /// </summary>
        private void EidtUI()
        {
            BT_SoftAdd.Visible = false;
            BT_SoftEdit.Visible = true;
            BT_SoftEdit.Attributes.Add("onclick", "return CheckForm();");

            model = MyClassBLL.EditLoad(int.Parse(Request["ID"]));

            DDL_SoftClass.SelectedValue = model.ClassID.ToString();
            DDL_SoftLanguage.SelectedValue = model.SoftLanguage;
            DDL_SoftType.SelectedValue = model.SoftType;
            TB_SoftName.Text = model.SoftName;
            TB_SoftVersion.Text = model.SoftVersion;
            TB_SoftSize.Text = model.SoftSize;
            TB_Key.Text = model.Key;

            DDL_Stars.SelectedValue = model.Stars.ToString();
            DDL_CopyrightType.SelectedValue = model.CopyrightType;
            try
            {
                string[] arrStr = model.RunAtSystem.Split(',');
                foreach (ListItem CB in CBL_RunAtSystem.Items)
                {
                    foreach (string str in arrStr)
                    {
                        if (CB.Value == str)
                        {
                            CB.Selected = true;
                        }
                    }
                }
            }
            catch
            {
                MsgBox.Alert("加载软件运行平台的时候错误，请重新勾选。", this);
            }

            TB_Brief.Text = model.Brief;
            TB_Author.Text = model.Author;
            TB_Email.Text = model.Email;

            TB_Homepage.Text = model.Homepage;
            TB_DemoUrl.Text = model.DemoUrl;
            TB_PicUrl.Text = model.PicUrl;
            CB_IncludePic.Checked = model.IncludePic == 1 ? true : false;
            CB_OnTop.Checked = model.OnTop == 1 ? true : false;
            CB_Elite.Checked = model.Elite == 1 ? true : false;

            TB_DecompressPassword.Text = model.DecompressPassword;
            CE_Content.Text = HTML.Html2Text(model.Content);
            DDL_BlackGuard.SelectedValue = model.BlackGuard;

            CB_ContentPass.Checked = model.ContentPass == 1 ? true : false;
            CB_Pass.Checked = model.Pass == 1 ? true : false;
            DDL_Rank.SelectedValue = model.Rank.ToString();

            NTB_PointNum.Text = model.PointNum.ToString();
            NTB_Hits.Text = model.Hits.ToString();
            CB_AllowComment.Checked = model.AllowComment == 1 ? true : false;
            TB_TemplateFileName.Text = model.TemplateFileName;

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

            TD_SoftDownList_Edit.InnerHtml = new SoftDownListManage().GetDownListJS(iModelID, Request["ID"]);
            TD_SoftDownList_Edit.InnerHtml = TD_SoftDownList_Edit.InnerHtml.Replace("name=\"DownLoadServer\"", "name=\"DownLoadServer_Edit\"");
            TR_SoftDownList_Edit.Visible = true;

            #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

        protected void BT_SoftAdd_Click(object sender, System.EventArgs e)
        {
            if (ClassManage.CheckAllowClass(DDL_SoftClass.SelectedValue, iModelID, true) == false)
            {
                MsgBox.Alert("您没有该栏目的录入权限！");

                return;
            }
            if (CBL_RunAtSystem.SelectedItem == null)
            {
                MsgBox.Alert(" 请选择软件平台！");
                return;
            }

            model.ModelID = iModelID;
            model.ClassID = int.Parse(DDL_SoftClass.SelectedValue);
            model.SoftLanguage = DDL_SoftLanguage.SelectedValue;
            model.SoftType = DDL_SoftType.SelectedValue;
            model.SoftName = TB_SoftName.Text.Trim();
            model.SoftVersion = TB_SoftVersion.Text.Trim();
            model.SoftSize = TB_SoftSize.Text.Trim();
            model.Stars = int.Parse(DDL_Stars.SelectedValue);
            model.CopyrightType = DDL_CopyrightType.SelectedValue;
            model.SpecialID = int.Parse(DDL_SpecialID.SelectedValue);


            MyStringBuilder winner = new MyStringBuilder();
            foreach (ListItem CB in CBL_RunAtSystem.Items)
            {
                if (CB.Selected == true)
                {
                    winner.Append(CB.Value);
                    winner.Append(",");
                }
            }
            winner.TrimEnd();
            model.RunAtSystem = winner.ToString();
            model.Key = TB_Key.Text.Trim();
            if (model.Key.Length == 0)
            {
                model.Key = TB_SoftName.Text.Trim();
                model.Key = model.Key.Replace(" ", "|");
            }

            model.Author = TB_Author.Text.Trim();
            model.Email = TB_Email.Text.Trim();
            model.Homepage = TB_Homepage.Text.Trim();
            model.DemoUrl = TB_DemoUrl.Text.Trim();
            model.OnTop = CB_OnTop.Checked == true ? 1 : 0;
            model.Elite = CB_Elite.Checked == true ? 1 : 0;
            model.DecompressPassword = TB_DecompressPassword.Text.Trim();
            model.Brief = TB_Brief.Text.Trim();

            model.Content = HTML.Text2Html(CE_Content.Text);
            model.IncludePic = CB_IncludePic.Checked == true ? 1 : 0;
            model.PicUrl = TB_PicUrl.Text.Trim();
            model.IncludePic = TB_PicUrl.Text.Length > 0 ? 1 : 0;
            model.Editor = AdminLoginInfo.UserName;
            model.BlackGuard = DDL_BlackGuard.SelectedValue;
            model.ContentPass = CB_ContentPass.Checked == true ? 1 : 0;
            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.AllowComment = CB_AllowComment.Checked == true ? 1 : 0;
            model.ColorStyle = TB_ColorStyle.Text.Trim();
            model.FontStyle = DDL_FontStyle.SelectedValue;
            model.IsSlide = CB_IsSlide.Checked == true ? 1 : 0;
            model.Gather = 0;
            model.TemplateFileName = TB_TemplateFileName.Text.Trim();

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

                int SoftID = new SoftManage(iModelID).Add(model, ref Err);
                if (string.IsNullOrEmpty(Err) == false)
                {
                    MsgBox.Alert(Err, this);
                    return;
                }

                string DownLoadServers = Request.Form["DownLoadServer"];
                string FileNames = Request.Form["FileName"];
                new SoftDownListManage().Add(DownLoadServers, FileNames, iModelID, SoftID);

                HttpContext.Current.Response.Redirect("../Common/SaveOK.aspx?ClassID=" + model.ClassID + "&ID=" + SoftID + "&SaveSoftName=" + model.SoftName + "&ModelID=" + iModelID);
            }
            else
            {
                model.ID = int.Parse(Request["ID"]);
                new SoftManage(iModelID).Add(model, ref Err);
                if (string.IsNullOrEmpty(Err) == false)
                {
                    MsgBox.Alert(Err, this);
                    return;
                }

                //如果有新添加的就被添加进数据库
                string DownLoadServers = Request.Form["DownLoadServer"];
                string FileNames = Request.Form["FileName"];
                if (FileNames.Length > 0)
                {
                    new SoftDownListManage().Add(DownLoadServers, FileNames, iModelID, int.Parse(Request["ID"]));
                }

                string DownLoadServers_Edit = Request.Form["DownLoadServer_Edit"];
                string FileNames_Edit = Request.Form["FileName_Edit"];
                string SoftDownListID = Request.Form["SoftDownListID"];
                if (FileNames_Edit.Length > 0)
                {
                    new SoftDownListManage().Edit(DownLoadServers_Edit, FileNames_Edit, SoftDownListID);
                }

                HttpContext.Current.Response.Redirect("../Common/SaveOK.aspx?ClassID=" + model.ClassID + "&ID=" + model.ID + "&SaveSoftName=" + model.SoftName + "&ModelID=" + iModelID);
            }

        }



        protected void FileUploader1_FileUploaded(object sender, CuteEditor.UploaderEventArgs args)
        {
            if (DDL_SoftClass.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_SoftClass.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 BT_CheckSoftName_Click(object sender, EventArgs e)
        {
            if (this.TB_SoftName.Text.Trim().Length == 0)
            {
                MsgBox.Alert("请先输入", UpdatePanel1);
                return;
            }

            SoftInfo model = new SoftInfo();
            model.SoftName = TB_SoftName.Text.Trim();


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


    }
}