using MoYu.FriendlyException;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Web.Core.Controllers.Application.Business.Dto;
using System.Collections.Generic;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 设备管理接口
/// </summary>
[Route("/business/[controller]")]
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 100,Tag = "摄像头设备流媒体")]
public class DeviceApi:IDynamicApiController
{
    private readonly IDeepelephManager _deepelephManager;
    private readonly ISimpleCacheService _simpleCacheService;

    public DeviceApi(IDeepelephManager deepelephManager, ISimpleCacheService simpleCacheService)
    {
        _deepelephManager = deepelephManager;
        _simpleCacheService = simpleCacheService;
    }

    /// <summary>
    /// 获取设备ip
    /// </summary>
    /// <returns></returns>
    public async Task<string> FieldValidNetwork()
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await  $"{appSettings.SXAPIURL}/device/console/v1/device/field_valid_network"
            .SetBody(new { token = _deepelephManager.GetToken(), tenantCode=appSettings.TenantCode, poiId = appSettings.PoiId, })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"]["ipv4"].ToString();
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 分页查询摄像头列表
    /// </summary>
    /// <param name="search">查询条件</param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<dynamic> Brief(BriefSearch search)
    {
        if (string.IsNullOrEmpty(search.sensorId)||string.IsNullOrEmpty(search.sensorName))
        {
            var data = _simpleCacheService.Get<JToken>(SafeCampusConst.DeviceList);
            if (data != null)
            {
                return new
                {
                    pageNum = search.PageNum,
                    pageSize = data["data"]["size"],
                    total = data["data"]["total"],
                    pages = data["data"]["pages"],
                    list = data["data"]["items"]
                };
            }
        }
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/page_query/brief"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                search.sensorId,
                search.sensorName,
                pageNo = 1,
                pageSize=500,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        if (model["data"]!=null)
        {
            if (!string.IsNullOrEmpty(search.sensorId) &&!string.IsNullOrEmpty(search.sensorName))
            {
                _simpleCacheService.Set(SafeCampusConst.DeviceList, model["data"]);
            }
            return new
            {
                pageNum = search.PageNum,
                pageSize = model["data"]["size"],
                total = model["data"]["total"],
                pages = model["data"]["pages"],
                list = model["data"]["items"]
            };
        }
        return new
        {
            pageNum = search.PageNum,
            pageSize =0,
            total = 0,
            pages = 0,
            list = new List<string>()
        };

    }
    /// <summary>
    /// 摄像头数据同步
    /// </summary>
    /// <returns></returns>
    [Obsolete]
    public async Task<bool> DataSync()
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/page_query/brief"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
               
                pageNo = 1,
                pageSize = 500,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        _simpleCacheService.Set(SafeCampusConst.DeviceList, model["data"]);
        return true;
    }
    /// <summary>
    /// 根据id查询摄像头
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <returns></returns>
    public async Task<dynamic> GetCameraById(string sensorId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/api/v1/camera/get"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                fieldId = appSettings.PoiId,
                sensorId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 直播流拉取
    /// 拉流的时候，选pullStreamUrls和rtsPullStreamUrls里面的链接，pushStreamUrls和h5rtsPullStreamUrls直接忽略。
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<dynamic> GetStartVideoLive(string sensorId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/start_video_live"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId=sensorId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 直播流停止拉取
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <param name="videoToken">视频token</param>
    /// <param name="streamId">流ID</param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<dynamic> GetStopVideoLive(string sensorId,string videoToken,string streamId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/stop_video_live"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
                videoToken,
                streamId
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"]["streamId"].ToString();
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    ///  录像流拉取
    /// ！！！注意，录入摄像头时，需要填写存储设备相关信息，才能正常拉录像！！！
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <param name="startTime">开始时间</param>
    /// <param name="endTime">结束时间</param>
    /// <returns></returns>
    public async Task<dynamic> GetStartVideoPlayback(string sensorId,DateTime startTime,DateTime endTime)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/start_video_playback"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
                startTime=new DateTimeOffset(startTime).ToUnixTimeMilliseconds(),
                endTime=new DateTimeOffset(endTime).ToUnixTimeMilliseconds()
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 录像流停止
    /// </summary>
    /// <param name="sensorId">摄像头id</param>
    /// <param name="videoToken">视频token</param>
    /// <param name="streamId">流ID</param>
    /// <returns></returns>
    public async Task<dynamic> GetStopVideoPayback(string sensorId,string videoToken,string streamId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/stop_video_playback"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
                videoToken,
                streamId
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"]["streamId"].ToString();
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 摄像头快照获取
    /// </summary>
    /// <param name="sensorId">摄像头id不传入时，默认下发门店下所有摄像头</param>
    /// <returns></returns>
    public async Task<dynamic> GetTakeSnapshot(string sensorId)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/device/console/v1/sensor/take_snapshot"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                cameraId = sensorId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
}