using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiConfig.Controller
{
    public class MonthReportRecordController : BaseController
    {
        private readonly IMonthReportSendRecordRepository _recordRepository;
        public MonthReportRecordController(IMonthReportSendRecordRepository recordRepository)
        {
            _recordRepository = recordRepository;
        }

        [HttpGet]
        public IActionResult GetMonthReportRecord(string name, string starttime, string endtime, int page = PageIndex, int pagesize = PageSize)
        {
            var data = _recordRepository.GetPagedCollectionResult(name,starttime, endtime, ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        [HttpGet]
        public IActionResult GetPdfFileName(int id)
        {
            var report = _recordRepository.Get(id);
            if (report.status == (int)RowState.Invalid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var path = report.file_path;
            if (!System.IO.File.Exists(path))
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var file = new FileInfo(path);
            return new ObjectResult(file.Name);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoTokenValidateFilter]
        [NoResultFilter]
        public IActionResult DownloadReport(int id)
        {
            var report = _recordRepository.Get(id);
            if (report.status == (int) RowState.Invalid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var path = report.file_path;
            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 = "report.pdf"
                };
                return File(stream, "application/octet-stream");
            }
            catch
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
    }
}