using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.EsopRepository.Entities;
using Siger.Middlelayer.EsopRepository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiEsop.Controllers
{
    [Route("esop/[controller]/[action]")]
    public class DownloadController : ControllerBase
    {
        private readonly IEsopDocumentHistoryRepository _historyRepository;

        public DownloadController(IEsopDocumentHistoryRepository historyRepository)
        {
            _historyRepository = historyRepository;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoResultFilter]
        public IActionResult DownloadFile(int id)
        {
            var his = _historyRepository.Get(q => q.document_id == id && q.is_valid == 1 && q.status == (int)RowState.Valid);
            if (his == null)
            {
                return new NoContentResult();
            }
            if (string.IsNullOrWhiteSpace(his.file_name))
            {
                return new NoContentResult();
            }
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                return new NoContentResult();
            }

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder);

            var url = his.file_url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (url.Length != 4)
            {
                return new NoContentResult();
            }

            var path = Path.Combine(rootDir, url[1], url[2], url[3]);
            if (!System.IO.File.Exists(path))
            {
                return new NoContentResult();
            }
            try
            {
                var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = string.IsNullOrWhiteSpace(his.file_name) ? "" : his.file_name
                };

                return File(stream, "application/octet-stream");
            }
            catch
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        /// <summary>
        /// 获取文件内容
        /// </summary>
        ///// <returns></returns>
        [HttpGet]
        public IActionResult GetContent(int id)//,int type)
        {
            var his = _historyRepository.Get(q => q.document_id == id && q.is_valid == 1 && q.status == (int)RowState.Valid);
            if (his == null)
            {
                return new NoContentResult();
            }
            var file_url = his.file_url;
            if (string.IsNullOrEmpty(file_url))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            if (file_url.ToLower().EndsWith(".zip") || file_url.ToLower().EndsWith(".dwg") || file_url.ToLower().EndsWith(".jpg") || file_url.ToLower().EndsWith(".eng"))
            {
                return new ObjectResult(new { content = "无法预览" });
            }
            var path = FileUtility.GetEsopTruePath(file_url);
            if (!System.IO.File.Exists(path))
            {
                Logger.WriteLineError($"program getContent from:{path} failed");
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            var data = System.IO.File.ReadAllLines(path);

            return new ObjectResult(new { data.Length, content = FileUtility.GetText(path) });
        }
        /// <summary>
        /// 预览文本文件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="history_id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PreviewFile(int id, int history_id = 0)
        {
            siger_project_esop_document_history his = null;
            if (history_id == 0)
            {
                his = _historyRepository.Get(q => q.document_id == id && q.is_valid == 1 && q.status == (int)RowState.Valid);
            }
            else
            {
                his = _historyRepository.Get(q => q.id == history_id && q.status == (int)RowState.Valid);
            }
            
            if (his == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (string.IsNullOrWhiteSpace(his.file_name))
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (his.file_name.EndsWith(".txt") == false)
            {
                throw new BadRequestException(RequestEnum.CannotPreviewThisFile);
            }
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.ConfigError);
            }

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder);

            var url = his.file_url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (url.Length != 4)
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }

            var path = Path.Combine(rootDir, url[1], url[2], url[3]);
            if (!System.IO.File.Exists(path))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }

            try
            {
                var lineContent = string.Empty;
                var encoding = FileHelper.GetType(path);
                if (!Equals(encoding, Encoding.UTF8))
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    encoding = Encoding.GetEncoding("gb2312");
                }
                
                var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                var sr = new StreamReader(fs, encoding);
                while (sr.Peek() != -1)
                {
                    lineContent += sr.ReadLine() + "<br>";
                }
                sr.Close();
                fs.Close();

                return new ObjectResult(lineContent);
            }
            catch
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

    }
}