namespace SHH.CameraDashboard;

public partial class CameraRepository
{
    #region PtzControlAsync

    /// <summary>
    /// 发送 PTZ 控制指令
    /// </summary>
    public async Task<bool> PtzControlAsync(long cameraId, PtzControlDto payload)
    {
        var serviceNode = AppGlobal.UseServiceNode;
        if (serviceNode == null) return false;

        string requestUrl = $"http://{serviceNode.ServiceNodeIp}:{serviceNode.ServiceNodePort}{WebApiRoutes.Cameras.Ptz(cameraId.ToString())}";

        try
        {
            string json = JsonHelper.Serialize(payload);
            await WebApiService.Instance.PostAsync(requestUrl, json, "PTZ控制");
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"PTZ控制失败: {ex.Message}");
            return false;
        }
    }

    #endregion
    #region 运维指令 (Maintenance)

    /// <summary>
    /// [修正] 发送校时指令
    /// 修正点：后端 [FromBody] DateTime 需要接收带双引号的标准 ISO 时间字符串
    /// </summary>
    public async Task<bool> SyncTimeAsync(long cameraId)
    {
        var serviceNode = AppGlobal.UseServiceNode;
        if (serviceNode == null) return false;

        string requestUrl = $"http://{serviceNode.ServiceNodeIp}:{serviceNode.ServiceNodePort}{WebApiRoutes.Cameras.Time(cameraId.ToString())}";

        try
        {
            // 1. 获取当前时间，格式化为标准 ISO 8601 (yyyy-MM-ddTHH:mm:ss)
            string timeStr = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");

            // 2. [关键] 手动构造 JSON Body，必须包含双引号
            // 例如发送的内容应该是: "2025-01-01T12:00:00"
            string jsonBody = $"\"{timeStr}\"";

            // 3. 发送请求
            // 确保你的 WebApiService.PostAsync 会设置 Content-Type: application/json
            await WebApiService.Instance.PostAsync(requestUrl, jsonBody, "设备校时");
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"校时失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 发送远程重启指令
    /// 接口定义: [HttpPost("{id}/reboot")] public async Task<IActionResult> RebootDevice(long id)
    /// 该接口没有 [FromBody] 参数，Body 可以为空或空 JSON
    /// </summary>
    public async Task<bool> RebootCameraAsync(long cameraId)
    {
        var serviceNode = AppGlobal.UseServiceNode;
        if (serviceNode == null) return false;

        string requestUrl = $"http://{serviceNode.ServiceNodeIp}:{serviceNode.ServiceNodePort}{WebApiRoutes.Cameras.Reboot(cameraId.ToString())}";

        try
        {
            await WebApiService.Instance.PostAsync(requestUrl, "{}", "远程重启");
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"重启失败: {ex.Message}");
            return false;
        }
    }

    #endregion
}