using AutoNotificatPhone.Models;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NLog;
using System;
using System.Text.Json;

namespace AutoNotificatPhone.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CallAndMsgController : ControllerBase
    {
        // 日志记录器
        public static Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request">类型type： 1电话 2短信</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnInfo SendToPhone([FromBody] SmsRequest request)
        {
            try
            {
                // 创建一个新的对象来存储转换后的值
                var notification = new
                {
                    request.PhoneNumber,
                    request.CallerName,
                    request.Content,
                    request.Type,
                    // 转换时间值为 ISO 8601 格式字符串
                    StartingPoint = ConvertTimestampToIso(request.StartingPoint),
                    DeadLine = ConvertTimestampToIso(request.DeadLine)
                };

                // 生成唯一的NoticeID
                string noticeId = "MsgAndCall";

                // 将转换后的通知内容发布到redis
                CSRedisCacheHelper.Publish(noticeId, Newtonsoft.Json.JsonConvert.SerializeObject(notification));
                logger.Error($"执行发送任务:" + Newtonsoft.Json.JsonConvert.SerializeObject(request));
                return new ReturnInfo
                {
                    isok = true,
                    message = request.Type == "1" ? "电话已加入拨打队列" : "短信已加入发送队列",
                    status = 200,
                    response = "success"
                };
            }
            catch (Exception ex)
            {
                return new ReturnInfo
                {
                    isok = false,
                    message = ex.Message,
                    status = 500,
                    response = ""
                };
            }
        }

        // 将时间戳转换为 ISO 8601 格式字符串
        private long ConvertTimestampToIso(long timestamp)
        {
            DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeSeconds(timestamp);
            return dateTime.ToUnixTimeSeconds();
        }
    }
}