using RGD.Common;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace RGD.HaiRouAPI
{
    public class HttpServer
    {
        private static HttpListener httpobj;

        public static void start()
        {
            httpobj = new HttpListener();
            //定义url及端口号，通常设置为配置文件
            var url = "http://192.168.0.12:17020/";
            httpobj.Prefixes.Add(url);
            httpobj.Start();

            //异步监听客户端请求，当客户端的网络请求到来时会自动执行Result委托
            //该委托没有返回值，有一个IAsyncResult接口的参数，可通过该参数获取context对象
            httpobj.BeginGetContext(Result, null);
        }

        public static void close()
        {
            httpobj.Close();
        }

        private static void Result(IAsyncResult ar)
        {
            try
            {
                httpobj.BeginGetContext(Result, null);
                var guid = Guid.NewGuid().ToString();
                var context = httpobj.EndGetContext(ar);
                var request = context.Request;
                var response = context.Response;
                context.Response.ContentEncoding = Encoding.UTF8;
                string returnObj = null;
                if (request.HttpMethod == "POST" && request.InputStream != null)
                {
                    returnObj = HandleRequest(request, response);
                }
                else
                {
                    returnObj = "不是POST请求或传入数据有误";
                }

                using (var stream = response.OutputStream)
                {
                    //把处理信息返回到客户端
                    response.AddHeader("Content-Type", "application/json");
                    byte[] returnByteArr = Encoding.UTF8.GetBytes(returnObj);
                    stream.Write(returnByteArr, 0, returnByteArr.Length);

                    stream.Close();
                    string log = string.Format("WCS返回AGV接口时间{0}:\n{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), returnObj);
                    LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                }
            }
            catch (Exception ex)
            {
            }
        }

        private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
        {
            string data = null;
            try
            {
                Stream stream = request.InputStream;
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string content = reader.ReadToEnd();
                string log = string.Format("AGV调用WCS接口时间{0}:\n{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                switch (request.RawUrl)
                {
                    case "/conveyor/taskStatusReport":
                        log = string.Format("AGV调用WCS    名称:taskStatusReport    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var tsrrmodel = HandleAgvRequest.taskStatueResponse(content);
                        return tsrrmodel;

                    case "/conveyor/errorMesReport":
                        log = string.Format("AGV调用WCS    名称:errorMesReport    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var ermrmodel = HandleAgvRequest.ErrorMesResponse(content);
                        return ermrmodel;

                    case "/conveyor/unloadContainerReq":
                        log = string.Format("AGV调用WCS    名称:unloadContainerReq    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var boxmodel = HandleAgvRequest.PutBoxApply(content);
                        return boxmodel;

                    case "/conveyor/unloadContainerFinish":
                        log = string.Format("AGV调用WCS    名称:unloadContainerFinish    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var boxfinmodel = HandleAgvRequest.PutBoxFinish(content);
                        return boxfinmodel;

                    case "/conveyor/loadContainerFinish":
                        log = string.Format("AGV调用WCS    名称:loadContainerFinish    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var takeboxmodel = HandleAgvRequest.TaskBoxFinish(content);
                        return takeboxmodel;

                    default:
                        return "";
                }
            }
            catch (Exception ex)
            {
                response.StatusDescription = "404";
                response.StatusCode = 404;
                Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
                return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回
            }
            response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
            response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"接收数据完成:{data.Trim()},时间：{DateTime.Now.ToString()}");
            return $"接收数据完成";
        }

        public static string sendJsonToService(string url, string jsonmodel, string interfacename)
        {
            try
            {
                string log = string.Format("WCS调用AGV   名称{2}    接口时间{0}:\n{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), jsonmodel, interfacename);
                LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                var wc = new WebClient();
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                var returnInfo = wc.UploadString(url, jsonmodel);

                log = string.Format("AGV返回接口时间{0}:\n{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), returnInfo);
                LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);

                return returnInfo;
            }
            catch (Exception ex)
            {
            }
            return "";
        }
    }
}