using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using NPOI.HPSF;
using WCS.BLL.DbModels;
using WCS.BLL.Services.IService;
using WCS.BLL.Services.Service;
using WCS.DAL.Db;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.User;
using WCS.Model.WebSocketModel;

namespace WCS.WebApi.Controllers
{
    /// <summary>
    /// 文件下载
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class FileDownLoadController : ControllerBase
    {
        public FileDownLoadController()
        {
        }
        [HttpPost("uploadApp")]
        public async Task<ResponseBase> uploadApp([FromForm] IFormFile excelFile, [FromForm] string version, [FromForm] string content)
        {
            //文件校验
            if (excelFile == null || excelFile.Length == 0 || !excelFile.FileName.ToUpper().Contains("APK"))
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = "上传失败:文件格式错误或文件为空！"
                };
            }
            //版本号输入参数的校验
            if (string.IsNullOrEmpty(version))
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = "上传失败:请输入上传文件的版本号version！"
                };
            }

            //版本号输入参数的校验
            if (string.IsNullOrEmpty(content) || content.Length > 250)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"上传失败:请输入【更新内容】或者【更新内容】长度{content.Length}过长需要小于250！"
                };
            }

            // 定义保存路径
            var savePath = Path.Combine(AppContext.BaseDirectory, $"Files");
            // 确保文件夹存在  
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            // 构造文件完整路径  
            var filePath = Path.Combine(savePath, excelFile.FileName);
            try
            {
                // 保存文件  
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await excelFile.CopyToAsync(stream);
                }
                #region 保存数据
                var appVersion = new AppVersion()
                {
                    AppName = excelFile.FileName,
                    Version = version,
                    Content = content,
                };
                DbHelp.db.Insertable(appVersion).ExecuteCommand();
                #endregion
                // 文件上传成功，返回成功信息  
                return new ResponseCommon()
                {
                    Code = 200,
                    Message = "上传成功！"
                };
            }
            catch (Exception ex)
            {
                // 异常处理，返回错误信息  
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = "上传失败: " + ex.Message
                };
            }
        }
        [HttpGet("downloadApp")]
        public IActionResult downloadApp(string fileName)
        {
            // 这里是文件的物理路径，你需要根据实际情况提供  
            var filePath = Path.Combine(AppContext.BaseDirectory, $"Files/{fileName}");
            // 检查文件是否存在  
            if (!System.IO.File.Exists(filePath))
            {
                return NotFound();
            }
            // 获取文件流  
            var stream = System.IO.File.OpenRead(filePath);
            // 设置HTTP响应头，使浏览器知道这是一个附件，应该下载而不是打开  
            Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 返回文件流作为FileResult  
            return File(stream, "application/octet-stream", fileName);
        }

        [HttpGet("getLatestAppName")]
        public ResponseCommon<string> getLatestAppName()
        {
            try
            {
                string directoryPath = Path.Combine(AppContext.BaseDirectory, $"Files");

                // 获取目录下的所有文件信息  
                FileInfo[] files = Directory.GetFiles(directoryPath, "*.APK")
                                        .Select(file => new FileInfo(file))
                                        .ToArray();
                if (files == null || files.Length == 0)
                {
                    return new ResponseCommon<string>()
                    {
                        Code = 201,
                        Message = "服务器不存在App安装包"
                    };
                }
                //获取最后修改的一个
                FileInfo lastModifiedFile = files.OrderByDescending(f => f.LastWriteTime).First();
                if (lastModifiedFile != null)
                {
                    return new ResponseCommon<string>()
                    {
                        Code = 200,
                        Data = lastModifiedFile.Name
                    };
                }
                else
                {
                    return new ResponseCommon<string>()
                    {
                        Code = 201,
                        Message = "服务器不存在App安装包"
                    };
                }
            }
            catch
            {
                return new ResponseCommon<string>()
                {
                    Code = 201,
                    Message = "服务器不存在App安装包"
                };
            }
        }

        /// <summary>
        /// 获取最新的版本
        /// </summary>
        /// <returns></returns>
        [HttpGet("getLatestAppVersion")]
        public ResponseBase getLatestAppVersion()
        {
            try
            {
                var appVersion = DbHelp.db.Queryable<AppVersion>().OrderByDescending(t => t.Id).First(); ;
                if (appVersion != null)
                {
                    return new ResponseBase<object>()
                    {
                        Code = 200,
                        Message = "success",
                        Data = new
                        {
                            AppName = appVersion.AppName,
                            Version = appVersion.Version,
                            Content = appVersion.Content,
                        }
                    };
                }
                else
                {
                    return new ResponseBase<object>()
                    {
                        Code = 201,
                        Message = "未获取到APK的最新版本",
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResponseBase<object>()
                {
                    Code = 300,
                    Message = $"请求失败：{ex.Message}"
                };
            }
        }

    }
}
