using BLL;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FineUIPro.Web.SupportDocument
{
    public partial class GuideManual : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();//按钮权限
                BindGrid();

            }
        }

        private void BindGrid()
        {
            string strSql = @"SELECT t.GuideManualId, 
                                     t.GuideManual, 
                                     t.UploadBy, 
                                     t.UploadDate,
                                     t.AttachUrl,
                                     U.UserName AS UploadByName
                                FROM dbo.SupportDocument_GuideManual AS t
                                LEFT JOIN Sys_User AS U ON U.UserId = t.UploadBy
                                WHERE 1=1 ";

            List<SqlParameter> listStr = new List<SqlParameter>();
            //if (tvStandardTemp.SelectedNodeID != "0" && tvStandardTemp.SelectedNodeID != null)
            //{
            //    strSql += " AND t.TemplateTypeId = @TemplateTypeId";
            //    listStr.Add(new SqlParameter("@TemplateTypeId", tvStandardTemp.SelectedNodeID));
            //}
            strSql += " ORDER BY t.UploadDate DESC";
            SqlParameter[] parameter = listStr.ToArray();

            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();

            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                System.Web.UI.WebControls.LinkButton lbtnUrl = ((System.Web.UI.WebControls.LinkButton)(this.Grid1.Rows[i].FindControl("lbtnUrl1")));
                string url = lbtnUrl.CommandArgument.ToString();
                if (!string.IsNullOrEmpty(url))
                {
                    url = url.Replace('\\', '/');
                    lbtnUrl.Text = BLL.UploadAttachmentService.ShowAttachment("../", url);
                }
            }
        }

        //protected void btnSearch_Click(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrEmpty(this.tvStandardTemp.SelectedNodeID))
        //    {
        //        BindGrid(this.tvStandardTemp.SelectedNodeID);
        //    }
        //}
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string id = SQLHelper.GetNewID(typeof(Model.SupportDocument_GuideManual));
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=add&toKeyId={0}&path=FileUpload/SupportDocument/GuideManual&menuId={1}", id, BLL.Const.GuideManualMenuId)));
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            string rowId = Grid1.SelectedRowID;
            if (!string.IsNullOrEmpty(rowId))
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=edit&toKeyId={0}&path=FileUpload/SupportDocument/GuideManual&menuId={1}", rowId, BLL.Const.GuideManualMenuId)));
            }
            else
            {
                Alert.ShowInTop("Please select the record to modify!", MessageBoxIcon.Warning);
                return;
            }
            //PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("StandardTemplateEdit.aspx?templateId={0}", rowId, "编辑 - ")));
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var t = BLL.GuideManualService.GetGuideManualById(rowID);
                    if (t != null)
                    {
                        BLL.GuideManualService.DeleteGuideManualById(rowID);
                    }
                }
                BindGrid();
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete Guide Manual");
                ShowNotify("Deleted successfully!");
            }
            else
            {
                Alert.ShowInTop("Please select the record to Delete!", MessageBoxIcon.Warning);
                return;
            }
        }


        protected void Grid1_RowDoubleClick(object sender, EventArgs e)
        {
            string rowId = Grid1.SelectedRowID;
            if (!string.IsNullOrEmpty(rowId))
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=edit&toKeyId={0}&path=FileUpload/SupportDocument/GuideManual&menuId={1}", rowId, BLL.Const.GuideManualMenuId)));
            }
            else
            {
                Alert.ShowInTop("Please select the record to modify!", MessageBoxIcon.Warning);
                return;
            }
            //PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("StandardTemplateEdit.aspx?templateId={0}", rowId, "编辑 - ")));
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        /// <summary>
        /// 分页显示条数下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }

        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.GuideManualMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDownload))
                {
                    this.btnBatchDownload.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                }
            }
        }
        #endregion

        protected void btnBatchDownload_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/").Replace('\\', '/');
            if (Grid1.SelectedRowIDArray.Count() == 0)
            {
                Alert.ShowInParent("Please select Download Row!");
                return;
            }
            else
            {
                string[] rowList = Grid1.SelectedRowIDArray;
                List<string> durl = new List<string>();
                List<string> urlList = (from x in Funs.DB.SupportDocument_GuideManual where rowList.Contains(x.GuideManualId) && x.AttachUrl != null && x.AttachUrl != "" select x.AttachUrl).ToList();
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                string destFile = rootPath + "FileUpload\\Temp\\GuideManual" + date;
                string zipFileName = "GuideManual_" + date;
                if (!Directory.Exists(destFile))
                {
                    Directory.CreateDirectory(destFile);
                }

                foreach (string url in urlList)
                {
                    string sourceFileName = rootPath + url.Replace('\\', '/');
                    string[] subUrl = sourceFileName.Split('/');
                    string fileName = subUrl[subUrl.Count() - 1];


                    string newFileName = fileName.Substring(fileName.IndexOf("~") + 1);
                    if (newFileName.Contains("_"))
                    {
                        if (newFileName.Substring(0, 1) == "_")
                        {
                            newFileName = newFileName.Substring(1, newFileName.Length - 1);
                        }
                        else
                        {
                            newFileName = newFileName.Replace(newFileName.Split('_')[0], "");
                            newFileName = newFileName.Substring(1);
                        }
                    }
                    string destFileName = destFile + "/" + newFileName;
                    if (File.Exists(sourceFileName))
                    {
                        File.Copy(sourceFileName, destFileName, true);
                    }
                }
                FileZipDownload(destFile.Replace('\\', '/'), zipFileName);
            }
        }

        public string DownloadFileByHttpUrl(List<string> HttpUrlList)
        {
            if (HttpUrlList == null || HttpUrlList.Count == 0)
            {
                return "没有附件";
            }
            try
            {
                var random = new Random();
                var zipMs = new MemoryStream();
                ZipOutputStream zipStream = new ZipOutputStream(zipMs);
                zipStream.SetLevel(6);//压缩率0~9
                foreach (var url in HttpUrlList)
                {
                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        string rootPath = System.Configuration.ConfigurationManager.AppSettings["RootUrl"];
                        string surl = rootPath + url.Replace('\\', '/');
                        var urlStr = HttpUtility.UrlDecode(surl);
                        Console.WriteLine(urlStr);
                        string fileExt = Path.GetExtension(urlStr).ToLower();
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(urlStr);
                        var strName = fileNameWithoutExtension.Substring(fileNameWithoutExtension.LastIndexOf("/") + 1) + random.Next(1000, 9999) + fileExt;
                        zipStream.PutNextEntry(new ZipEntry(strName));
                        ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
                        ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlStr);
                        request.AllowAutoRedirect = true;
                        WebProxy proxy = new WebProxy();
                        proxy.BypassProxyOnLocal = true;
                        proxy.UseDefaultCredentials = true;
                        request.Proxy = proxy;
                        WebResponse response = request.GetResponse();
                        using (Stream streams = response.GetResponseStream())
                        {
                            Byte[] buffer = new Byte[1024];
                            int current = 0;
                            while ((current = streams.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                zipStream.Write(buffer, 0, current);
                            }
                            zipStream.Flush();
                        }
                    }
                }
                zipStream.Finish();
                zipMs.Position = 0;
                //下边为打包压缩
                MemoryStream stream = zipMs;
                byte[] srcBuf = new Byte[stream.Length];
                stream.Read(srcBuf, 0, srcBuf.Length);
                stream.Seek(0, SeekOrigin.Begin);

                string filePath = "C:/DownLoad";//Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                string con = "GuideManual";


                var file_name = con + "_" + date + ".zip";
                using (FileStream fs = new FileStream(filePath + "\\" + file_name, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(srcBuf, 0, srcBuf.Length);
                    fs.Close();
                    return "已下载到C盘Download文件下!";
                }
            }
            catch (Exception ex)
            {
                return "下载失败:" + ex.ToString();
            }
        }

        private void FileZipDownload(string destFilePath, string zipFileName)
        {
            string zipFilePath = destFilePath + ".zip";
            System.IO.Compression.ZipFile.CreateFromDirectory(destFilePath, zipFilePath);
            FileInfo info = new FileInfo(zipFilePath);
            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(zipFileName + ".zip", System.Text.Encoding.UTF8));
            System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
            System.Web.HttpContext.Current.Response.TransmitFile(zipFilePath, 0, fileSize);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.Close();
            Funs.DeleteDir(destFilePath);
            File.Delete(zipFilePath);
        }
    }
}