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

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

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

            try
            {
                httpobj.Start();
            }
            catch(Exception ex)
            {
                Console.WriteLine();
            }
            //异步监听客户端请求，当客户端的网络请求到来时会自动执行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)
                {
                    //Console.WriteLine(request.RawUrl);
                    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)
        {
            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 "/agv/requestDilivery":
                        log = string.Format("AGV调用WCS    名称:requestDilivery    接口时间{0}:\n,内容:{1}\n", DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss:fff"), content);
                        LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
                        var reqTakeModel = HandleAgvRequest.takeDiliveryRequest(content);
                        return reqTakeModel;

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

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

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

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

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

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

                    default:
                        return "";
                }
            }
            catch (Exception ex)
            {
                response.StatusDescription = "404";
                response.StatusCode = 404;
                Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
                return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回
            }
        }

        public static string sendJsonToService(string url, string jsonmodel, string interfacename)
        {
            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);
            try
            {
               
                var wc = new WebClient();
                wc.Encoding = Encoding.UTF8;
                wc.Headers[HttpRequestHeader.ContentType] 
                    = "application/json";
                //wc.Headers[HttpRequestHeader.Authorization] = "767e4e1d144c7512f2c94d68e4236b61";
                wc.Headers.Add("appcode", "767e4e1d144c7512f2c94d68e4236b61");
                //wc.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                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)
            {
                log = string.Format("发送数据异常,异常信息为:{0}", ex.Message);
                LogUtil.WriteLogNoTime("D:\\AGV通讯日志", "", log);
            }
            return "";
        }
    }
}