using APT.BaseData.Domain.Entities;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http.Features;
using APT.Infrastructure.Api;
using System.Dynamic;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.ApiModel.OP;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using System.ComponentModel;
using System.Net.Http;
using System.Net;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Ubiety.Dns.Core;

namespace APT.PF.WebApiControllers.Api.PF
{
    /// <summary>
    /// 文件
    /// </summary>
    [Route("api/PF/File")]
    public class FileController : APTApiController<T_PF_FILE>
    {


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_PF_FILE>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_PF_FILE>> OrderEntities([FromBody] KeywordFilter filter)
        {
            return WitOrderEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_FILE> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_FILE> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return WitDelete(id);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_PF_FILE entity)
        {
            return WitUpdate(entity);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return WitBatchDelete(ids);
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_PF_FILE> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }


        /// <summary>
        /// 上次文件
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[HttpPost, Route("UploadFile")]
        //public JsonActionResult<string> UploadFile()
        //{
        //    return SafeExecute<string>(() =>
        //    {
        //        string result = string.Empty;

        //        var httpRequest = HttpContext.Request;
        //        var orgId = httpRequest.Form["OrgId"];  // 获取 组织

        //        List<T_PF_FILE> fileList = new List<T_PF_FILE>();
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象

        //            T_PF_FILE file = new T_PF_FILE();
        //            file.ORG_ID = new Guid(orgId);
        //            file.FILE_NAME = postedFile.FileName;
        //            file.FILE_TYPE = postedFile.ContentType;
        //            Byte[] fileData = new Byte[postedFile.Length];
        //            Stream sr = postedFile.OpenReadStream();//创建数据流对象 
        //            sr.Read(fileData, 0, (int)postedFile.Length);
        //            file.FILE_DATA = fileData;
        //            fileList.Add(file);
        //            result = file.ID.ToString();
        //        }
        //        this.BantchAddEntity(fileList);
        //        return result;
        //    });
        //}

        [HttpGet, Route("GetFileFromWebApi")]
        public ActionResult GetFileFromWebApi(string strServerPath, string strfileName)
        {
            var httpRequest = HttpContext.Request;
            var strOrgId = httpRequest.Form["OrgId"][0];
            var orgId = new Guid(strOrgId);
            string filePath = GetFilePath(orgId);
            var fullFilePath = $"{ConfigurationManager.AppSettings["Img_Local"]}{filePath}";
            var host = ConfigurationManager.AppSettings["SapInvokeHost"];
            var url = host + fullFilePath + strServerPath;
            if (System.IO.File.Exists(url))
            {
                return File(new FileStream(url, FileMode.Open), "application/octet-stream", strfileName);
            }
            else
            {
                return Content("需要下载的文件已不存在！");
            }
        }
        /// <summary>
        /// 上次文件转为图片
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UploadFileToImage")]
        public JsonActionResult<dynamic> UploadFileToImage()
        {
            return SafeExecute<dynamic>(() =>
            {
                dynamic result = new ExpandoObject();

                var httpRequest = HttpContext.Request;
                var strOrgId = httpRequest.Form["OrgId"][0];  // 获取 组织
                var isSaveSelfStr = httpRequest.Form["IsSaveSelf"].Any() ? httpRequest.Form["IsSaveSelf"][0] : "false";  // 是否存储本身
                if (string.IsNullOrEmpty(strOrgId))
                    throw new Exception("组织不允许为空");
                var orgId = new Guid(strOrgId);
                //返回的文件地址
                List<string> filenames = new List<string>();
                var now = DateTime.Now;
                //文件存储路径
                //var filePath = string.Format("/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
                string filePath = GetFilePath(orgId);
                var fullFilePath = $"{ ConfigurationManager.AppSettings["Img_Local"]}{filePath}";
                //GetFilePath(fullFilePath);


                ImageConverterFactory imageConverterFactory = new ImageConverterFactory();
                var host = ConfigurationManager.AppSettings["SapInvokeHost"];

                List<T_PF_FILE> fileList = new List<T_PF_FILE>();
                List<T_PF_IMG_FILE> imgFileList = new List<T_PF_IMG_FILE>();
                List<T_PF_IMG_FILE_DETAIL> imgFileDetailList = new List<T_PF_IMG_FILE_DETAIL>();

                var files = httpRequest.Form.Files;

                if (!Directory.Exists(fullFilePath))
                {
                    Directory.CreateDirectory(fullFilePath);
                }
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);
                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据
                        using (FileStream fs = System.IO.File.Create(fullFilePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        filenames.Add(filePath + saveName);
                        string fileName = item.FileName;
                        var pos = fileName.LastIndexOf(".");
                        var extendName = fileName.Substring(pos);
                        List<ConvertImageFile> list = new List<ConvertImageFile>();
                        bool isSuppot = imageConverterFactory.Support(extendName);
                        bool isSaveSelf = true;

                        T_PF_IMG_FILE imgFile = new T_PF_IMG_FILE
                        {
                            FILE_NAME = fileName,
                            FILE_TYPE = item.ContentType,
                            ORG_ID = orgId
                        };

                        var inputStream = item.OpenReadStream();
                        //支持转换时，按类型转为图片，否则直接存储
                        if (isSuppot)
                        {
                            if (!string.IsNullOrEmpty(host))
                            {
                                ConvertImageFileParam param = new ConvertImageFileParam();
                                param.FileName = fileName;
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                param.FileData = fileData;
                                string url = host + "ImageConvert/ImageConvert";
                                ConvertImageFileParam retModel =
                                    WebUtils.Execute<ConvertImageFileParam>(url, param, string.Empty, SendType.Post);
                                if (retModel != null && retModel.Files != null && retModel.Files.Any())
                                    list.AddRange(retModel.Files);
                            }
                            else
                            {
                                var convert = imageConverterFactory.CreateImageConverter(fileName);
                                convert.ConvertToImage(fileName, inputStream, list);
                            }
                            if (isSaveSelf)//保存自身数据
                            {
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    FILE_NAME = fileName,
                                    FILE_TYPE = item.ContentType,
                                    //FILE_DATA = fileData,
                                    ORG_ID = orgId,
                                    FILE_PATH = filePath + saveName
                                };
                                imgFile.FILE_ID = file.ID;
                                imgFile.Nav_File = file;
                                fileList.Add(file);
                            }
                        }
                        else
                        {
                            ConvertImageFile tmpImgFile = new ConvertImageFile();
                            tmpImgFile.FileName = fileName;
                            tmpImgFile.FileType = item.ContentType;
                            Byte[] fileData = new Byte[(int)item.Length];
                            Stream sr = inputStream;//创建数据流对象 
                            sr.Read(fileData, 0, (int)item.Length);
                            tmpImgFile.FileData = fileData;
                            list.Add(tmpImgFile);
                        }
                        //保存文件数据
                        if (list.Any())
                        {
                            int i = 1;
                            foreach (var fileitem in list)
                            {
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    ID = Guid.NewGuid(),
                                    FILE_NAME = fileitem.FileName,
                                    FILE_TYPE = fileitem.FileType,
                                    //FILE_DATA = fileitem.FileData,
                                    FILE_PATH = filePath + saveName,
                                    ORG_ID = orgId
                                };

                                if (!isSuppot && isSaveSelf)
                                {
                                    imgFile.FILE_ID = file.ID;
                                    imgFile.Nav_File = file;
                                }


                                T_PF_IMG_FILE_DETAIL detail = new T_PF_IMG_FILE_DETAIL
                                {
                                    ORG_ID = orgId,
                                    IMG_FILE_ID = imgFile.ID,
                                    FILE_ID = file.ID,
                                    NUM = i
                                };
                                i++;
                                fileList.Add(file);
                                imgFileDetailList.Add(detail);
                            }
                        }
                        imgFileList.Add(imgFile);
                        result.imgFileID = imgFile.ID;
                        result.imgFilePath = imgFile.Nav_File?.FILE_PATH;
                    }
                }
                this.BantchAddEntity(fileList);
                this.BantchAddEntity(imgFileList);
                this.BantchAddEntity(imgFileDetailList);
                return result;
            });
        }
        /// <summary>
        /// 首页上传修改签名接口
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UploadFileEditSign")]
        public JsonActionResult<dynamic> UploadFileEditSign()
        {
            return SafeExecute<dynamic>(() =>
            {
                dynamic result = new ExpandoObject();

                var httpRequest = HttpContext.Request;
                var strOrgId = httpRequest.Form["OrgId"][0];  // 获取 组织

                if (string.IsNullOrEmpty(strOrgId))
                    throw new Exception("组织不允许为空");
                var orgId = new Guid(strOrgId);
                //返回的文件地址
                List<string> filenames = new List<string>();
                var now = DateTime.Now;
                //文件存储路径
                //var filePath = string.Format("/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
                string filePath = GetFilePath(orgId);
                var fullFilePath = $"{ ConfigurationManager.AppSettings["Img_Local"]}{filePath}";

                ImageConverterFactory imageConverterFactory = new ImageConverterFactory();
                var host = ConfigurationManager.AppSettings["SapInvokeHost"];

                List<T_PF_FILE> fileList = new List<T_PF_FILE>();
                List<T_PF_IMG_FILE> imgFileList = new List<T_PF_IMG_FILE>();
                List<T_PF_IMG_FILE_DETAIL> imgFileDetailList = new List<T_PF_IMG_FILE_DETAIL>();

                var files = httpRequest.Form.Files;

                if (!Directory.Exists(fullFilePath))
                {
                    Directory.CreateDirectory(fullFilePath);
                }
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);
                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据
                        using (FileStream fs = System.IO.File.Create(fullFilePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        filenames.Add(filePath + saveName);
                        string fileName = item.FileName;
                        var pos = fileName.LastIndexOf(".");
                        var extendName = fileName.Substring(pos);
                        List<ConvertImageFile> list = new List<ConvertImageFile>();
                        bool isSuppot = imageConverterFactory.Support(extendName);
                        bool isSaveSelf = true;

                        T_PF_IMG_FILE imgFile = new T_PF_IMG_FILE
                        {
                            FILE_NAME = fileName,
                            FILE_TYPE = item.ContentType,
                            ORG_ID = orgId
                        };

                        var inputStream = item.OpenReadStream();
                        //支持转换时，按类型转为图片，否则直接存储
                        if (isSuppot)
                        {
                            if (!string.IsNullOrEmpty(host))
                            {
                                ConvertImageFileParam param = new ConvertImageFileParam();
                                param.FileName = fileName;
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                param.FileData = fileData;
                                string url = host + "ImageConvert/ImageConvert";
                                ConvertImageFileParam retModel =
                                    WebUtils.Execute<ConvertImageFileParam>(url, param, string.Empty, SendType.Post);
                                if (retModel != null && retModel.Files != null && retModel.Files.Any())
                                    list.AddRange(retModel.Files);
                            }
                            else
                            {
                                var convert = imageConverterFactory.CreateImageConverter(fileName);
                                convert.ConvertToImage(fileName, inputStream, list);
                            }
                            if (isSaveSelf)//保存自身数据
                            {
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    FILE_NAME = fileName,
                                    FILE_TYPE = item.ContentType,
                                    //FILE_DATA = fileData,
                                    ORG_ID = orgId,
                                    FILE_PATH = filePath + saveName
                                };
                                imgFile.FILE_ID = file.ID;
                                imgFile.Nav_File = file;
                                fileList.Add(file);
                            }
                        }
                        else
                        {
                            ConvertImageFile tmpImgFile = new ConvertImageFile();
                            tmpImgFile.FileName = fileName;
                            tmpImgFile.FileType = item.ContentType;
                            Byte[] fileData = new Byte[(int)item.Length];
                            Stream sr = inputStream;//创建数据流对象 
                            sr.Read(fileData, 0, (int)item.Length);
                            tmpImgFile.FileData = fileData;
                            list.Add(tmpImgFile);
                        }
                        //保存文件数据
                        if (list.Any())
                        {
                            int i = 1;
                            foreach (var fileitem in list)
                            {
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    ID = Guid.NewGuid(),
                                    FILE_NAME = fileitem.FileName,
                                    FILE_TYPE = fileitem.FileType,
                                    //FILE_DATA = fileitem.FileData,
                                    FILE_PATH = filePath + saveName,
                                    ORG_ID = orgId
                                };

                                if (!isSuppot && isSaveSelf)
                                {
                                    imgFile.FILE_ID = file.ID;
                                    imgFile.Nav_File = file;
                                }


                                T_PF_IMG_FILE_DETAIL detail = new T_PF_IMG_FILE_DETAIL
                                {
                                    ORG_ID = orgId,
                                    IMG_FILE_ID = imgFile.ID,
                                    FILE_ID = file.ID,
                                    NUM = i
                                };
                                i++;
                                fileList.Add(file);
                                imgFileDetailList.Add(detail);
                            }
                        }
                        imgFileList.Add(imgFile);
                        result.imgFileID = imgFile.ID;
                        result.imgFilePath = imgFile.Nav_File?.FILE_PATH;
                    }
                }
                var userId = new Guid(httpRequest.Form["userID"][0]);
                var dbEntity = this.GetEntity<T_FM_USER_SIGN_FILE>(t => t.USER_ID == userId);
                List<Guid> deleteSignFileIds = new List<Guid>();
                if (dbEntity != null)
                {
                    if (dbEntity != null)
                    {
                        deleteSignFileIds.Add(dbEntity.ID);
                    }
                }
                T_FM_USER_SIGN_FILE userSign = new T_FM_USER_SIGN_FILE()
                {
                    ID = Guid.NewGuid(),
                    USER_ID = userId,
                    IMG_FILE_ID = imgFileList.FirstOrDefault().ID,
                    ORG_ID = orgId,
                };


                this.BantchAddEntity(fileList);
                this.BantchAddEntity(imgFileList);
                this.BantchAddEntity(imgFileDetailList);
                if (deleteSignFileIds.Any())
                    this.DeleteEntityNoCommit<T_FM_USER_SIGN_FILE>(t => deleteSignFileIds.Contains(t.ID));
                if (userSign != null)
                    this.AddEntity(userSign);
                return result;
            });
        }
        /// <summary>
        /// 上次文件转为图片
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UploadFile")]
        public JsonActionResult<dynamic> UploadFile()
        {
            return SafeExecute<dynamic>(() =>
            {
                dynamic result = new ExpandoObject();

                var httpRequest = HttpContext.Request;
                var strOrgId = httpRequest.Form["OrgId"][0];  // 获取 组织
                var strImgID = string.Empty;
                if (httpRequest.Form.ContainsKey("imgFileID"))
                {
                    strImgID = httpRequest.Form["imgFileID"][0];
                }  // 获取 组织

                var isSaveSelfStr = httpRequest.Form["IsSaveSelf"].Any() ? httpRequest.Form["IsSaveSelf"][0] : "false";  // 是否存储本身
                if (string.IsNullOrEmpty(strOrgId))
                    throw new Exception("组织不允许为空");
                var orgId = new Guid(strOrgId);
                Guid ImgID = Guid.Empty;
                if (strImgID != null && !string.IsNullOrEmpty(strImgID))
                {
                    try
                    {
                        ImgID = new Guid(strImgID.ToString());
                    }
                    catch { }
                }
                if (ImgID == Guid.Empty)
                {
                    ImgID = Guid.NewGuid();
                }

                //返回的文件地址
                //List<string> filenames = new List<string>();
                var now = DateTime.Now;
                //文件存储路径
                //var filePath = string.Format("/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
                string filePath = GetFilePath(orgId);

                var fullFilePath = $"{ ConfigurationManager.AppSettings["Img_Local"]}{filePath}";

                ImageConverterFactory imageConverterFactory = new ImageConverterFactory();
                var host = ConfigurationManager.AppSettings["SapInvokeHost"];

                List<T_PF_FILE> fileList = new List<T_PF_FILE>();
                List<T_PF_IMG_FILE> imgFileList = new List<T_PF_IMG_FILE>();
                List<T_PF_IMG_FILE_DETAIL> imgFileDetailList = new List<T_PF_IMG_FILE_DETAIL>();

                var files = httpRequest.Form.Files;

                if (!Directory.Exists(fullFilePath))
                {
                    Directory.CreateDirectory(fullFilePath);
                }

                //wyw 2023-12-15 保存的文件还是用自动生成的文件名吧 省得处理url转译
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);

                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //var saveName = strDateTime + strRan + fileExtension;
                        string fileName = item.FileName;

                        //插入图片数据
                        using (FileStream fs = System.IO.File.Create(fullFilePath + saveName))//fullFilePath + fileName  wyw
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        //filenames.Add(filePath + fileName);
                        var pos = fileName.LastIndexOf(".");
                        var extendName = fileName.Substring(pos);
                        List<ConvertImageFile> list = new List<ConvertImageFile>();
                        bool isSuppot = imageConverterFactory.Support(extendName);
                        bool isSaveSelf = true;

                        T_PF_IMG_FILE imgFile = new T_PF_IMG_FILE
                        {
                            ID = ImgID,
                            FILE_NAME = fileName,
                            FILE_TYPE = item.ContentType,
                            ORG_ID = orgId
                        };

                        var inputStream = item.OpenReadStream();
                        //支持转换时，按类型转为图片，否则直接存储
                        if (isSuppot)
                        {
                            if (!string.IsNullOrEmpty(host))
                            {
                                ConvertImageFileParam param = new ConvertImageFileParam();
                                param.FileName = fileName;
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                param.FileData = fileData;
                                string url = host + "ImageConvert/ImageConvert";
                                ConvertImageFileParam retModel =
                                    WebUtils.Execute<ConvertImageFileParam>(url, param, string.Empty, SendType.Post);
                                if (retModel != null && retModel.Files != null && retModel.Files.Any())
                                    list.AddRange(retModel.Files);
                            }
                            else
                            {
                                var convert = imageConverterFactory.CreateImageConverter(fileName);
                                convert.ConvertToImage(fileName, inputStream, list);
                            }
                            if (isSaveSelf)//保存自身数据
                            {
                                Byte[] fileData = new Byte[(int)item.Length];
                                Stream sr = inputStream;//创建数据流对象 
                                sr.Read(fileData, 0, (int)item.Length);
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    FILE_NAME = fileName,
                                    FILE_TYPE = item.ContentType,
                                    //FILE_DATA = fileData,
                                    ORG_ID = orgId,
                                    //FILE_PATH = filePath + fileName
                                    FILE_PATH = filePath + saveName//wyw
                                };
                                imgFile.FILE_ID = file.ID;
                                imgFile.Nav_File = file;
                                fileList.Add(file);
                            }
                        }
                        else
                        {
                            ConvertImageFile tmpImgFile = new ConvertImageFile();
                            //tmpImgFile.FileName = fileName;
                            tmpImgFile.FileName = saveName;//wyw
                            tmpImgFile.FileType = item.ContentType;
                            Byte[] fileData = new Byte[(int)item.Length];
                            Stream sr = inputStream;//创建数据流对象 
                            sr.Read(fileData, 0, (int)item.Length);
                            tmpImgFile.FileData = fileData;
                            list.Add(tmpImgFile);
                        }
                        //保存文件数据
                        if (list.Any())
                        {
                            int i = 1;
                            foreach (var fileitem in list)
                            {
                                T_PF_FILE file = new T_PF_FILE
                                {
                                    ID = Guid.NewGuid(),
                                    FILE_NAME = fileitem.FileName,
                                    FILE_TYPE = fileitem.FileType,
                                    //FILE_DATA = fileitem.FileData,
                                    //FILE_PATH = filePath + fileName,
                                    FILE_PATH = filePath + saveName,//wyw,
                                    ORG_ID = orgId
                                };

                                if (!isSuppot && isSaveSelf)
                                {
                                    imgFile.FILE_ID = file.ID;
                                    imgFile.Nav_File = file;
                                }


                                T_PF_IMG_FILE_DETAIL detail = new T_PF_IMG_FILE_DETAIL
                                {
                                    ORG_ID = orgId,
                                    IMG_FILE_ID = imgFile.ID,
                                    FILE_ID = file.ID,
                                    NUM = i
                                };
                                i++;
                                fileList.Add(file);
                                imgFileDetailList.Add(detail);
                            }
                        }
                        imgFileList.Add(imgFile);
                        result.imgFileID = imgFile.ID;
                        result.imgFilePath = imgFile.Nav_File?.FILE_PATH;
                    }
                }
                this.BantchAddEntity(fileList);
                this.BantchAddEntity(imgFileList);
                this.BantchAddEntity(imgFileDetailList);
                return result;
            });
        }





        /// <summary>
        /// 根据ID获取文件数据
        /// </summary> 
        /// <param name="id"></param>
        [HttpGet, Route("GetFile")]
        public void GetFile(string id)
        {
            if (string.IsNullOrEmpty(id)) return;
            var file = this.GetEntity<T_PF_FILE>(id);
            if (file == null) return;
            var syncIOFeature = HttpContext.Features.Get<IHttpBodyControlFeature>();
            if (syncIOFeature != null)
            {
                syncIOFeature.AllowSynchronousIO = true;
            }
            SetData(file.FILE_NAME, file.FILE_TYPE, file.FILE_DATA);
        }
        /// <summary>
        /// 根据ID获取文件数据
        /// </summary> 
        /// <param name="id"></param>
        [HttpGet, Route("GetFilePath")]
        public JsonActionResult<string> GetFilePath(string id)
        {
            return SafeExecute<string>(() =>
            {
                if (string.IsNullOrEmpty(id)) return "";
                var file = this.GetEntity<T_PF_FILE>(id);
                if (file == null) return "";
                return file.FILE_PATH;
            });
        }

        /// <summary>
        /// 根据ID获取文件数据
        /// </summary> 
        /// <param name="name"></param>
        [HttpGet, Route("GetFileByName")]
        public void GetFileByName(string name)
        {
            if (string.IsNullOrEmpty(name)) return;
            var file = this.GetEntity<T_PF_FILE>(i => i.FILE_NAME == name);
            if (file == null) return;
            var syncIOFeature = HttpContext.Features.Get<IHttpBodyControlFeature>();
            if (syncIOFeature != null)
            {
                syncIOFeature.AllowSynchronousIO = true;
            }
            SetData(file.FILE_NAME, file.FILE_TYPE, file.FILE_DATA);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        [HttpGet, Route("GetFileByPath")]
        public void GetFileByPath(string id)
        {
            if (string.IsNullOrEmpty(id)) return;
            var file = this.GetEntity<T_PF_FILE>(id);
            if (file == null) return;
            var ss = file.FILE_PATH;
            byte[] zipdata = System.IO.File.ReadAllBytes(ss);
            SetData(file.FILE_NAME, file.FILE_TYPE, zipdata);
        }

        private void SetData(string fileName, string contentType, byte[] data)
        {
            var httpResponse = HttpContext.Response;
            httpResponse.ContentType = contentType;
            string encodeFilename = System.Net.WebUtility.UrlEncode(fileName);
            httpResponse.Headers.Add("Content-Disposition", "attachment;filename=" + encodeFilename);
            //httpResponse.Body.Write(file.FILE_DATA,0,file.FILE_DATA.Length);
            //httpResponse.Body.Flush();
            int bufferSize = 1024;
            using (Response.Body)//调用Response.Body.Dispose()并不会关闭客户端浏览器到ASP.NET Core服务器的连接，之后还可以继续往Response.Body中写入数据
            {
                long contentLength = data.Length;//获取下载文件的大小
                Response.ContentLength = contentLength;//在Response的Header中设置下载文件的大小，这样客户端浏览器才能正确显示下载的进度

                byte[] buffer;
                long hasRead = 0;//变量hasRead用于记录已经发送了多少字节的数据到客户端浏览器

                //如果hasRead小于contentLength，说明下载文件还没读取完毕，继续循环读取下载文件的内容，并发送到客户端浏览器
                while (hasRead < contentLength)
                {
                    //HttpContext.RequestAborted.IsCancellationRequested可用于检测客户端浏览器和ASP.NET Core服务器之间的连接状态，如果HttpContext.RequestAborted.IsCancellationRequested返回true，说明客户端浏览器中断了连接
                    if (HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        //如果客户端浏览器中断了到ASP.NET Core服务器的连接，这里应该立刻break，取消下载文件的读取和发送，避免服务器耗费资源
                        break;
                    }

                    buffer = new byte[bufferSize];

                    int currentRead = data.Length - hasRead > bufferSize ? bufferSize :
                       data.Length - (int)hasRead;//  fs.Read(buffer, 0, bufferSize);//从下载文件中读取bufferSize(1024字节)大小的内容到服务器内存中

                    Array.Copy(data, hasRead, buffer, 0, currentRead);

                    var r = Response.Body.WriteAsync(buffer, 0, currentRead);//发送读取的内容数据到客户端浏览器
                    r.Wait();
                    Response.Body.Flush();//注意每次Write后，要及时调用Flush方法，及时释放服务器内存空间

                    hasRead += currentRead;//更新已经发送到客户端浏览器的字节数
                }
            }
        }


        /// <summary>
        /// 根据OrgId获取文件夹名称
        /// </summary>
        /// <param name="OrgId"></param>
        /// <returns></returns>
        public string GetFilePath(Guid OrgId)
        {
            string orgid = OrgId.ToString().ToUpperInvariant();
            string pathHead = "";
            if (OrgId != new Guid())
            {
                List<EnumberEntity> listHead = EnumToList<FilePathHead>();
                //var info = listHead.Find(e => e.Desction.Contains("," + orgid + ","));
                var info = listHead.FirstOrDefault(e => e.Desction == orgid);
                if (info != null)
                {
                    pathHead = info.EnumName;
                }
            }
            DateTime dtNow = DateTime.Now;
            var strDateTime = DateTime.Now.ToString("hhmmssfff"); //取得时间字符串
            //var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
            var filePath = string.Format("/{0}/{1}/{2}/{3}/", dtNow.ToString("yyyy"), dtNow.ToString("yyyyMM"), dtNow.ToString("yyyyMMdd"), strDateTime);
            return string.IsNullOrEmpty(pathHead) ? filePath : "/" + pathHead + filePath;
        }


        public static List<EnumberEntity> EnumToList<T>()
        {
            List<EnumberEntity> list = new List<EnumberEntity>();
            foreach (var e in Enum.GetValues(typeof(T)))
            {
                EnumberEntity m = new EnumberEntity();
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objArr != null && objArr.Length > 0)
                {
                    DescriptionAttribute da = objArr[0] as DescriptionAttribute;
                    m.Desction = da.Description;

                }
                m.EnumValue = Convert.ToInt32(e);
                m.EnumName = e.ToString();
                list.Add(m);
            }
            return list;
        }

    }

    /// <summary>
    /// 枚举类
    /// </summary>
    public class EnumberEntity
    {
        /// <summary>  
        /// 枚举的描述  
        /// </summary>  
        public string Desction { set; get; }

        /// <summary>  
        /// 枚举名称  
        /// </summary>  
        public string EnumName { set; get; }

        /// <summary>  
        /// 枚举对象的值  
        /// </summary>  
        public int EnumValue { set; get; }
    }
}
