WebApiClient.cs 14.7 KB
using Newtonsoft.Json;
using OfficeOpenXml.Drawing.Chart;
using RCS.Model.Comm;
using RCS.Model.Entity;
using RCS.Model.WebApi.Respose;
using RCS.WinClient.WebApi.Common;
using RestSharp;
using System.Data;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Documents;
using static RCS.Model.Comm.EnumMsg;

namespace RCS.WinClient.WebApi.Client
{
    public class WebApiClient
    {
        private static HttpClient client = new HttpClient();
        private static string url = App.AppConfig.ToWebApi;// ConfigurationManager.AppSettings["ToWebApi"];
        private static string iotUrl = App.AppConfig.ToIOTApi;// ConfigurationManager.AppSettings["ToWebApi"];
        private static RestClient iotClient = new RestClient(iotUrl, configureSerialization: x => new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true // 可选,用于更具可读性的输出
        });

        /// <summary>
        /// 返回给上层系统结果
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="requestUri"></param>
        /// <returns></returns>
        private static BllResult FormPost(object obj, string requestUri)
        {
            try
            {
                requestUri = url + requestUri;
                var json = JsonConvert.SerializeObject(obj);
                HttpContent content = GetTextContent(obj);

                var tk = App.AppConfig!.WMSToken;
                client.DefaultRequestHeaders.Add("token", tk);

                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                var ret = client.PostAsync(requestUri, content).Result;
                if (ret.IsSuccessStatusCode)
                {
                    ret.EnsureSuccessStatusCode();
                    string temp = ret.Content.ReadAsStringAsync().Result;
                    //LogExecute.logNet.WriteDebug($"请求WMS接口{url}成功,返回值:{temp}");
                    App.ExFile.MessageWebApi("AcsWebApiMsg", $"请求接口【{requestUri}】发送数据【{json}】成功,返回值:{temp} \r");
                    client.DefaultRequestHeaders.Clear();
                    //var serializerSettings = new JsonSerializerSettings
                    //{
                    //    // 设置为驼峰命名
                    //    ContractResolver = new CamelCasePropertyNamesContractResolver()
                    //};
                    var result = JsonConvert.DeserializeObject<ApiResultModel>(temp);

                    if (result.Status || result.State)
                    {
                        return BllResult.Success(null, result.Message);
                    }
                    //else if (result.state)
                    //{
                    //    //token验证失败,重新登陆
                    //    return BllResult.Error(null, b.message);
                    //}
                    else
                    {
                        return BllResult.Error(null, $"请求成功,但上游系统报错:{result.Message}");
                    }
                }
                else
                {
                    App.ExFile.MessageWebApi("AcsWebApiError", $"请求接口【{requestUri}】发送数据【{json}】失败,原因:{ret.StatusCode}\r");
                    return BllResult.Error(null, $"请求失败,请检查网络连接,详情:{ret.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                App.ExFile.MessageWebApi("AcsWebApiError", $"请求接口【{requestUri}】出现异常,原因:{ex.Message}\r  堆栈:{ex.StackTrace} \r");
                return BllResult.Error(null, $"请求失败,请检查网络连接或者重启本程序,详情:{ex.Message}");
            }
        }

        private static BllResult<T> FormPost<T>(object obj, string requestUri)
        {
            try
            {
                requestUri = url + requestUri;
                HttpContent content = GetTextContent(obj);
                var ret = client.PostAsync(requestUri, content).Result;
                if (ret.IsSuccessStatusCode)
                {
                    ret.EnsureSuccessStatusCode();
                    string temp = ret.Content.ReadAsStringAsync().Result;
                    var b = JsonConvert.DeserializeObject<ApiResultModel<T>>(temp);
                    if (b.State) //(b.State == true) //(b.Code == System.Net.HttpStatusCode.OK) (code == HttpStatusCode.OK)
                    {
                        return BllResult<T>.Success(b.Data, b.Message);
                    }
                    else
                    {
                        return BllResult<T>.Error(default(T), b.Message);
                    }
                }
                else
                {
                    return BllResult<T>.Error(default(T), "请求WMS失败,请检查网络连接");
                }
            }
            catch (Exception ex)
            {
                return BllResult<T>.Error(default(T), "请求WMS失败,请检查网络连接或者重启本程序" + ex.Message);
            }
        }

        private static HttpContent GetTextContent(Object obj)
        {
            string json = JsonConvert.SerializeObject(obj);
            HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
            return content;
        }

        /// <summary>
        /// RCS任务回传WMS
        /// </summary>
        /// <param name="task"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static BllResult ToWebApiTaskRefresh(Base_Task task, int status)
        {
            ResTaskConfirm taskConfirm = new ResTaskConfirm()
            {
                TaskNo = task.TaskNo,
                state = status
            };
            return FormPost(taskConfirm, "/TaskRefresh");
        }

        /// <summary>
        /// 任务状态回传
        /// </summary>
        /// <param name="linkAgv"></param>
        /// <returns></returns>
        public static BllResult ToAcsWebApiTaskState(Base_Task task, int status)
        {

            //如果不是wms下发的任务,就不需要回传
            if (task.TaskGroup != EnumMsg.TaskGroup.WMS任务.ToString())
            {
                return BllResult.Success();
            }
            ResTaskConfirm taskConfirm = new ResTaskConfirm()
            {
                //原版
                //executeDate = task.BeginTime.ToString(),
                taskNo = task.TaskNo,
                carNo = task.TaskAgvNo,
                status = status,
                updateBy = "AGV",
                updatedTime = DateTime.Now,
                TaskNo = task.TaskNo,
                //适配周锋南方航空项目
                //agvNo = task.TaskAgvNo,// task.TaskAgvNo,
                //taskNo = task.TaskNo,
                //state = status
            };
            //var result = FormPost(taskConfirm, "/api/AGV/AGVTaskComplete");
            var result = FormPost(taskConfirm, "/wms/api/acs/notifyAGVTask");

            if (!result.IsSuccess)
            {
                result.Message = $"回传WMS任务完成失败,{result.Message}";
            }
            return result;
        }




        /// <summary>
        /// 获取可用输送线站台
        /// </summary>
        /// <param name="linkAgv"></param>
        /// <returns></returns>
        public static BllResult GetAvailableStation(Base_Task task)
        {

            //如果不是wms下发的任务,就不需要回传
            if (task.TaskGroup != EnumMsg.TaskGroup.WMS任务.ToString())
            {
                return BllResult.Success();
            }
            ResTaskConfirm taskConfirm = new ResTaskConfirm()
            {
                taskNo = task.TaskNo,
            };
            var result = FormPost(taskConfirm, "wms/api/acs/getToAgvPort");

            if (!result.IsSuccess)
            {
                result.Message = $"向WMS请求可用站台失败,{result.Message}";
            }
            return result;
        }


        /// <summary>
        /// 剪床请求入空托盘
        /// </summary>
        /// <param name="linkAgv"></param>
        /// <returns></returns>
        public static BllResult ToAcsWebApiCallContainer(int containerType, string port, int area, string warehouseCode)
        {
            ResTaskConfirm taskConfirm = new ResTaskConfirm()
            {
                containerType = containerType,
                port = port,
                area = 4,
                warehouseCode = "CS0001"
            };
            return FormPost(taskConfirm, "/wms/agv/agvCallEmptyOut");
        }

        /// <summary>
        /// 剪床请求入空托盘
        /// </summary>
        /// <param name="linkAgv"></param>
        /// <returns></returns>
        public static BllResult<string> GetEndBarcode(Base_Task task)
        {
            return BllResult<string>.Success("as", "");
            //ResTaskConfirm taskConfirm = new ResTaskConfirm()
            //{
            //    containerType = containerType,
            //    port = port,
            //    area = 4,
            //    warehouseCode = "CS0001"
            //};
            //return FormPost(taskConfirm, "/wms/agv/agvCallEmptyOut");
        }

        /// <summary>
        /// 給wms物料信息
        /// </summary>
        /// <param name="containerCode"></param>
        /// <param name="weight"></param>
        /// <param name="height"></param>
        /// <param name="formPort"></param>
        /// <returns></returns>
        public static BllResult ToWMSContainerInfo(string containerCode, double weight, double height, string formPort)
        {
            containerCode = containerCode.Replace("\0", "").Trim();
            formPort = App.StationList.Find(X => X.Name == formPort)?.Code ?? throw new Exception("站台编码不匹配");
            var req = new
            {
                containerCode,
                weight,
                height,
                formPort,
                warehouseCode = "CS0001"
            };
            return FormPost(req, "/wms/agv/weightAndHeightByContainer");
        }

        /// <summary>
        /// 发送IOT数据
        /// </summary>
        /// <returns></returns>
        public static BllResult SendAGVInfoToIot()
        {
            try
            {
                var data = new List<IOTApiRequestModel>();
                IOTApiRequestModel model;
                object temp;
                Base_PathPoint? nextPathPoint;
                List<TagItem> list;
                foreach (var agv in App.AgvList)
                {
                    model = new IOTApiRequestModel(Guid.NewGuid().ToString(), agv.SN, DateTimeOffset.UtcNow.ToUnixTimeSeconds(), "", 1);

                    data.Add(model);
                    nextPathPoint = agv.PathPointList.Skip(1).FirstOrDefault();
                    temp = new
                    {
                        agv.AgvNo,
                        AgvType = (int)agv.AgvType,
                        agv.Speed,
                        CurrentBarcode = agv.Barcode,
                        agv.AgvHeight,
                        //InStock=(int)agv.InStock,
                        Direction = (int)agv.AgvDirection,
                        DialDirection = (int)agv.DialDirection,
                        Status = (int)agv.AgvState,
                        RadarStatus = (int)agv.RadarStatus,
                        Battery = agv.Voltage,
                        agv.RadarArea,
                        agv.IsOnline,
                        CoordX = agv.XLength,
                        CoordY = agv.YLength,
                        agv.Error,
                        RollerState = (int)agv.RollerState,
                        agv.FrontBarcode,
                        AfterBarcode = nextPathPoint == null ? "" : nextPathPoint.Barcode,
                    };
                    var props = temp.GetType().GetProperties();
                    list = new List<TagItem>();
                    foreach (var item in props)
                    {
                        list.Add(new TagItem(item.Name, item.GetValue(temp)?.ToString()));
                    }
                    model.Reported = list;
                }

                var result = SendIotPostRequest<IOTApiResultModel>("/SendEquipmentData", data);
                return new BllResult(result.IsSuccess, result.Message, result.Data);
            }
            catch (Exception ex)
            {
                App.ExFile.MessageError("SendAGVInfoToIot", $"发送数据到IOT异常,原因:{ex}");
                return BllResult.Error($"发送数据到IOT异常,原因:{ex.Message}");
            }
        }

        /// <summary>
        /// 更新客户端在线状态
        /// </summary>
        /// <returns></returns>
        public static BllResult UpdateClientStatus()
        {
            var data = new
            {
                ClientId = "9E9D0CFF-AB52-4E80-AFB7-6436110D9247"
            };
            var result = SendIotPostRequest<IOTApiResultModel>("/UpdateClientStatus", data);
            return new BllResult(result.IsSuccess, result.Message, result.Data);

        }


        /// <summary>
        /// 发送IOT数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static BllResult<T> SendIotPostRequest<T>(string url, object data)
        {
            try
            {
                var request = new RestRequest(url, Method.Post);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Accept", "application/json");
                request.AddJsonBody(data);
                var json = System.Text.Json.JsonSerializer.Serialize(data);
                var res = iotClient.Execute<T>(request);
                var absoluteUri = iotClient.BuildUri(request).AbsoluteUri;
                if (!res.IsSuccessful)
                {
                    return BllResult<T>.Error($"发送数据到IOT接口【{absoluteUri}】失败,错误码【{res.StatusCode}】,错误信息【{res.ErrorMessage}】");
                }
                if (res.Data == null)
                {
                    return BllResult<T>.Error($"发送数据到IOT接口【{absoluteUri}】是把,接口返回空");
                }
                App.ExFile.MessageWebApi("SendAGVInfoToIot", $"发送数据【{json}】到IOT接口【{absoluteUri}】成功!");
                return BllResult<T>.Success(res.Data);
            }
            catch (Exception ex)
            {
                return BllResult<T>.Error($"发送数据到IOT接口,发生异常,原因:{ex}");
            }

        }


    }
}