using MaxCommunication.DataBase.Document;
using PmsSecondaryPackaging.Electronic.Business;
using PmsSecondaryPackaging.Electronic.Model;
using PmsSecondaryPackaging.Entrance.Start;
using PmsSecondaryPackaging.Interface.Model.TaskBook;
using PmsSecondaryPackaging.WareHouse.Model;
using ProjectManagementSystem.Config;
using ProjectManagementSystem.TaskBookEvent;
using ProjectManagementSystem.WebApi.Service;
using ProjectManagementSystem.Common.Log;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ProjectManagementSystem.OrderLogic;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Core;
using System.Linq;
using DbCommon.Enties.DbModels;
using DbCommon.BusinessCore.BaseCore;
using ProjectManagementSystem.TaskEvent;
using ProjectManagementSystem.Common.Device;
using System.Configuration;
using System.Diagnostics;
using ProjectManagementSystem.WebApi;
using Pms.DataLibrary.Models;
using Pms.Models;
using ProjectManagementSystem.Common.WebApi;
using ProjectManagementSystem.NHibernateDBHelper;
using PmsSecondaryPackaging.Interface.Model.Carrier;
using System.ServiceModel.Web;
using Pms.WebHandle;

namespace ProjectManagementSystem.Enterance
{
    public class SystemEnterance : EntranceProgram
    {
        public WebApiServerHost webApiServerHost = new WebApiServerHost(true);
        private LocationPropertyManager m_locationManager = new LocationPropertyManager();

        public SystemEnterance()
        {
            OpService();
        }

        public override void InitSetting()
        {
            //WMSDBModelHelper.initialize(WMSAccessSetting.ConnectionString);
            MiddleDBModelHelper.initialize(MiddleDBAccessSetting.ConnectionString);
            CConfiManager.Init();
        }
        /// <summary>
        /// 开放WCF接口供第三方调用
        /// </summary>
        private void OpService()
        {
            //string url= UriSetting.g_ServiceUri; //AppSetting.GetString("InterFaceUrl")
            //SKTrumpRestFullService sk = new SKTrumpRestFullService();
            //WebServiceHost webServiceHost = new WebServiceHost(sk,new Uri(url));
            //webServiceHost.Open();

            try
            {
                WebServiceHost _serviceHost = new WebServiceHost(typeof(SKTrumpRestFullService), new Uri(UriSetting.g_ServiceUri));

                _serviceHost.Open();
                //CLog.Instance.WriteLog("WebService启动", "启动成功，Uri:" + UriSetting.g_ServiceUri);
                TextDocument.WriteFile(@"PMS/Log", "WebService启动", "启动成功，Uri:" + UriSetting.g_ServiceUri);

            }
            catch (Exception ex)
            {
                //CLog.Instance.WriteLog("WebService启动", "启动异常：" + ex.ToString());
                TextDocument.WriteFile(@"PMS/Log", "WebService启动", "启动异常：" + ex.ToString());

            }
        }
        public override void InitTaskBook()
        {
            TaskBookRegister taskBookRegister = new TaskBookRegister();
        }

        public override void TaskFactory()
        {
            CTaskEvent taskEvent = new CTaskEvent();
            COrderLogic orderLogic = COrderLogic.Instance;

            //string url = @"http://localhost:63300/api/Pms/SyncScaleData";
            //var result = ScaleApi.Post(url, null, new { scaleNo = "111" }, out string data);
            Task.Factory.StartNew(ScanCarriers);
            Task.Factory.StartNew(TaskThread);
        }

        private bool InitDataSource()
        {
            try
            {
                MaterialBindingManager materialBindingManager = new MaterialBindingManager();
                materialBindingManager.Init();
                return true;
            }
            catch (Exception ex)
            {
                CLog.Instance.GetLog("System").WriteException("Exception", ex);
            }
            return false;
        }

        private bool InitWareHouse()
        {
            try
            {
                if (!PmsApi.Get(EPmsApi.GetWarehouseListInfo, new { warehouseId = string.Empty }, null, out List<WarehouseInfo> whouseInfoList))
                {
                    return false;
                }

                var dataList = m_locationManager.GetList();
                foreach (var item in dataList)
                {
                    int findIndex = whouseInfoList.FindIndex(d => d.WareHouseID == item.LocationCode);
                    if (findIndex < 0)
                    {
                        //添加
                        var requestInfo = new RequestWarehouseInfo()
                        {
                            WareHouseID = item.LocationCode,
                            StationID = item.Mark,
                        };

                        PmsApi.Post(EPmsApi.AddWarehouse, null, requestInfo, out string dataString);
                    }
                    else
                    {
                        //更新
                        var requestInfo = whouseInfoList[findIndex];
                        if (requestInfo.StationID != item.Mark)
                        {
                            requestInfo.StationID = item.Mark;
                            PmsApi.Post(EPmsApi.UpdateWarehouse, null, requestInfo, out string dataString);
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                CLog.Instance.GetLog("System").WriteException("Exception", ex);
            }
            return false;
        }

        private void KillCurrentProcess(string logContext)
        {
            System.Windows.Forms.MessageBox.Show(logContext);
            System.Windows.Forms.Application.Exit();

            Process[] process = Process.GetProcesses();
            Process currentProcess = Process.GetCurrentProcess();
            for (int idx = 0; idx < process.Count(); idx++)
            {
                if (process[idx].ProcessName == currentProcess.ProcessName)
                {
                    process[idx].Kill();
                }
            }
            return;
        }

        private void ScanCarriers()
        {
            while (true)
            {
                try
                {
                    //if (interfaceService.GetAllCarrier(out List<CarrierInfoModel> carriers, out string message))
                    //{
                    //    foreach (CarrierInfoModel carrierInfoModel in carriers)
                    //    {
                    //        int SKCarrier = GlobalData.GetSKCarrier(carrierInfoModel.AgvID);

                    //    }
                    //}

                    if (PmsApi.Get(EPmsApi.GetAllCarrier, null, null, out ResultCarrierInfo resultCarrierInfo))
                    {

                        foreach (ResultAgvData resultAgvData in resultCarrierInfo.ResultAgvDataList)
                        {
                            int SKCarrier = GlobalData.GetSKCarrier(resultAgvData.AgvID);
                            AGVState aGVState = new AGVState();
                            aGVState.agvid = SKCarrier;
                            aGVState.power = resultAgvData.BatteryLevel;
                            aGVState.state = resultAgvData.Status;
                            aGVState.x = (int)resultAgvData.MovementX;
                            aGVState.y = (int)resultAgvData.MovementY;
                            string[] values = resultAgvData.OrderID!=null? resultAgvData.OrderID.Split('_') :new string[] { resultAgvData.OrderID };
                            string tempOrderId = values != null & values.Length > 1 ? values[1] : resultAgvData.OrderID;
                            aGVState.taskid = tempOrderId;
                            aGVState.updatetime = DateTime.Now.ToString("G");

                            SKMESWebServiceHelper.UpdateAGVState(aGVState);
                        }
                    }
                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    // CLog.Instance.GetLog("UpdateAGVState").WriteException("Exception", ex);
                    TextDocument.WriteFile(@"PMS/Log", "AGV状态上报异常", "异常：" + ex.ToString());
                }
            }      
        }
        public void TaskThread()
        {
            while (true)
            {
                Thread.Sleep(500);
                try
                {
                    #region 从中间表添加任务
                    try
                    {
                        using (var session = MiddleDBModelHelper.Session)
                        {
                            var result = session.QueryOver<Order>().Where(p => p.OrderState == -1).List();//.OrderBy(p => p.CallTime) p.OrderState == (int)OrderState.进车间风淋中 || p.OrderState == (int)OrderState.出车间风淋中 ||
                            foreach (var item in result)
                            {
                                Order curOrder = item;// result.First();
                                if (curOrder.OrderState == -1)
                                {
                                    int carrier = GlobalData.GetCasunCarrier(curOrder.Remain);
                                    //if (interfaceService.GetTaskDataList(out List<TaskDetailInfoModel> taskDetailInfoList, out string Message))
                                    //{
                                    //    if (taskDetailInfoList.Any(p => p.Carrier == carrier))
                                    //    {
                                    //        continue;
                                    //    }
                                    //}
                                    switch (carrier)
                                    {
                                        case 1:
                                        case 3:
                                            {
                                                //var r1 = session.QueryOver<Order>().Where(p => (p.OrderType == OrderType.五楼货物运送到电梯) && p.OrderState != -1 && p.OrderState != 255).List();
                                                //if (r1.Count > 0)
                                                //    continue;
                                                Pms.DataLibrary.Models.WarehouseInfo upwarehouseInfo = null;
                                                Pms.DataLibrary.Models.WarehouseInfo downwarehouseInfo = null;
                                                if (PmsApi.Get(EPmsApi.GetWarehouseListInfo, new { WarehouseID = curOrder.UpPos }, null, out List<Pms.DataLibrary.Models.WarehouseInfo> upwarehouseinfos))
                                                {
                                                    upwarehouseInfo = upwarehouseinfos != null && upwarehouseinfos.Count > 0 ? upwarehouseinfos.First() : upwarehouseInfo;
                                                }
                                                if (PmsApi.Get(EPmsApi.GetWarehouseListInfo, new { WarehouseID = curOrder.DownPos }, null, out List<Pms.DataLibrary.Models.WarehouseInfo> downwarehouseinfos))
                                                {
                                                    downwarehouseInfo = downwarehouseinfos != null && downwarehouseinfos.Count > 0 ? downwarehouseinfos.First() : downwarehouseInfo;
                                                }
                                                //upwarehouseInfo.GroupId
                                                TaskAddInfoModel taskAddInfoModel = new TaskAddInfoModel();
                                                taskAddInfoModel.TaskID = curOrder.OrderID; //System.DateTime.Now.ToString("MMddhhmmssffff")
                                                taskAddInfoModel.TemplateName = "StandardTemplate1";
                                                taskAddInfoModel.AgvId = carrier;
                                                taskAddInfoModel.AgvType = carrier == 1 ? "0" : "2";
                                                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                                dictionary.Add("U1", curOrder.UpPos);
                                                dictionary.Add("U2", curOrder.DownPos);
                                                taskAddInfoModel.ParametersDic = dictionary;
                                                //taskAddInfoModel.ParentTaskId = TaskID;

                                                if (!interfaceService.TaskAdd(taskAddInfoModel, out string MessageAdd1))//添加任务
                                                {
                                                    TextDocument.WriteFile(@"PMS/Log", "二维码F8叉车任务", MessageAdd1);
                                                }
                                                else
                                                {
                                                    curOrder.OrderState = (int)WCSOrderState.None;
                                                    session.Update(curOrder);
                                                    TextDocument.WriteFile(@"PMS/Log", "二维码F8叉车任务", "任务添加成功！");
                                                }
                                            }
                                            break;
                                        default:
                                            {
                                                //var r1 = session.QueryOver<Order>().Where(p => (p.OrderType == OrderType.五楼货物运送到电梯) && p.OrderState != -1 && p.OrderState != 255).List();
                                                //if (r1.Count > 0)
                                                //    continue;
                                                Pms.DataLibrary.Models.WarehouseInfo upwarehouseInfo = null;
                                                Pms.DataLibrary.Models.WarehouseInfo downwarehouseInfo = null;
                                                if (PmsApi.Get(EPmsApi.GetWarehouseListInfo, new { WarehouseID = curOrder.UpPos }, null, out List<Pms.DataLibrary.Models.WarehouseInfo> upwarehouseinfos))
                                                {
                                                    upwarehouseInfo = upwarehouseinfos != null && upwarehouseinfos.Count > 0 ? upwarehouseinfos.First() : upwarehouseInfo;
                                                }
                                                if (PmsApi.Get(EPmsApi.GetWarehouseListInfo, new { WarehouseID = curOrder.DownPos }, null, out List<Pms.DataLibrary.Models.WarehouseInfo> downwarehouseinfos))
                                                {
                                                    downwarehouseInfo = downwarehouseinfos != null && downwarehouseinfos.Count > 0 ? downwarehouseinfos.First() : downwarehouseInfo;
                                                }
                                                //upwarehouseInfo.GroupId
                                                
                                                TaskAddInfoModel taskAddInfoModel = new TaskAddInfoModel();
                                                taskAddInfoModel.TaskID = curOrder.OrderID; //System.DateTime.Now.ToString("MMddhhmmssffff")
                                                taskAddInfoModel.AgvId = carrier;
                                                taskAddInfoModel.AgvType = "1";
                                                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                                bool isnormal = true;
                                                if (upwarehouseInfo!=null&& downwarehouseInfo!=null)
                                                {
                                                    if(upwarehouseInfo.WareHouseName=="H0"&& downwarehouseInfo.WareHouseName == "H0")
                                                    {
                                                        taskAddInfoModel.TemplateName = "StandardTemplate3";
                                                        dictionary.Add("M1", curOrder.UpPos);
                                                        dictionary.Add("M2", curOrder.DownPos);
                                                        isnormal = false;
                                                    }
                                                    else if(upwarehouseInfo.WareHouseName == "H0")
                                                    {
                                                        taskAddInfoModel.TemplateName = "StandardTemplate4";
                                                        dictionary.Add("M1", curOrder.UpPos);
                                                        dictionary.Add("M2", curOrder.DownPos);
                                                        dictionary.Add("M_R3", curOrder.DownPos);
                                                        dictionary.Add("M_R4", curOrder.DownPos);
                                                        isnormal = false;
                                                        isnormal = false;
                                                    }
                                                    else if(downwarehouseInfo.WareHouseName == "H0")
                                                    {
                                                        taskAddInfoModel.TemplateName = "StandardTemplate5";
                                                        dictionary.Add("M_R1", curOrder.UpPos);
                                                        dictionary.Add("M1", curOrder.UpPos);
                                                        dictionary.Add("M_R2", curOrder.UpPos);//两台车
                                                                                               //dictionary.Add("M2", curOrder.DownPos);
                                                        dictionary.Add("M2", curOrder.DownPos);
                                                        isnormal = false;
                                                        isnormal = false;
                                                    }
                                                }
                                                if (isnormal)
                                                {
                                                    taskAddInfoModel.TemplateName = "StandardTemplate2";
                                                    dictionary.Add("M_R1", curOrder.UpPos);
                                                    dictionary.Add("M1", curOrder.UpPos);
                                                    dictionary.Add("M_R2", curOrder.UpPos);//两台车
                                                                                           //dictionary.Add("M2", curOrder.DownPos);
                                                    dictionary.Add("M2", curOrder.DownPos);
                                                    dictionary.Add("M_R3", curOrder.DownPos);
                                                    dictionary.Add("M_R4", curOrder.DownPos);
                                                }
                                                taskAddInfoModel.ParametersDic = dictionary;
                                                //taskAddInfoModel.ParentTaskId = TaskID;

                                                if (!interfaceService.TaskAdd(taskAddInfoModel, out string MessageAdd2))
                                                {
                                                    TextDocument.WriteFile(@"PMS/Log", "堆垛叉车任务", MessageAdd2);
                                                }
                                                else
                                                {
                                                    curOrder.OrderState = (int)WCSOrderState.None;
                                                    session.Update(curOrder);
                                                    TextDocument.WriteFile(@"PMS/Log", "堆垛叉车任务", "任务添加成功！");
                                                }
                                            }
                                            break;
                                    }
                                }
                                session.Flush();
                            }
                        }

                        //using (var session = MiddleDBModelHelper.Session)
                        //{
                        //    var result = session.QueryOver<Order>().Where(p => p.OrderState != -1 && p.OrderState != (int)OrderState.电梯缓存中 && p.Material == "是").List();//.OrderBy(p => p.CallTime) p.OrderState == (int)OrderState.进车间风淋中 || p.OrderState == (int)OrderState.出车间风淋中 ||
                        //    bool hasdeleted = false;
                        //    foreach (var item in result)
                        //    {
                        //        Order curOrder = item;// result.First();
                        //        if (curOrder.OrderState == 0)
                        //        {
                        //            session.Delete(curOrder);
                        //            hasdeleted = true;
                        //        }
                        //        else
                        //        {
                        //            //if(interfaceService.GetTask(curOrder.OrderID, out TaskDetailInfoModel taskDetailInfoModel, out string message)&& taskDetailInfoModel!=null)
                        //            {
                        //                TaskCancelInfoModel taskCancelInfoModel = new TaskCancelInfoModel(curOrder.OrderID, true);
                        //                interfaceService.TaskCancel(taskCancelInfoModel, out string msg);
                        //                curOrder.FinishTime = DateTime.Now;
                        //            }
                        //        }
                        //    }
                        //    if (hasdeleted)
                        //    {
                        //        session.Flush();
                        //    }
                        //}
                    }
                    catch (Exception ex)
                    {
                        //TextDocument.WriteFile(@"PMS/Log","从中间表加载任务", ex.ToString());
                    }
                    #endregion
                    //ElevatorFullTask();
                    Thread.Sleep(100);
                }
                catch (Exception e)
                {
                    //TextDocument.WriteFile(@"PMS/Log","启动任务线程", e.ToString());
                    // 写日志
                    Thread.Sleep(5000);
                }
            }
        }
        /// <summary>
        /// 1楼从电梯运出货物
        /// </summary>
        private void ElevatorFullTask()
        {
            bool existed = false;
            OrderType ordertype1 = OrderType.None;
            OrderType ordertype2 = OrderType.None;//五楼货物运送到电梯
            //MiddleDBModelHelper MiddleDBModelHelper0 = new MiddleDBModelHelper();
            using (var session = MiddleDBModelHelper.Session)
            {
                var result = session.QueryOver<Order>().Where(p => (p.OrderType == ordertype1 || p.OrderType == ordertype2) && p.OrderState != 255).List();
                if (result.Count > 0)
                {
                    existed = true;
                }
            }
            if (existed)
            {
                return;
            }
            using (var session = WMSDBModelHelper.Session)
            {
                var result = session.QueryOver<WareHouseLocation>().Where(p => p.WareHouseCode == "002" && p.Status == "2").List();
                if (result.Count > 0)
                {
                    bool sussess = false;
                    string orderid = "JL" + DateTime.Now.ToString("HHmmssffff");
                    string uppos = result[0].LocationCode;
                    string middlepos = "";//JudgeBC
                    string downpos = "1F_T1";
                    Order newOrder = new Order(orderid, OrderType.None, uppos, middlepos, downpos, (int)WCSOrderState.BindingAGV, 0);
                    //MiddleDBModelHelper MiddleDBModelHelper = new MiddleDBModelHelper();
                    using (var sessionMiddleDB = MiddleDBModelHelper.Session)
                    {
                        sessionMiddleDB.Save(newOrder);
                        sessionMiddleDB.Flush();
                        sussess = true;
                    }
                }
            }
            Thread.Sleep(1000);
        }

        /// <summary>
        /// 系统PLC对接，收到命令信号处理方法
        /// </summary>
        /// <param name="transmissionModel"></param>
        public override void ElectronicStatusUpdateDeal(ElectronicBaseBusiness electronicBaseBusiness, ElectronicMonitorModel electronicMonitorModel)
        {
            //TaskAddInfoModel taskAddInfoModel = new TaskAddInfoModel();
            //taskAddInfoModel.TaskID = DateTime.Now.ToString("yyyyMMddhhmmssffff");
            //taskAddInfoModel.TemplateName = "TaskBook_Electronic";
            //Dictionary<string, string> dictionary = new Dictionary<string, string>();
            //dictionary.Add("U1", "W1"); dictionary.Add("U2", "W8");
            //taskAddInfoModel.ParametersDic = dictionary;
            //if (!interfaceService.TaskAdd(taskAddInfoModel, out string Message))
            //{
            //    TextDocument.WriteFile(@"PMS/Log", "TaskError_", Message);
            //}
        }

        /// <summary>
        /// 库位检测，由空变满的处理方法
        /// </summary>
        /// <param name="wareHouseModel"></param>
        public override void WareHouseStatusUpdateDeal(WareHouseModel wareHouseModel, WareHouseMonitorModel wareHouseMonitorModel)
        {
            //TaskAddInfoModel taskAddInfoModel = new TaskAddInfoModel();
            //taskAddInfoModel.TaskID = DateTime.Now.ToString("yyyyMMddhhmmssffff");
            //taskAddInfoModel.TemplateName = "TaskBook_Electronic";
            //Dictionary<string, string> dictionary = new Dictionary<string, string>();
            //dictionary.Add("U1", wareHouseModel.LocationCode); dictionary.Add("U2", "W8");
            //taskAddInfoModel.ParametersDic = dictionary;
            //if (!interfaceService.TaskAdd(taskAddInfoModel, out string Message))
            //{
            //    TextDocument.WriteFile(@"PMS/Log", "TaskError_", Message);
            //}
        }
    }
}

