using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Serilog;
using SlnMesnac.Config;
using SlnMesnac.Model.dto;
using SlnMesnac.Plc;
using SlnMesnac.TouchSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TouchSocket.Sockets;

namespace SlnMesnac.Extensions
{
    public static class MesPlcSingalSetup
    {
        /// <summary>
        /// MES PLC 信号下发处理
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseMesPlcSingalHandleExtensions(this IApplicationBuilder app)
        {

            var plcFactories = app.ApplicationServices.GetService<List<PlcAbsractFactory>>();

            var _server = app.ApplicationServices.GetService<TcpServer>();

            _server.ReceivedClientBufferEvent += (client, buffer) =>
            {
                string asciiStr = Encoding.ASCII.GetString(buffer);
                Log.Information($"收到客户端指令:{asciiStr}");
                var request = JsonConvert.DeserializeObject<MesPlcHandleRequest>(asciiStr);

                if(request != null )
                {
                    var plc = plcFactories.Where(x => x.ConfigKey == "mesSingal").First();
                    var result = SingaleHandle(plc, request.stationNo);

                    var resultJson = JsonConvert.SerializeObject(result);

                    client.Send(resultJson);
                }
            };

            _server.Init(6000);

            // 启动UDP
            var udpSession = app.ApplicationServices.GetService<UdpServer>();
            udpSession.Init(3000);
        //    udpSession.Init(7749);
            return app;
        }


        /// <summary>
        /// 信号处理
        /// </summary>
        /// <param name="plcPool"></param>
        /// <param name="stationId"></param>
        /// <returns></returns>
        private static MesPlcHandleResponse SingaleHandle(PlcAbsractFactory _plc, int stationId)
        {

            MesPlcHandleResponse response = new MesPlcHandleResponse()
            {
                code = 500
            };

            bool res = false;
            try
            {

                if (_plc == null)
                {
                    throw new ArgumentException("PLC连接信息为空");
                }

                res = _plc.writeInt16ByAddress("M200", stationId);

                if (res)
                {
                    response.code = 200;
                    response.message = "下发成功";
                }
                else
                {
                    response.message = "下发失败";
                }
            }
            catch (Exception ex)
            {
                response.message = $"MES信号处理异常:{ex.Message}";
            }
            finally
            {
                response.isFlag = res;
                DateTime currentTimeUtc = DateTime.UtcNow;
                long unixTimeStamp = ((DateTimeOffset)currentTimeUtc).ToUnixTimeSeconds();
                response.timestamp = unixTimeStamp;
            }

            return response;
        }
    }
}