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 webuploader : PageBase
    {
       
        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 sessionName
        {
            get
            {
                return (string)ViewState["sessionName"];
            }
            set
            {
                ViewState["sessionName"] = value;
            }
        }

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

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

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

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

                if (FileType == "1")
                {
                    sessionName = "AttachFile.webuploader1";
                }
                else if (FileType == "2")
                {
                    sessionName = "AttachFile.webuploader2";
                }
                else
                {
                    sessionName = "AttachFile.webuploader3";
                }

                ParamStr = sessionName + "|" + AttachPath;

                Session["AttachFile.webuploader1"] = null;
                Session["AttachFile.webuploader2"] = null;
                Session["AttachFile.webuploader3"] = null;

                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")
            {
                if (Request.QueryString["edit"] == "1")
                {
                    DeleteRow(e.RowID);
                    BindGrid();
                }
                else
                {
                    ShowNotify("您没有删除附件权限,请与管理员联系!");
                }
            }

            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.ToKeyId = ToKeyId;
                att.AttachSource = source.ToString();
                att.AttachUrl = attachUrl;
                att.MenuId = MenuId;
                BLL.AttachFileService.AddAttachFile(att);
            }
            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;
                    BLL.AttachFileService.updateAttachFile(att);
                }
            }

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

        #region 获取权限按钮
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private void GetButtonPower(string isEnabelEdit)
        {
            if (isEnabelEdit == "1")
            {
                toolBar1.Hidden = false;
            }
            else
            {
                toolBar1.Hidden = true;
            }
        }
        #endregion

        protected void btnChange_Click(object sender, EventArgs e)
        {
            //var law = from x in Funs.DB.Common_LawRegulation select x;
            //foreach (var q in law)
            //{
            //    InsertAttachFile(q.LawRegulationId, q.AttachUrl, "96DE448F-0629-40BC-2222-3E79686D3343");
            //}

            //var co = from x in Funs.DB.Common_ConstructionStandardList select x;
            //foreach (var q in co)
            //{
            //    InsertAttachFile(q.StandardId, q.AttachUrl, "46EE9F79-64CF-4BF4-2222-67E73B1ECB2F");
            //}

            //var edu = from x in Funs.DB.HSSE_Train_EduTrainType select x;
            //foreach (var q in edu)
            //{
            //    InsertAttachFile(q.EduTrainTypeCode, q.AttachUrl, "9D99A981-7380-4085-3333-8C3B1AFA6202");
            //}
        }

        #region 多附件转化方法
        /// <summary>
        /// 多附件转化方法
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="attachUrl"></param>
        private void InsertAttachFile(string ID, string attachUrl, string menuId)
        {
            if (!string.IsNullOrEmpty(attachUrl))
            {
                var att = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == ID);
                if (att == null)
                {
                    Model.AttachFile newAttachFile = new Model.AttachFile();
                    newAttachFile.AttachFileId = SQLHelper.GetNewID(typeof(Model.AttachFile));
                    newAttachFile.ToKeyId = ID;
                    string attachSource = string.Empty;

                    int strInt = attachUrl.LastIndexOf("~");
                    if (strInt < 0)
                    {
                        strInt = attachUrl.LastIndexOf("\\");
                    }
                    string name = attachUrl.Substring(strInt + 1);
                    string type = attachUrl.Substring(attachUrl.LastIndexOf(".") + 1);
                    string savedName = attachUrl.Substring(attachUrl.LastIndexOf("\\") + 1);

                    string id = SQLHelper.GetNewID(typeof(Model.AttachFile));
                    attachSource = "[  {    \"name\": \"" + name + "\",    \"type\": \"" + type + "\",    \"savedName\": \"" + savedName
                        + "\",    \"size\": 100,    \"id\": \"" + SQLHelper.GetNewID(typeof(Model.AttachFile)) + "\"  }]";
                    newAttachFile.AttachSource = attachSource;
                    if (menuId == "9D99A981-7380-4085-3333-8C3B1AFA6202")
                    {
                        newAttachFile.AttachUrl = attachUrl.Replace("\\File\\", "FileUpload\\HSSE\\");
                    }
                    else
                    {
                        newAttachFile.AttachUrl = attachUrl.Replace("\\Law\\", "\\Common\\");
                    }
                    newAttachFile.MenuId = menuId;
                    Funs.DB.AttachFile.InsertOnSubmit(newAttachFile);
                    Funs.DB.SubmitChanges();
                }
                else
                {
                    if (string.IsNullOrEmpty(att.MenuId))
                    {
                        att.MenuId = menuId;
                        Funs.DB.SubmitChanges();
                    }
                }
            }
        }
        #endregion


    }
}