using MaxCommunication.DataBase.Document;
using PmsSecondaryPackaging.Interface.Model.Carrier;
using PmsSecondaryPackaging.Interface.Model.TaskBook;
using ProjectManagementSystem.Common.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using Pms.DataLibrary.Models;
using ProjectManagementSystem.NHibernateDBHelper;

namespace Pms.WebHandle
{
    [ServiceContract(Name = "TCLTrumpRestFullService")]
    public interface ISKTrumpRestFullService
    {
        /// <summary>
        /// 获取所有的站点
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        [WebGet(UriTemplate = "?OrderID={OrderID}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Json)]
        string GetOrder(string OrderID);


        [OperationContract]//对应接口编号001
        [WebInvoke(Method = "POST", UriTemplate = "TaskDownload", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        SKClentOrderResponse TaskDownload(SKClentOrder orderRequest);

        [OperationContract]//对应接口编号001
        [WebInvoke(Method = "POST", UriTemplate = "TaskCancel", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        ClentOrderCancelResponse TaskCancel(ClentOrderCancel wmsorderRequest);

        [OperationContract]//对应接口编号001
        [WebInvoke(Method = "POST", UriTemplate = "TaskRedirection", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        ClentOrderRedirectionResponse TaskRedirection(ClentOrderRedirection wmsorderRequest);

        /// <summary>
        /// 获取站点信息
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "?CancelOrderID={OrderID}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Json)]
        string CancelOrder(string OrderID);

        /// <summary>
        /// 释放小车，用于在完成工作后释放指定的小车。当找到小车时，会返回小车等信息
        /// </summary>
        /// <returns>失败编码 0 成功</returns>
        [OperationContract]
        [WebGet(UriTemplate = "ReleaseAGV/{agvID}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string ReleaseAGV(string agvID);
    }


    public class SKTrumpRestFullService : ISKTrumpRestFullService
    {
        public SKClentOrderResponse TaskDownload(SKClentOrder orderRequest)
        {
            SKClentOrderResponse tCLClentOrderResponse = new SKClentOrderResponse();
            try
            {
                if (orderRequest != null)
                {
                    //
                    int.TryParse(orderRequest.agvid, out int tempAgvId);
                    using (var session = MiddleDBModelHelper.Session)
                    {
                        var result = session.QueryOver<Order>().Where(p => p.Material == orderRequest.taskid).List();
                        if (result.Count > 0)
                        {
                            tCLClentOrderResponse.code = string.Format("已存在任务号:{0} 的任务!", orderRequest.taskid);
                            TextDocument.WriteFile(@"PMS/Log", "OrderRequest", tCLClentOrderResponse.code);
                            return tCLClentOrderResponse;
                        }
                        Order tempOrder = new Order(DateTime.Now.ToString("yyyyMMddhhmmssffff") + "_" + orderRequest.taskid, (OrderType)0, orderRequest.source, "", orderRequest.target, -1, tempAgvId, orderRequest.taskid);
                        tempOrder.CallTime = DateTime.Now;
                        tempOrder.FinishTime = DateTime.MaxValue;
                        tempOrder.Suspend = false;
                        session.Save(tempOrder);
                        session.Flush();
                        tCLClentOrderResponse.code = "0";
                        tCLClentOrderResponse.taskid = orderRequest.taskid;
                        TextDocument.WriteFile(@"PMS/Log", "OrderRequest", string.Format("添加任务成功,taskid:{0},source:{1},target:{2},tasktype:{3},agvid:{4}!", orderRequest.taskid, orderRequest.source, orderRequest.target, 0, orderRequest.agvid));
                    }


                    //TaskAddInfoModel taskAddInfoModel = new TaskAddInfoModel();
                    //taskAddInfoModel.TaskID = orderRequest.taskid; //System.DateTime.Now.ToString("MMddhhmmssffff")
                    //taskAddInfoModel.TemplateName ="StandardTemplate1"; //orderRequest.tasktype
                    ////taskAddInfoModel.AgvType = "1";
                    ////int.TryParse(orderRequest.agvid, out int tempAgvId);
                    //taskAddInfoModel.AgvId = tempAgvId;
                    //Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    //dictionary.Add("M_R1", orderRequest.source);
                    //dictionary.Add("M1", orderRequest.source);
                    //dictionary.Add("M_R2", orderRequest.source);//两台车
                    //                                       //dictionary.Add("M2", curOrder.DownPos);
                    //dictionary.Add("ME_R1", orderRequest.target);
                    //taskAddInfoModel.ParametersDic = dictionary;
                    ////taskAddInfoModel.ParentTaskId = TaskID;
                    //PmsSecondaryPackaging.Interface.Service.InterfaceService interfaceService = new PmsSecondaryPackaging.Interface.Service.InterfaceService();
                    //if (interfaceService.GetCarrier(orderRequest.agvid,out CarrierInfoModel carrierInfoModel,out string message))
                    //{
                    //    //PmsApi.Get(EPmsApi.GetCarrier, new { },null,out  carrier)
                    //    if (!carrierInfoModel.Online)
                    //    {
                    //        //Pms.DataLibrary.Carrier.CarrierTask
                    //    }
                    //    else if(carrierInfoModel.AlarmList.Any(p=>p.alarmId!=0))
                    //    {

                    //    }
                    //}
                    //else
                    //{
                    //    //未找到小车
                    //}

                    //if (!interfaceService.TaskAdd(taskAddInfoModel, out string Message))
                    //{
                        
                    //    TextDocument.WriteFile(@"PMS/Log", "添加任务", Message);
                    //}
                    //else
                    //{
                    //    //curOrder.OrderState = (int)OrderState.None;
                    //    //session.Update(curOrder);
                    //    TextDocument.WriteFile(@"PMS/Log", "添加任务", "任务添加成功！");
                    //}
                    //TextDocument.WriteFile(@"PMS/Log","OrderRequest", string.Format("收到请求时间:{0},请求内容",DateTime.Now,JsonHelper.ConvertToJson(typeof(SKClentOrder),orderRequest)));
                }
                else
                {
                    TextDocument.WriteFile(@"PMS/Log","OrderRequest", "请求数据为空");
                    tCLClentOrderResponse.code = "请求数据为空";
                }
            }
            catch(Exception ex)
            {
                TextDocument.WriteFile(@"PMS/Log","OrderRequest", "处理请求数据异常:"+ex.ToString());
                tCLClentOrderResponse.code = "处理请求数据异常";
            }
            return tCLClentOrderResponse;
        }

       

        public ClentOrderCancelResponse TaskCancel(ClentOrderCancel orderRequest)
        {
            ClentOrderCancelResponse tCLClentOrderResponse = new ClentOrderCancelResponse();
            try
            {
                if (orderRequest != null)
                {
                    using (var session = MiddleDBModelHelper.Session)
                    {
                        var result = session.QueryOver<Order>().Where(p => p.Material == orderRequest.taskid).List();
                        if(result.Count<0)
                        {
                            tCLClentOrderResponse.code = "0";
                            return tCLClentOrderResponse;
                        }
                        Order tempOrder = result.First();
                        PmsSecondaryPackaging.Interface.Service.InterfaceService interfaceService = new PmsSecondaryPackaging.Interface.Service.InterfaceService();
                        if(interfaceService.TaskCancel(new TaskCancelInfoModel(tempOrder.OrderID, false), out string message))
                        {
                            tCLClentOrderResponse.code = "0";
                            return tCLClentOrderResponse;
                        }
                        else
                        {
                            tCLClentOrderResponse.code = message;
                            return tCLClentOrderResponse;
                        }
                    }
                }
                else
                {
                    TextDocument.WriteFile(@"PMS/Log","WMSOrderRequest", "请求数据为空");
                    tCLClentOrderResponse.code = "请求数据为空";
                }
            }
            catch (Exception ex)
            {
                TextDocument.WriteFile(@"PMS/Log","WMSOrderRequest", "处理请求数据异常:" + ex.ToString());
                tCLClentOrderResponse.code = "处理请求数据异常";
            }
            return tCLClentOrderResponse;
        }

        public ClentOrderRedirectionResponse TaskRedirection(ClentOrderRedirection wmsorderRequest)
        {
            ClentOrderRedirectionResponse tCLClentOrderResponse = new ClentOrderRedirectionResponse();
            try
            {
                if (wmsorderRequest != null)
                {

                }
                else
                {
                    TextDocument.WriteFile(@"PMS/Log", "WMSOrderRequest", "请求数据为空");
                    tCLClentOrderResponse.code = "请求数据为空";
                }
            }
            catch (Exception ex)
            {
                TextDocument.WriteFile(@"PMS/Log", "WMSOrderRequest", "处理请求数据异常:" + ex.ToString());
                tCLClentOrderResponse.code = "处理请求数据异常";
            }
            return tCLClentOrderResponse;
        }



        string[] RESULTS = { "OK", "RUN", "NG", "NEW" };
        public string CancelOrder(string OrderID)
        {
            string result = RESULTS[2];

            return result;
        }

        public string GetOrder(string OrderID)
        {
            string result = RESULTS[3];

            return result;
        }



        public string ReleaseAGV(string agvID)
        {
            string result = RESULTS[2];

            return result;
        }

        
    }
}

