using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Collections.Concurrent;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Net;
using System.Net.Http.Headers;
using System.IO;
using MisDataSaveDate;

namespace MisDataSaveDate
{
    /// <summary>
    /// AGV接口控制器
    /// </summary>
    public class AGVController : ApiController
    {
        readonly string headUrl = "agv/";

        /// <summary>
        /// AGV请求进入离开、下降举升接口（接收方）
        /// 接收AGV的进入、离开、下降、举升请求并存储到数据库
        /// </summary>
        /// <param name="jobj">AGV请求数据</param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [Route("agv/agvReqInOut")]
        public HttpResponseMessage agvReqInOut([FromBody] JObject jobj)
        {
            return new HttpResponseMessage
            {
                Content = new StringContent(AGV_BusinessLogic.ProcessAGVEnterRequest(headUrl + System.Reflection.MethodBase.GetCurrentMethod().Name, jobj), Encoding.GetEncoding("UTF-8"), "application/json")
            };
        }

        /// <summary>
        /// 临工AGV到达/离开状态回调接口。
        /// </summary>
        /// <param name="jobj">临工AGV状态回调数据</param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [Route("agv/lgagv/statusUpdate")]
        public HttpResponseMessage LGAGV_StatusUpdate([FromBody] JObject jobj)
        {
            return new HttpResponseMessage
            {
                Content = new StringContent(LGAGV_BusinessLogic.ProcessStatusUpdate(headUrl + System.Reflection.MethodBase.GetCurrentMethod().Name, jobj), Encoding.GetEncoding("UTF-8"), "application/json")
            };
        }

        /// <summary>
        /// 临工AGV任务结果回调接口。
        /// </summary>
        /// <param name="jobj">临工AGV任务结果数据</param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [Route("agv/lgagv/taskResult")]
        public HttpResponseMessage LGAGV_TaskResult([FromBody] JObject jobj)
        {
            return new HttpResponseMessage
            {
                Content = new StringContent(LGAGV_BusinessLogic.ProcessTaskResult(headUrl + System.Reflection.MethodBase.GetCurrentMethod().Name, jobj), Encoding.GetEncoding("UTF-8"), "application/json")
            };
        }

        [HttpPost]
        [Route("api/reportExternalBusinessTaskStatus")]
        public HttpResponseMessage TCS_ReportExternalBusinessTaskStatus([FromBody] JObject jobj)
        {
            return JsonResponse(TCSAGV_BusinessLogic.ProcessTaskStatus("api/reportExternalBusinessTaskStatus", jobj));
        }

        [HttpPost]
        [Route("api/mcrInfoLocation")]
        public HttpResponseMessage TCS_McrInfoLocation([FromBody] JObject jobj)
        {
            return JsonResponse(TCSAGV_BusinessLogic.ProcessPositionPush("api/mcrInfoLocation", jobj));
        }

        [HttpPost]
        [Route("agv/tcs/dispatchStation")]
        public HttpResponseMessage TCS_DispatchStation([FromBody] TCSAGV_StationDispatchRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                if (string.IsNullOrWhiteSpace(request.portCombination)) throw new Exception("请选择动作组合");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.DispatchStationTask(
                    request.stationCode, request.actionType, request.portCombination, "MANUAL", request.operatorCode,
                    request.parentExternalCode, false);
                return result.Success
                    ? TCSAGV_ApiResponse.Ok("任务下发成功", result)
                    : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/dispatchStep")]
        public HttpResponseMessage TCS_DispatchStep([FromBody] TCSAGV_StepDispatchRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.DispatchSingleStep(
                    request.stationCode, request.programName, request.operatorCode, request.parentExternalCode);
                return result.Success
                    ? TCSAGV_ApiResponse.Ok("单步任务下发成功", result)
                    : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/retry")]
        public HttpResponseMessage TCS_Retry([FromBody] TCSAGV_TaskOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.RetryTask(request.externalCode, request.operatorCode);
                return result.Success
                    ? TCSAGV_ApiResponse.Ok("整单重发成功", result)
                    : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/cancel")]
        public HttpResponseMessage TCS_Cancel([FromBody] TCSAGV_TaskOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.CancelTask(request.externalCode, request.operatorCode);
                return result.Success ? TCSAGV_ApiResponse.Ok("任务取消成功", result) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/stopPending")]
        public HttpResponseMessage TCS_StopPending([FromBody] TCSAGV_TaskOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                string externalCode = request == null ? "" : request.externalCode;
                string operatorCode = request == null ? "" : request.operatorCode;
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.StopPendingTasks(externalCode, operatorCode);
                return result.Success ? TCSAGV_ApiResponse.Ok("未开始任务已停止", result) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/reset")]
        public HttpResponseMessage TCS_Reset([FromBody] TCSAGV_RobotOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.ResetRobot(
                    request.externalCode, request.ip, request.operatorCode);
                return result.Success ? TCSAGV_ApiResponse.Ok("移动机器人复位成功", result) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/stopNow")]
        public HttpResponseMessage TCS_StopNow([FromBody] TCSAGV_RobotOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.StopNow(
                    request.externalCode, request.ip, request.operatorCode);
                return result.Success ? TCSAGV_ApiResponse.Ok("移动机器人已紧急停止", result) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/syncTask")]
        public HttpResponseMessage TCS_SyncTask([FromBody] TCSAGV_TaskOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.SyncTaskStatus(request.externalCode, request.operatorCode);
                return result.Success ? TCSAGV_ApiResponse.Ok("任务状态同步成功", result) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpGet]
        [Route("agv/tcs/queryRobot")]
        public HttpResponseMessage TCS_QueryRobot()
        {
            return ExecuteTcs(() =>
            {
                TCSAGV_CallResult result = TCSAGV_BusinessLogic.QueryRobotInfo();
                return result.Success ? TCSAGV_ApiResponse.Ok("机器人状态查询成功", result.Response) : TCSAGV_ApiResponse.Fail(result.Message);
            });
        }

        [HttpPost]
        [Route("agv/tcs/handleFailure")]
        public HttpResponseMessage TCS_HandleFailure([FromBody] TCSAGV_TaskOperationRequest request)
        {
            return ExecuteTcs(() =>
            {
                if (request == null) throw new Exception("请求参数不能为空");
                TCSAGV_BusinessLogic.HandleFailure(request.externalCode, request.operatorCode, request.remark, request.notifyPlc);
                return TCSAGV_ApiResponse.Ok("失败任务已人工处理");
            });
        }

        private static HttpResponseMessage ExecuteTcs(Func<TCSAGV_ApiResponse> action)
        {
            TCSAGV_ApiResponse response;
            try
            {
                response = action();
            }
            catch (Exception ex)
            {
                response = TCSAGV_ApiResponse.Fail(ex.Message);
            }
            return JsonResponse(JsonConvert.SerializeObject(response));
        }

        private static HttpResponseMessage JsonResponse(string json)
        {
            return new HttpResponseMessage
            {
                Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json")
            };
        }
    }
}
