using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace RFrameGenerate.Common
{
    public static class UpLoadFileHelp
    {
        /// <summary>
        /// 上传的路径
        /// </summary>
        public static string UpLoadFilePathDir { get; set; }
        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;
        }

        /// <summary>
        /// 验证文件类型
        /// </summary>
        /// <param name="file">上传上来的文件</param>
        /// <returns></returns>
        public static Boolean IsAllowedExtension(this HttpPostedFileBase file)
        {
            int fileLen = file.ContentLength;
            byte[] imgArray = new byte[fileLen];
            file.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
            }
            finally
            {
                br.Close();
                ms.Close();
            }
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
                return true;
            else
                return false;
        }

        /// <summary>
        /// 将文件保存文件夹
        /// </summary>
        /// <param name="file"></param>
        /// <param name="savePath"></param>
        /// <param name="IsSafe"></param>
        /// <param name="isimglimitzip">极限压缩</param>
        /// <returns></returns>
        public static void SaveInFileSystem(this HttpPostedFileBase file, string savePath, string _fileName, bool IsSafe = false, bool isimglimitzip = false)
        {


            //if (!UpLoadFileHelp.IsAllowedExtension(file))
            //{
            //    throw new Exception("文件格式不正确");
            //}
            string fileName = Path.GetFileName(file.FileName);
            if (!string.IsNullOrEmpty(_fileName))
            {
                fileName = _fileName;
            }

            if (!System.IO.Directory.Exists(savePath))      //检测文件夹是否存在，不存在则创建
            {
                System.IO.Directory.CreateDirectory(savePath);
            }

            string ext = Path.GetExtension(file.FileName).ToLower();
            if (ext.ToLower() == ".jpg" || ext.ToLower() == ".gif" || ext.ToLower() == ".png" || ext.ToLower() == ".jpeg" || ext.ToLower() == ".bmp")
            {
                Image image = Image.FromStream(file.InputStream);

                try
                {
                    bool result = false;
                    string fileNameExt = Path.GetExtension(file.FileName).ToLower();
                    if (fileNameExt == ".jpg" || fileNameExt == ".jpeg")
                    {
                        if (isimglimitzip == true && image.Width >= 400)
                        {
                            int width = 400;
                            int height = (image.Height * width) / image.Width;
                            result = Thumbnail.GetPicThumbnail((Image)image.Clone(), Path.Combine(savePath, fileName), height, width, 50);
                        }
                        else
                            result = Thumbnail.GetPicThumbnail((Image)image.Clone(), Path.Combine(savePath, fileName), image.Height, image.Width, 60);
                    }
                    else if (fileNameExt == ".gif")
                    {
                        image.Save(Path.Combine(savePath, fileName));
                    }
                    else
                    {
                        if (isimglimitzip == true && image.Width >= 400)
                        {
                            int width = 400;
                            int height = (image.Height * width) / image.Width;
                            result = Thumbnail.GetPicThumbnail((Image)image.Clone(), Path.Combine(savePath, fileName), image.Height, image.Width, 50);
                        }
                        else
                            result = Thumbnail.GetPicThumbnail((Image)image.Clone(), Path.Combine(savePath, fileName), image.Height, image.Width, 80);
                    }

                    if (result == true)
                    {
                        image.Dispose();
                        return;
                    }
                }
                catch { }

                image.Dispose();
            }
            else
            {
                if (IsSafe)
                {
                    file.SaveAs(Path.Combine(savePath, "%%" + fileName));
                }
                else
                {
                    file.SaveAs(Path.Combine(savePath, fileName));
                }
            }
        }

        public static bool IsLegalFile(string ext, string typeName)
        {
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");


            return Array.IndexOf(((String)extTable[typeName]).Split(','), ext) == -1;


        }

    }
}
