using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace FineUIPro.Web.AttachFile
{
    public partial class webuploader2 : PageBase
    {
        private static readonly string sessionName = "AttachFile.webuploader";
        protected string ParamStr;

        public string ToKeyId
        {
            get
            {
                return (string)ViewState["ToKeyId"];
            }
            set
            {
                ViewState["ToKeyId"] = value;
            }
        }

        public string AttachPath
        {
            get
            {
                return (string)ViewState["AttachPath"];
            }
            set
            {
                ViewState["AttachPath"] = value;
            }
        }

        public string MenuId
        {
            get
            {
                return (string)ViewState["MenuId"];
            }
            set
            {
                ViewState["MenuId"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 删除选中行
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项!");
                btnDelete.ConfirmText = String.Format("你确定要删除选中的&nbsp;<b><script>{0}</script></b>&nbsp;个文件吗?", Grid1.GetSelectedCountReference());
                
                Session[sessionName] = null;
                ToKeyId = Request.QueryString["toKeyId"];
                AttachPath = Request.QueryString["path"];
                ParamStr = sessionName + "|" + AttachPath;
                MenuId = Request.QueryString["menuId"];
                BindGrid();
            }
            else
            {
                if (GetRequestEventArgument() == "RebindGrid")
                {
                    BindGrid();
                }
            }
        }

        #region BindGrid

        private void BindGrid()
        {
            Grid1.DataSource = GetSourceData();
            Grid1.DataBind();
        }

        #endregion

        #region Events

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (string rowId in Grid1.SelectedRowIDArray)
            {
                DeleteRow(rowId);
            }

            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                DeleteRow(e.RowID);

                BindGrid();
            }

            if (e.CommandName == "Attach")
            {
                JArray source = GetSourceData();

                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;

                    if (item.Value<string>("id") == e.RowID)
                    {

                        try
                        {
                            string savedName = item.Value<string>("savedName");

                            string url = BLL.Funs.RootPath + AttachPath + "\\" + savedName;
                            FileInfo info = new FileInfo(url);
                            if (!info.Exists || string.IsNullOrEmpty(savedName))
                            {
                                url = BLL.Funs.RootPath + "Images//Null.jpg";
                                info = new FileInfo(url);
                            }

                            string fileName = Path.GetFileName(url);
                            long fileSize = info.Length;
                            System.Web.HttpContext.Current.Response.Clear();
                            System.Web.HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                            System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
                            System.Web.HttpContext.Current.Response.TransmitFile(url, 0, fileSize);
                            System.Web.HttpContext.Current.Response.Flush();
                            System.Web.HttpContext.Current.Response.Close();
                            
                        }
                        catch (Exception)
                        {
                           
                        }
                    }
                }

               
            }
        }
        #endregion

        #region GetSourceData

        private JArray GetSourceData()
        {
            
            if (Session[sessionName] == null)
            {
                var sour = from x in BLL.Funs.DB.AttachFile where x.ToKeyId == ToKeyId select x;

                if (sour.Count() > 0)
                {
                    Session[sessionName] = JArray.Parse(sour.First().AttachSource);
                }
                else
                {
                    Session[sessionName] = new JArray();
                }
            }

            return (JArray)Session[sessionName];
        }

        private void DeleteRow(string rowId)
        {
            JArray source = GetSourceData();

            for (int i = 0, count = source.Count; i < count; i++)
            {
                JObject item = source[i] as JObject;

                if (item.Value<string>("id") == rowId)
                {

                    try
                    {
                        string savedName = item.Value<string>("savedName");
                        System.IO.File.Delete(Server.MapPath("~/" + AttachPath + "\\" + savedName));
                    }
                    catch (Exception)
                    {
                        // 尝试删除物理文件失败,不做处理
                    }

                    source.RemoveAt(i);
                    break;
                }
            }

             Session[sessionName] = source;
        }

        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Model.EProjectDB db = Funs.DB;
            JArray source = GetSourceData();
            string attachUrl = string.Empty;
            for (int i = 0, count = source.Count; i < count; i++)
            {
                JObject item = source[i] as JObject;
                attachUrl += AttachPath + "\\" + item.Value<string>("savedName") + ",";
            }

            if (!string.IsNullOrEmpty(attachUrl))
            {
                attachUrl = attachUrl.Replace('/', '\\');
                attachUrl = attachUrl.Substring(0, attachUrl.LastIndexOf(","));
            }            
            var sour = from x in db.AttachFile where x.ToKeyId == ToKeyId select x;
            if (sour.Count() == 0)
            {
               
                Model.AttachFile att = new Model.AttachFile();
                att.AttachFileId = BLL.SQLHelper.GetNewID(typeof(Model.AttachFile));
                att.ToKeyId = ToKeyId;
                att.AttachSource = source.ToString();
                att.AttachUrl = attachUrl;
                att.MenuId = MenuId;
                db.AttachFile.InsertOnSubmit(att);
                db.SubmitChanges();
            }
            else
            {
                Model.AttachFile att = db.AttachFile.FirstOrDefault(x => x.AttachFileId == sour.First().AttachFileId);
                if (att != null)
                {
                    att.ToKeyId = ToKeyId;
                    att.AttachSource = source.ToString();
                    att.AttachUrl = attachUrl;
                    att.MenuId = MenuId;
                    db.SubmitChanges();
                }
            }

            ShowNotify("保存成功!");
        }

        #region 获取权限按钮
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private void GetButtonPower()
        {
            //var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, MenuId);
            //if (buttonList.Count > 0)
            //{
            //    if (!buttonList.Contains(BLL.Const.BtnSave))
            //    {
            //        this.btnSelectFiles.Hidden = true;
            //        this.btnDelete.Hidden = true;
            //        this.btnSave.Hidden = true;
            //    }                              
            //}
        }
        #endregion

    }
}