using BPA.AGV;
using BPA.MES.Base.Application.Services.AGVService.Dtos;
using Furion.EventBus;
using Furion.JsonSerialization;
using Furion.RemoteRequest.Extensions;

namespace BPA.MES.Base.Application.Services
{
    /// <summary>
    /// AGV第三方api
    /// </summary>
    [AllowAnonymous, NonUnify]
    [ApiDescriptionSettings("AGV管理", Name = "AgvThirdParty", Tag = "AGV第三方api", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class AGVThirdPartyService : IAGVThirdPartyService, ITransient, IDynamicApiController
    {
        private readonly AGVHandler _aGVHandler;
        private readonly IMQTTService _MQTTService;
        public AGVThirdPartyService(AGVHandler aGVHandler, IMQTTService MQTTService)
        {
            _aGVHandler = aGVHandler;
            _MQTTService = MQTTService;
        }

        /// <summary>
        /// 下发任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<KC_Response> Execute(KC_ExecuteRequest input)
        {
            List<KC_ExecuteRequest> cExecuteRequests = new();
            if (string.IsNullOrEmpty(input.RobotJobId))
            {
                throw Oops.Bah("任务编号不能为空");
            }
            if (input.JobData != null)
                input = new KC_ExecuteRequest
                {
                    Url =  string.IsNullOrEmpty(input.Url) ? App.GetConfig<string>("AGVUrl")+"/api/quicktron/wcs/standardized.robot.job.submit": input.Url + "/api/quicktron/wcs/standardized.robot.job.submit",
                    RobotJobId = input.RobotJobId,//任务号
                    WarehouseId = input.WarehouseId,//仓库编码 默认值1
                    JobPriority = input.JobPriority, //优先级 0-99 越高越先执行
                    JobPriorityType = input.JobPriorityType, //优先级类型 0 普通和1 强制.  
                    JobType = input.JobType,//任务类型 用来滚筒点对点 POINT_ROLLER_MOVE n8H7jX
                    JobData = new KC_JobDataRequest
                    {
                        StartPoint = input.JobData.StartPoint, //起点
                        EndPoint = input.JobData.EndPoint,//终点
                        ContainerCode = input.JobData.ContainerCode,//桶号
                        AutoLoad = input.JobData.AutoLoad,//上料方式 自动/人工
                        EnableIOLoad = input.JobData.EnableIOLoad,//上料交互方式 //接口对接 false
                        AutoUnload = input.JobData.AutoUnload,//下料方式 true自动/false人工
                        EnableIOUnload = input.JobData.EnableIOUnload,//接口对接 false
                        LoadEquipmentId = input.JobData.LoadEquipmentId,//起点设备ID
                        UnloadEquipmentId = input.JobData.UnloadEquipmentId,//目标设备ID
                    }
                };
            cExecuteRequests.Add(input);
            try
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:{input.RobotJobId}接收到下发任务!");
                var res = await input.Url.SetBody(cExecuteRequests).PostAsStringAsync();
                return JSON.Deserialize<KC_Response>(res);
            }
            catch (Exception ex)
            {
                throw Oops.Bah(ex.Message);
            }
        }
        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="kCCancelRequest"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<KCResponse> Cancel(KCCancelRequest kCCancelRequest)
        {
            kCCancelRequest.Url = string.IsNullOrEmpty(kCCancelRequest.Url) ? App.GetConfig<string>("AGVUrl") + "/api/quicktron/wcs/standardized.robot.job.cancel" : kCCancelRequest.Url + "/api/quicktron/wcs/standardized.robot.job.cancel";
            return await _aGVHandler.CancelAsync(kCCancelRequest);
        }
        /// <summary>
        /// 上下料反馈给AGV接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<RollerJobResponse> RollerJobExecute(Roller_JobRequest input)
        {
            //http://[IP:Port]/api/quicktron/wcs/standardized.roller.job.upstream.response
            input.Url = string.IsNullOrEmpty(input.Url) ? App.GetConfig<string>("AGVUrl") + "/api/quicktron/wcs/standardized.roller.job.upstream.response": input.Url+ "/api/quicktron/wcs/standardized.roller.job.upstream.response";
            try
            {
                var res = await input.Url.SetBody(input).PostAsStringAsync();
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:{input.JobId}上下料反馈给AGV接口!{res}");
                return JSON.Deserialize<RollerJobResponse>(res);
            }
            catch (Exception ex)
            {
                return new RollerJobResponse() { Success = false };
            }
        }
        /// <summary>
        /// 任务反馈（暴露给AGV厂商）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<AgvBody> ExecuteReply(AGVExecuteReplyRequest input)
        {
            try
            {
                var data = new AGVExecuteReplyMQTT()
                {
                    Event = input.Body.Event,
                };
                bool res = await _MQTTService.MqttPublish(new MqttPublishDto(){ Payload= data, Topic = Topics.ExecuteReplyTopic, MessageId = MessageID.TaskState });
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:接收到AGV反馈请求!", res.ToString());
                AgvBody agvBody = new()
                {
                    Header = input.Header,
                    Body = new AgvRetrun { Code = "SUCCESS", Success = res, Message = "SUCCESS", Data = null }
                };
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:AGV反馈消息!{JSON.Serialize(agvBody)}");
                return agvBody;
            }
            catch (Exception ex)
            {
                AgvBody agvBody = new()
                {
                    Header = input.Header,
                    Body = new AgvRetrun { Code = "SUCCESS", Success = false, Message = ex.Message, Data = null }
                };
                return agvBody;
            }
        }
        /// <summary>
        /// AGV上下料交互请求 （暴露给AGV厂商）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost, AGV]
        public async Task<AgvBody> LoadAndUnload(AGVLoadAndUnloadRequest input)
        {
            try
            {
                var data = new AGVLoadAndUnloadMQTT()
                {
                    Event = input.Body.Event,
                };
                bool res = await _MQTTService.MqttPublish(new MqttPublishDto() { Payload= data, Topic = Topics.LoadAndUnloadTopic, MessageId = MessageID.LoadAndUnload });
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:接收到AGV上下料交互请求!{res.ToString()}");
                AgvBody agvBody = new()
                {
                    Header = input.Header,
                    Body = new AgvRetrun { Code = "SUCCESS", Success = res, Message = "SUCCESS", Data = null }
                };
                return agvBody;
            }
            catch (Exception ex)
            {
                AgvBody agvBody = new()
                {
                    Header = input.Header,
                    Body = new AgvRetrun { Code = "SUCCESS", Success = false, Message = ex.Message, Data = null }
                };
                return agvBody;
            }
        }
    }
}
