using AI.Platform.Core;
using AI.Platform.Core.Entity.Device;
using AI.Platform.Core.Entity.Media;
using AI.Platform.Core.Entity.Site;
using AI.Platform.Service.Common;
using AI.Platform.Service.Output;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

namespace AI.Platform.Service;


[ApiGroup(ApiGroupNames.Media)]
public class MediaService:BaseService
{
    private readonly SqlSugarRepository<MediaEntity> _mediaRepository;
    private readonly SqlSugarRepository<SiteEntity> _siteRepository;
    private readonly SqlSugarRepository<ScreentEntity> _screenRepository;

    private readonly IHttpContextAccessor _contextAccessor;

    public MediaService(IHttpContextAccessor contextAccessor, SqlSugarRepository<MediaEntity> mediaRepository, SqlSugarRepository<SiteEntity> siteRepository, SqlSugarRepository<ScreentEntity> screenRepository)
    {
        _contextAccessor = contextAccessor;
        _mediaRepository = mediaRepository;
        _siteRepository = siteRepository;
        _screenRepository = screenRepository;
    }

    /// <summary>
    /// 查询可播放广告
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<List<PlayAbleMedia>> Playable()
    {
        var SN = _contextAccessor.HttpContext.Request.Headers["DeviceSn"];

        var playAbleMedias = await _screenRepository.AsQueryable()
            .LeftJoin<SiteEntity>((scrren, site) => scrren.SiteId == site.Id)
            .LeftJoin<MediaEntity>((scrren, site, media) => site.Id == media.BusinessUnitId)
            .Where((scrren, site, media) => scrren.sn == SN)
            .Where((scrren, site, media) => media.MediaState == 1)
            .Where((scrren, site, media) => media.EffectiveTime <= DateTime.Now && media.FailureTime >= DateTime.Now)
            .Select((scrren, site, media) => new 
            {
                media.Id,
                media.GuidFileName,
                media.StartTime,
                media.EndTime,
                media.MachineState 
            })
            .ToListAsync();

        var result = playAbleMedias.Select(media => new PlayAbleMedia()
        {
            id = media.Id,
            guidFileName = media.GuidFileName,
            startTime = media.StartTime,
            endTime = media.EndTime,
            machineState = JsonSerializer.Deserialize<List<string>>(media.MachineState),
        }).ToList();
        return result;
    }

    /// <summary>
    /// 查询可播放广告
    /// </summary>
    /// <returns></returns>
    [HttpGet("api/Media/download/{id}")]
    public async Task<IActionResult> DownloadFile(long id)
    {
        MediaEntity mediaEntity = await _mediaRepository.AsQueryable()
            .Where(it => it.Id == id)
            .FirstAsync();

        // 假设文件存放在 wwwroot/files 目录下
        var filePath = mediaEntity.LocalPath;

        if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
        {
            return new ObjectResult(new
            {
                Message = "没找到文件",
                StatusCode = StatusCodes.Status204NoContent
            });
        }

        byte[] fileBytes = await File.ReadAllBytesAsync(filePath);

        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(fileBytes)
        };


        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        //_contextAccessor.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        string contentType = GetContentType(Path.GetExtension(mediaEntity.FileExtension));
        return new FileStreamResult(fileStream, contentType)
        {
            FileDownloadName = mediaEntity.GuidFileName,
        };
    }

        private string GetContentType(string fileExtension)
        {
            switch (fileExtension.ToLower())
            {
                case ".txt":
                    return "text/plain";
                case ".html":
                case ".htm":
                    return "text/html";
                case ".css":
                    return "text/css";
                case ".js":
                    return "application/javascript";
                case ".json":
                    return "application/json";
                case ".jpg" or ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                case ".gif":
                    return "image/gif";
                case ".rar":
                    return "application/x-rar-compressed";
                case ".zip":
                    return "application/zip";
                default:
                    return "application/octet-stream";
            }
        }
}



