using FineUIPro;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
namespace BLL
{
    public static class AttachFileService
    {
        public static Model.SGGLDB db = Funs.DB;
        /// 
        /// 添加附件存储信息
        /// 
        /// 
        public static void AddAttachFile(Model.AttachFile attachFile)
        {
            string newKeyID = SQLHelper.GetNewID(typeof(Model.AttachFile));
            Model.AttachFile newAttachFile = new Model.AttachFile();
            newAttachFile.AttachFileId = newKeyID;
            newAttachFile.ToKeyId = attachFile.ToKeyId;
            newAttachFile.AttachSource = attachFile.AttachSource;
            newAttachFile.AttachUrl = attachFile.AttachUrl;
            newAttachFile.MenuId = attachFile.MenuId;
            db.AttachFile.InsertOnSubmit(newAttachFile);
            db.SubmitChanges();
        }
        /// 
        /// 修改附件存储信息
        /// 
        /// 
        public static void updateAttachFile(Model.AttachFile attachFile)
        {
            Model.AttachFile newAttachFile = db.AttachFile.FirstOrDefault(x => x.AttachFileId == attachFile.AttachFileId);
            newAttachFile.ToKeyId = attachFile.ToKeyId;
            newAttachFile.AttachSource = attachFile.AttachSource;
            newAttachFile.AttachUrl = attachFile.AttachUrl;
            newAttachFile.MenuId = attachFile.MenuId;
            db.SubmitChanges();
        }
        /// 
        /// 根据对应Id删除附件信息及文件存放的物理位置
        /// 
        /// 
        public static void DeleteAttachFile(string rootPath, string toKeyId, string menuId)
        {
            Model.AttachFile att = db.AttachFile.FirstOrDefault(e => e.ToKeyId == toKeyId && e.MenuId == menuId);
            if (att != null)
            {
                BLL.UploadFileService.DeleteFile(rootPath, att.AttachUrl);
                db.AttachFile.DeleteOnSubmit(att);
                db.SubmitChanges();
            }
        }
        /// 
        /// 根据对应主键和菜单获取文件信息
        /// 
        /// 对应主键
        /// 对应菜单
        /// 文件信息
        public static Model.AttachFile GetAttachFile(string toKey, string menuId)
        {
            return Funs.DB.AttachFile.FirstOrDefault(e => e.ToKeyId == toKey && e.MenuId == menuId);
        }
        /// 
        /// 根据对应主键获取文件信息
        /// 
        /// 对应主键
        /// 文件信息
        public static string GetBtnFileUrl(object toKey)
        {
            string fileUrl = string.Empty;
            if (toKey != null)
            {
                Model.AttachFile file = Funs.DB.AttachFile.FirstOrDefault(e => e.ToKeyId == toKey.ToString());
                if (file != null && !string.IsNullOrEmpty(file.AttachUrl))
                {
                    string url = file.AttachUrl.Replace('\\', '/');
                    fileUrl = BLL.UploadAttachmentService.ShowAttachment2("../../", url);
                  
                }
            }
            return fileUrl;
        }
        /// 
        /// 根据对应主键和菜单获取文件信息
        /// 
        /// 对应主键
        /// 对应菜单
        /// 文件信息
        public static Model.AttachFile GetAttachFileByToKeyId(string toKey)
        {
            return Funs.DB.AttachFile.FirstOrDefault(e => e.ToKeyId == toKey);
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string getFileUrl(string toKeyId)
        {
            try
            {
                using (var db = new Model.SGGLDB(Funs.ConnString))
                {
                    string res = "";
                    var list = db.AttachFile.Where(p => p.ToKeyId == toKeyId).ToList();
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            if (!string.IsNullOrEmpty(item.AttachUrl))
                                res += item.AttachUrl.ToLower().TrimEnd(',') + ",";
                        }
                        res = res.Substring(0, res.Length - 1);
                    }
                    return res.Replace('\\', '/');
                }
            }
            catch (Exception e)
            {
                return "";
            }
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Boolean Getfile(string toKeyId, string menuId)
        {
            bool res = false;
            var q = Funs.DB.AttachFile.FirstOrDefault((x => x.ToKeyId == toKeyId && x.MenuId == menuId));
            if (q != null)
            {
                var file = q.AttachUrl;
                if (!string.IsNullOrEmpty(file))
                {
                    res = true;
                }
            }
            return res;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IList Getfilelist(string toKeyId, string menuId)
        {
            List listToKeyId = new List();
            listToKeyId.Add(toKeyId);
            listToKeyId.Add(toKeyId + "r");
            listToKeyId.Add(toKeyId + "re");
            listToKeyId.Add(toKeyId + "_1");
            listToKeyId.Add(toKeyId + "_2");
            listToKeyId.Add(toKeyId + "_3");
            listToKeyId.Add(toKeyId + "_4");
            listToKeyId.Add(toKeyId + "_5");
            listToKeyId.Add(toKeyId + "_6");
            var list = Funs.DB.AttachFile.Where(p => listToKeyId.Contains(p.ToKeyId) && p.MenuId == menuId).ToList();
            return list;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static bool updateAttachFile(string url, string toKeyId, string menuId)
        {
            if (!string.IsNullOrEmpty(url))
            {
                string fileDir = "WebApi";
                switch (menuId)
                {
                    case Const.CheckEquipmentMenuId:
                        fileDir = "CheckEquipment";
                        break;
                    case Const.CheckListMenuId:
                        fileDir = "CheckControl";
                        break;
                    case Const.JointCheckMenuId:
                        fileDir = "JointCheck";
                        break;
                    case Const.TechnicalContactListMenuId:
                        fileDir = "TechnicalContactList";
                        break;
                    case Const.WorkContactMenuId:
                        fileDir = "WorkContact";
                        break;
                    case Const.DesignMenuId:
                        fileDir = "Design";
                        break;
                    case Const.CQMSConstructSolutionMenuId:
                        fileDir = "Solution";
                        break;
                }
                using (var db = new Model.SGGLDB(Funs.ConnString))
                {
                    var query = from f in db.AttachFile
                                where f.ToKeyId == toKeyId
                                select f;
                    Model.AttachFile temp = query.FirstOrDefault();
                    if (temp == null)
                    {
                        temp = new Model.AttachFile();
                        temp.AttachFileId = BLL.SQLHelper.GetNewID(typeof(Model.AttachFile));
                        temp.ToKeyId = toKeyId;
                        temp.AttachUrl = reNameUrl(url, fileDir);
                        temp.AttachSource = getAttachSource(url, fileDir);
                        temp.MenuId = menuId;
                        db.AttachFile.InsertOnSubmit(temp);
                        db.SubmitChanges();
                    }
                    else
                    {
                        temp.AttachUrl = reNameUrl(url, fileDir);
                        temp.AttachSource = getAttachSource(url, fileDir);
                        db.SubmitChanges();
                    }
                    return true;
                }
            }
            else
            {
                using (var db = new Model.SGGLDB(Funs.ConnString))
                {
                    var query = from f in db.AttachFile
                                where f.ToKeyId == toKeyId
                                select f;
                    Model.AttachFile temp = query.FirstOrDefault();
                    if (temp != null)
                    {
                        db.AttachFile.DeleteOnSubmit(temp);
                        db.SubmitChanges();
                    }
                    return true;
                }
            }
            return false;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string reNameUrl(string url, string fileDir)
        {
            string[] urls = url.Split(',');
            string res = "";
            foreach (var item in urls)
            {
                string size = "0";
                int strInt = item.LastIndexOf("~");
                if (strInt < 0)
                {
                    strInt = item.LastIndexOf("\\");
                }
                if (strInt < 0)
                {
                    strInt = item.LastIndexOf("/");
                }
                res += "FileUpLoad/" + fileDir + "/" + item.Substring(strInt + 1) + ",";
            }
            if (!string.IsNullOrEmpty(res))
                return res.Substring(0, res.Length - 1);
            return res;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string getAttachSource(string url, string fileDir)
        {
            string res = "";
            string attachSource = string.Empty;
            if (!string.IsNullOrEmpty(url))
            {
                string[] urls = url.Split(',');
                foreach (var item in urls)
                {
                    string size = "0";
                    int strInt = item.LastIndexOf("~");
                    if (strInt < 0)
                    {
                        strInt = item.LastIndexOf("\\");
                    }
                    if (strInt < 0)
                    {
                        strInt = item.LastIndexOf("/");
                    }
                    string filepath = ConfigurationManager.AppSettings["localRoot"] + "/FileUpLoad/" + fileDir + "/" + item.Substring(strInt + 1);
                    strInt = filepath.LastIndexOf("~");
                    if (strInt < 0)
                    {
                        strInt = filepath.LastIndexOf("\\");
                    }
                    if (strInt < 0)
                    {
                        strInt = filepath.LastIndexOf("/");
                    }
                    if (File.Exists(ConfigurationManager.AppSettings["localRoot"] + "/" + item))
                    {
                        if (!Directory.Exists(filepath.Substring(0, strInt)))
                        {
                            Directory.CreateDirectory(filepath.Substring(0, strInt));
                        }
                        if (!File.Exists(filepath))
                        {
                            File.Copy(ConfigurationManager.AppSettings["localRoot"] + "/" + item, filepath);
                        }
                        FileInfo fileInfo = new System.IO.FileInfo(filepath);
                        size = System.Math.Ceiling(fileInfo.Length / 1024.0) + "";
                    }
                    string name = filepath.Substring(strInt + 1);
                    string type = filepath.Substring(filepath.LastIndexOf(".") + 1);
                    string id = SQLHelper.GetNewID(typeof(Model.AttachFile));
                    attachSource += "{    \"name\": \"" + name + "\",    \"type\": \"" + type + "\",    \"savedName\": \"" + name
                        + "\",    \"size\": " + size + ",    \"id\": \"" + SQLHelper.GetNewID(typeof(Model.AttachFile)) + "\"  },";
                }
            }
            if (!string.IsNullOrEmpty(attachSource))
            {
                attachSource = attachSource.Substring(0, attachSource.Length - 1);
            }
            return "[" + attachSource + "]";
        }
        /// 
        /// 根据id获取url地址
        /// 
        /// 
        /// 
        public static string GetfileUrl(string toKeyId)
        {
            try
            {
                string file = string.Empty;
                var result = Funs.DB.AttachFile.FirstOrDefault((x => x.ToKeyId == toKeyId && x.MenuId == Const.UserMenuId));
                if (result != null && !string.IsNullOrEmpty(result.AttachUrl))
                {
                    file = result.AttachUrl.ToLower();
                    file = file.Replace('\\', '/').TrimEnd(',');
                }
                return file;
            }
            catch (Exception e)
            {
                return "";
            }
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static Model.AttachFile Getfiles(string toKeyId, string menuId)
        {
            var list = Funs.DB.AttachFile.FirstOrDefault((x => x.ToKeyId == toKeyId && x.MenuId == menuId));
            return list;
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IList GetfileDetaillist(List toKeyId, string menuId)
        {
            if (toKeyId.Count > 0)
            {
                var list = Funs.DB.AttachFile.Where(p => toKeyId.Contains(p.ToKeyId) && p.MenuId == menuId).ToList();
                return list;
            }
            else
            {
                return null;
            }
        }
        #region 根据图片路径转换为base64
        /// 
        /// 根据图片路径转换为base64
        /// 
        /// 
        /// 
        public static byte[] SetImageToByteArray(string imageUrl)
        {
            try
            {
                FileStream fs = new FileStream(imageUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                int streamLength = (int)fs.Length;
                byte[] image = new byte[streamLength];
                fs.Read(image, 0, streamLength);
                fs.Close();
                return image;
            }
            catch
            {
                return null;
            }
        }
        #endregion
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string Base64ToImage(string base64Str, string path, string imgName)
        {
            string filename = "";//声明一个string类型的相对路径
            String base64 = base64Str.Substring(base64Str.IndexOf(",") + 1);      //将‘,’以前的多余字符串删除
            System.Drawing.Bitmap bitmap = null;//定义一个Bitmap对象,接收转换完成的图片
            try//会有异常抛出,try,catch一下
            {
                byte[] arr = Convert.FromBase64String(base64);//将纯净资源Base64转换成等效的8位无符号整形数组
                System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);//转换成无法调整大小的MemoryStream对象
                bitmap = new System.Drawing.Bitmap(ms);//将MemoryStream对象转换成Bitmap对象
                filename = path + imgName + ".jpg";//所要保存的相对路径及名字
                string url = ConfigurationManager.AppSettings["localRoot"];
                string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录 
                string imagesurl2 = tmpRootDir + filename; //转换成绝对路径 
                bitmap.Save(imagesurl2, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到服务器路径
                //bitmap.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                //bitmap.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                //bitmap.Save(filePath + ".png", System.Drawing.Imaging.ImageFormat.Png);
                ms.Close();//关闭当前流,并释放所有与之关联的资源
                bitmap.Dispose();
            }
            catch (Exception e)
            {
                string massage = e.Message;
            }
            return filename;//返回相对路径
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IList GetBeforeFileList(string toKeyId, string menuId)
        {
            List listToKeyId = new List();
            listToKeyId.Add(toKeyId);
            // listToKeyId.Add(toKeyId + "r");
            //listToKeyId.Add(toKeyId + "re");
            var list = Funs.DB.AttachFile.Where(p => listToKeyId.Contains(p.ToKeyId) && p.MenuId == menuId).ToList();
            return list;
        }
        /// 
        /// 判断文件类型是否支持的预览
        /// 
        /// 
        /// 
        public static bool IsSupportFileType(string FiletExtension)
        {
            bool result = false;
            List list = new List();
            list.Add(".doc");
            list.Add(".docx");
            list.Add(".pdf");
            list.Add(".txt");
            list.Add(".xlsx");
            list.Add(".xls");
            list.Add(".png");
            list.Add(".jpg");
            list.Add(".jpeg");
            foreach (var item in list)
            {
                if (item == FiletExtension)
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        /// 
        /// 判断文件类型是否是图片
        /// 
        /// 
        /// 
        public static bool IsImage(string FiletExtension)
        {
            bool result = false;
            List list = new List();
            list.Add(".png");
            list.Add(".jpg");
            list.Add(".jpeg");
            foreach (var item in list)
            {
                if (item == FiletExtension)
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        /// 
        /// 获取附件数据流类 多附件的情况
        /// 
        /// 附件路径
        /// 
        public static List GetMoreFileStructByAttachUrl(string attachUrl)
        {
            List fileContext = new List();
            try
            {
                if (!String.IsNullOrEmpty(attachUrl))
                {
                    string physicalpath = ConfigurationManager.AppSettings["localRoot"];
                    string filePath = string.Empty;
                    string[] strs = attachUrl.Trim().Split(',');
                    foreach (var item in strs)
                    {
                        //HttpContext.Current.Request.PhysicalApplicationPath;    
                        filePath = physicalpath + item;
                        if (File.Exists(filePath))
                        {
                            fileContext.Add(fileConvertByte(item));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
            return fileContext;
        }
        #region 附件转换二进制数据(用于保存数据库)
        /// 
        /// 附件转换二进制数据(用于保存数据库)
        /// 
        /// 附件路径
        /// 二进制
        public static byte[] fileConvertByte(string filePath)
        {
            string physicalpath = (ConfigurationManager.AppSettings["localRoot"] + "\\" + filePath).Replace("\\\\", "\\");
            byte[] bytContent = null;
            System.IO.FileStream fs = null;
            System.IO.BinaryReader br = null;
            try
            {
                fs = new FileStream(physicalpath, System.IO.FileMode.Open);
            }
            catch
            {
            }
            br = new BinaryReader((Stream)fs);
            bytContent = br.ReadBytes((Int32)fs.Length);
            fs.Dispose();
            return bytContent;
        }
        #endregion
    }
}