using System.Dynamic;
using Infrastructure;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.WebApi;
using SqlSugar;

namespace OpenAuth.App.ServiceApp;

public class LasaAircraftServiceApp : SqlSugarBaseApp<LasaAircraft, SugarDbContext>
{
    private readonly MqttClientManager _mqttClientManager;

    public LasaAircraftServiceApp(MqttClientManager mqttClientManager, ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<LasaAircraft> repository, IAuth auth) : base(unitWork, repository, auth)
    {
        _mqttClientManager = mqttClientManager;
    }

    public async Task<Response<bool>> AddLasaAircraft(LasaAircraft info)
    {
        info.Id = Guid.NewGuid().ToString();
        info.CreateTime = DateTime.Now;
        if (await Repository.InsertAsync(info))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "添加成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "添加失败"
        };
    }

    public async Task<Response<bool>> DeleteLasaAircraft(string id)
    {
        if (await Repository.DeleteByIdAsync(id))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "删除成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "删除失败"
        };
    }

    public async Task<Response<bool>> UpdateLasaAircraft(LasaAircraft info)
    {
        info.UpdateTime = DateTime.Now;
        // 使用Updateable方法来避免空值更新问题
        using (var db = Repository.AsSugarClient())
        {
            var result = await Repository.AsSugarClient().Updateable(info).IgnoreNullColumns().ExecuteCommandAsync();
            if (result > 0)
            {
                return new Response<bool>
                {
                    Result = true,
                    Message = "修改成功"
                };
            }
        }


        return new Response<bool>
        {
            Result = false,
            Message = "修改失败"
        };
    }

    public async Task<Response<PageInfo<IEnumerable<LasaAircraft>>>> GetLasaAircraftList(string key, int page,
        int limit)
    {
        RefAsync<int> totalCount = 0;
        var pageList = await Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(key), x => x.Name.Contains(key) || x.Sn.Contains(key))
            .ToPageListAsync(page, limit, totalCount);

        return new Response<PageInfo<IEnumerable<LasaAircraft>>>
        {
            Result = new PageInfo<IEnumerable<LasaAircraft>>
            {
                Items = pageList,
                Total = totalCount
            }
        };
    }

    public async Task<Response<LasaAircraft>> GetLasaAircraft(string id)
    {
        return new Response<LasaAircraft>
        {
            Result = await Repository.GetByIdAsync(id)
        };
    }

    public async Task<Response<bool>> StartLiveStreaming(string id)
    {
        var lasaAircraft = await Repository.GetByIdAsync(id);
        // 主题参考thing/product/1581F8HGX254V00A0BUY/osd
        dynamic data = new ExpandoObject();
        data.method = "live_start_push";
        data.data.url = ""; // todo 
        data.video_quality = 3; // "0":"自适应","1":"流畅","2":"标清","3":"高清","4":"超清"
        // todo 发送消息
        // todo 关于监听反馈消息
        String sn = lasaAircraft.Sn;
        await _mqttClientManager.PublishAsync("thing/aircraft/{sn}/service",
            JsonConvert.SerializeObject(data));
        return new Response<bool>
        {
            Result = true,
            Message = "推流命令已发送"
        };
    }

    public async Task<Response<bool>> StopLiveStreaming(string id)
    {
        var lasaAircraft = await Repository.GetByIdAsync(id);
        dynamic data = new ExpandoObject();
        data.method = "live_start_push";
        String sn = lasaAircraft.Sn;
        await _mqttClientManager.PublishAsync("thing/aircraft/{sn}/service",
            JsonConvert.SerializeObject(data));
        return new Response<bool>
        {
            Result = true,
            Message = "停止推流命令已发送"
        };
    }
}