using Application.Interface;
using Application.PdaDto;
using Jc.SnowId;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto.taskType;
using SlnMesnac.Model.dto.webapi;
using SlnMesnac.Serilog;
using SqlSugar;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;

namespace Application
{
    public class WcsTaskApplication : IWcsTaskApplication
    {
        private static readonly JcSnowId _snowId = new JcSnowId();
        private readonly SerilogHelper _logger;
        private ISqlSugarClient? sqlSugarClient;

        public WcsTaskApplication(IServiceProvider serviceProvider, ISqlSugarClient _sqlSugarClient)
        {
            _logger = serviceProvider.GetRequiredService<SerilogHelper>();
            sqlSugarClient = _sqlSugarClient;
            // sqlSugarClient = serviceProvider.GetRequiredService<ISqlSugarClient>();
        }

        /// <summary>
        /// 接收agv接收任务通知接口
        //in : 小料箱到达起点接驳位里面，agv通知wcs，请求退出接驳位
        //start 取完料开始前往终点
        //wait: agv到达等待点，通知wcs判断能否进接驳位
        //out: 小料箱到达终点接驳位里面，agv通知wcs，请求退出接驳位
        //end：任务结束
        /// </summary>
        /// <param name="agvCallbackDto"></param>
        /// <returns></returns>
        public ReponseagvCallbackDto AgvCallback(agvCallbackDto agvCallbackDto)
        {
            ReponseagvCallbackDto reponseagvCallbackDto = new ReponseagvCallbackDto();
            try
            {
                WcsTask? wcsTask = sqlSugarClient.Queryable<WcsTask>().First(t => t.TaskCode == agvCallbackDto.taskCode);
                WcsTaskLog? wcsTaskLog = null;
                if (wcsTask != null)
                {
                    wcsTaskLog = sqlSugarClient.Queryable<WcsTaskLog>().First(t => t.Id == wcsTask.Id);
                }
                sqlSugarClient.AsTenant().BeginTran();
                if (wcsTask != null)
                {
                    //任务赋值执行agv字段
                    wcsTask.NextPointNo = agvCallbackDto.robotCode;
                    if (wcsTaskLog != null)
                    {
                        wcsTaskLog.NextPointNo = agvCallbackDto.robotCode;
                    }
                    //待取货
                    if (agvCallbackDto.method.ToLower() == "in")
                    {
                        if (wcsTask.TaskType == StaticTaskType.TransferMaterialMetrologyRoomBoxTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletTask
                             || wcsTask.TaskType == StaticTaskType.DeliverTonerTask)
                        {
                            wcsTask.TaskStatus = 2;
                            sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                            if (wcsTaskLog != null)
                            {
                                wcsTaskLog.TaskStatus = wcsTask.TaskStatus;
                                sqlSugarClient.Updateable(wcsTaskLog).ExecuteCommand();
                            }
                        }
                        reponseagvCallbackDto.code = "0";
                        reponseagvCallbackDto.message = "成功";
                    }
                    //起点取完
                    if (agvCallbackDto.method.ToLower() == "start")
                    {
                        if (wcsTask.TaskType == StaticTaskType.SupplyEmptyPalletTask || wcsTask.TaskType == StaticTaskType.TransferMaterialBoxTask
                            || wcsTask.TaskType == StaticTaskType.MoveLocationTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletFromTonerTask
                            || wcsTask.TaskType == StaticTaskType.EmptyReturnFromTonerTask || wcsTask.TaskType == StaticTaskType.ExceptionTask)
                        {
                            wcsTask.TaskStatus = 2;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.TransferMaterialMetrologyRoomBoxTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletTask
                            || wcsTask.TaskType == StaticTaskType.DeliverTonerTask)
                        {
                            wcsTask.TaskStatus = 4;
                        }
                        sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                        if (wcsTaskLog != null)
                        {
                            wcsTaskLog.TaskStatus = wcsTask.TaskStatus;
                            sqlSugarClient.Updateable(wcsTaskLog).ExecuteCommand();
                        }
                        reponseagvCallbackDto.code = "0";
                        reponseagvCallbackDto.message = "成功";
                    }

                    if (agvCallbackDto.method.ToLower() == "wait")
                    {
                        if (wcsTask.TaskType == StaticTaskType.TransferMaterialMetrologyRoomBoxTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletTask)
                        {
                            wcsTask.TaskStatus = 6;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.SupplySmallPalletFromTonerTask || wcsTask.TaskType == StaticTaskType.EmptyReturnFromTonerTask)
                        {
                            wcsTask.TaskStatus = 4;
                        }
                        sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                        if (wcsTaskLog != null)
                        {
                            wcsTaskLog.TaskStatus = wcsTask.TaskStatus;
                            sqlSugarClient.Updateable(wcsTaskLog).ExecuteCommand();
                        }
                        reponseagvCallbackDto.code = "0";
                        reponseagvCallbackDto.message = "成功";
                    }
                    if (agvCallbackDto.method.ToLower() == "out")
                    {
                        if (wcsTask.TaskType == StaticTaskType.TransferMaterialMetrologyRoomBoxTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletTask)
                        {
                            wcsTask.TaskStatus = 8;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.SupplySmallPalletFromTonerTask || wcsTask.TaskType == StaticTaskType.EmptyReturnFromTonerTask)
                        {
                            wcsTask.TaskStatus = 6;
                        }
                        sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                        if (wcsTaskLog != null)
                        {
                            wcsTaskLog.TaskStatus = wcsTask.TaskStatus;
                            sqlSugarClient.Updateable(wcsTaskLog).ExecuteCommand();
                        }
                        reponseagvCallbackDto.code = "0";
                        reponseagvCallbackDto.message = "成功";
                    }
                    //放货完成
                    if (agvCallbackDto.method.ToLower() == "end")
                    {
                        if (wcsTask.TaskType == StaticTaskType.SupplyEmptyPalletTask || wcsTask.TaskType == StaticTaskType.TransferMaterialBoxTask
                            || wcsTask.TaskType == StaticTaskType.MoveLocationTask || wcsTask.TaskType == StaticTaskType.ExceptionTask)
                        {
                            wcsTask.TaskStatus = 4;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.TransferMaterialMetrologyRoomBoxTask || wcsTask.TaskType == StaticTaskType.SupplySmallPalletTask)
                        {
                            wcsTask.TaskStatus = 10;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.SupplySmallPalletFromTonerTask || wcsTask.TaskType == StaticTaskType.EmptyReturnFromTonerTask)
                        {
                            wcsTask.TaskStatus = 8;
                        }
                        else if (wcsTask.TaskType == StaticTaskType.DeliverTonerTask)
                        {
                            wcsTask.TaskStatus = 6;
                        }
                        sqlSugarClient.Updateable(wcsTask).ExecuteCommand();
                        if (wcsTaskLog != null)
                        {
                            wcsTaskLog.TaskStatus = wcsTask.TaskStatus;
                            sqlSugarClient.Updateable(wcsTaskLog).ExecuteCommand();
                        }
                        reponseagvCallbackDto.code = "0";
                        reponseagvCallbackDto.message = "成功";
                    }
                }
                else
                {
                    reponseagvCallbackDto.code = "1";
                    reponseagvCallbackDto.message = "未找到当前任务";
                }
            }
            catch (Exception ex)
            {
                sqlSugarClient!.AsTenant().CommitTran();
                _logger.Error(ex.Message);
                reponseagvCallbackDto.code = "1";
                reponseagvCallbackDto.message = ex.Message;
            }
            sqlSugarClient!.AsTenant().CommitTran();
            //返回请求
            reponseagvCallbackDto.reqCode = reponseagvCallbackDto.reqCode;
            return reponseagvCallbackDto;
        }

        /// <summary>
        /// MES核减条码数量通知
        /// </summary>
        /// <param name="mesRequest"></param>
        /// <returns></returns>
        //public ReponseagvCallbackDto MesReduction(MesRequest mesRequest)
        //{
        //    ReponseagvCallbackDto reponseagvCallbackDto = new ReponseagvCallbackDto();
        //    try
        //    {
        //        WmsPalletInfo? palletInfo = sqlSugarClient.Queryable<WmsPalletInfo>().First(t => t.Barcode == mesRequest.barcode);
        //        if (palletInfo != null)
        //        {
        //            sqlSugarClient.Deleteable(palletInfo).ExecuteCommand();
        //            reponseagvCallbackDto.code = "200";
        //            reponseagvCallbackDto.message = "核减成功";
        //        }
        //        else
        //        {
        //            reponseagvCallbackDto.code = "301";
        //            reponseagvCallbackDto.message = "核减失败:未找到条码库存";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //sqlSugarClient!.AsTenant().CommitTran();
        //        _logger.Error(ex.Message);
        //        reponseagvCallbackDto.code = "301";
        //        reponseagvCallbackDto.message = "核减失败:" + ex.Message;
        //    }
        //    reponseagvCallbackDto.reqCode = mesRequest.reqCode;
        //    return reponseagvCallbackDto;
        //}

        /// <summary>
        /// 根据库位编号获取托盘编号及库存信息
        /// </summary>
        public PadResponse GetLocationInfo(List<string> locationCodes)
        {
            PadResponse padResponse = new PadResponse();
            try
            {
                List<WmsBaseLocation> wmsBaseLocations = sqlSugarClient.Queryable<WmsBaseLocation>().Where(t => locationCodes.Contains(t.LocationCode)).ToList();
                List<LocationInfo> locationInfos = new List<LocationInfo>();
                foreach (string locationCode in locationCodes)
                {
                    WmsBaseLocation? location = wmsBaseLocations.FirstOrDefault(x => x.LocationCode == locationCode);
                    if (location != null && !string.IsNullOrEmpty(location.ContainerCode))
                    {
                        WmsPalletInfo wmsPalletInfo = sqlSugarClient.Queryable<WmsPalletInfo>().Where(t => t.PalletInfoCode == location.ContainerCode).First();
                        LocationInfo locationInfo = new LocationInfo();
                        locationInfo.LocationCode = locationCode;
                        locationInfo.PalletInfoCode = wmsPalletInfo.PalletInfoCode;
                        locationInfo.Amount = wmsPalletInfo.Amount;
                        locationInfos.Add(locationInfo);
                    }
                    else
                    {
                        LocationInfo locationInfo = new LocationInfo();
                        locationInfo.LocationCode = locationCode;
                        locationInfo.PalletInfoCode = "";
                        locationInfo.Amount = 0;
                        locationInfos.Add(locationInfo);
                    }
                }
                padResponse.code = "200";
                padResponse.message = "成功";
                padResponse.data = locationInfos;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                padResponse.code = "301";
                padResponse.message = "获取信息失败:" + ex.Message;
            }
            return padResponse;
        }

        /// <summary>
        ///根据托盘号托盘解绑
        /// </summary>
        /// <returns></returns>
        public PadResponse UnBindPalletInfo(string palletInfoCode)
        {
            PadResponse padResponse = new PadResponse();
            try
            {
                WmsPalletInfo? wmsPalletInfo = sqlSugarClient.Queryable<WmsPalletInfo>().Where(t => t.PalletInfoCode == palletInfoCode).First();

                if (wmsPalletInfo != null)
                {
                    wmsPalletInfo.Amount = 0;
                    wmsPalletInfo.TonerFlag = 0;
                    int result = sqlSugarClient.Updateable(wmsPalletInfo).ExecuteCommand();
                    if (result > 0)
                    {
                        padResponse.code = "200";
                        padResponse.message = "成功";
                    }
                    else
                    {
                        padResponse.code = "301";
                        padResponse.message = "失败";
                    }
                }
                else
                {
                    padResponse.code = "301";
                    padResponse.message = "未查询到该托盘信息";
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                padResponse.code = "301";
                padResponse.message = "失败:" + ex.Message;
            }
            return padResponse;
        }

        /// <summary>
        ///pad获取指定机台的RFID设备状态
        /// </summary>
        /// <returns></returns>
        public PadResponse GetRfidInfo(string machineCode)
        {
            PadResponse padResponse = new PadResponse();
            try
            {
                List<BaseRfidInfo> list = sqlSugarClient.Queryable<BaseRfidInfo>().Where(t => t.MachineCode == machineCode).ToList();

                if (list != null && list.Count > 0)
                {
                    padResponse.code = "200";
                    padResponse.message = "成功";
                    padResponse.data = list;
                }
                else
                {
                    padResponse.code = "301";
                    padResponse.message = "未查询到该机台的RFID设备信息";
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                padResponse.code = "301";
                padResponse.message = "失败:" + ex.Message;
            }
            return padResponse;
        }

        /// <summary>
        ///pad获取所有机台库存列表信息
        /// </summary>
        /// <returns></returns>
        public PadResponse GetAllMachineInfos()
        {
            PadResponse padResponse = new PadResponse();
            try
            {
                List<WmsBaseLocationVo> Locationlist = sqlSugarClient.SqlQueryable<WmsBaseLocationVo>
                    ("SELECT location_code as agv_position_code,location_status,ifnull(amount,0)  as amount  FROM wms_base_location wbl LEFT JOIN wms_pallet_info wpi ON wbl.container_code=wpi.pallet_info_code")
                    .ToList();
                //List<WmsBaseLocation> Locationlist = sqlSugarClient.Queryable<WmsBaseLocation>().LeftJoin<WmsPalletInfo>((wbi, wpi) => wbi.ContainerCode == wpi.PalletInfoCode).ToList();
                //List <AllLocationInfo> locationInfos = new List<AllLocationInfo>();
                //foreach (var location in Locationlist)
                //{
                //    if (location != null)
                //    {
                //        AllLocationInfo locationInfo = new AllLocationInfo();
                //        if (location.ContainerCode != "")
                //        {
                //            WmsPalletInfo wmsPalletInfo = sqlSugarClient.Queryable<WmsPalletInfo>().Where(t => t.PalletInfoCode == location.ContainerCode).First();


                //            locationInfo.Amount = wmsPalletInfo.Amount;


                //        }
                //        else {
                //            locationInfo.Amount = 0;
                //        }
                //        locationInfo.LocationCode = location.AgvPositionCode;
                //        locationInfo.LocationStatus = location.LocationStatus;
                //        locationInfos.Add(locationInfo);

                //    }
                //    else
                //    {
                //        AllLocationInfo locationInfo = new AllLocationInfo();
                //        locationInfo.LocationCode = "";
                //        locationInfo.Amount = 0;
                //        locationInfo.LocationStatus = 0;
                //        locationInfos.Add(locationInfo);
                //    }
                //}
                padResponse.code = "200";
                padResponse.message = "成功";
                padResponse.data = Locationlist;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                padResponse.code = "301";
                padResponse.message = "失败:" + ex.Message;
            }
            return padResponse;
        }

        /// <summary>
        ///指定机台优先级接口:加急/不加急
        ///priority:0-不加急 1-加急
        /// </summary>
        /// <returns></returns>
        //public PadResponse SetPriorityByMachineCode(string machineCode, int priority)
        //{
        //    PadResponse response = new PadResponse();
        //    try
        //    {
        //        WmsMachineInfo? machineInfo = sqlSugarClient.Queryable<WmsMachineInfo>().First(t => t.MachineCode == machineCode);
        //        if (priority != 0 && priority != 1)
        //        {
        //            response.code = "301";
        //            response.message = "优先级设置失败:优先级必须为0或1";
        //        }
        //        else if (machineInfo != null)
        //        {
        //            machineInfo.Priority = priority;
        //            int rowsAffected = sqlSugarClient.Updateable(machineInfo).UpdateColumns(it => new { it.Priority }).ExecuteCommand();
        //            if (rowsAffected > 0)
        //            {
        //                response.code = "200";
        //                response.message = "优先级设置成功";
        //            }
        //            else
        //            {
        //                response.code = "301";
        //                response.message = "优先级设置失败:更新数据库异常";
        //            }
        //        }
        //        else
        //        {
        //            response.code = "301";
        //            response.message = "优先级设置失败:未找到机台信息";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //sqlSugarClient!.AsTenant().CommitTran();
        //        _logger.Error(ex.Message);
        //        response.code = "301";
        //        response.message = "优先级设置失败:" + ex.Message;
        //    }
        //    return response;
        //}

        /// <summary>
        /// 4楼到5楼原材料入口继续
        /// </summary>
        /// <param name="taskContinue"></param>
        /// <returns></returns>
        //public AgvCompeletedResponse TaskContinue(TaskContinue taskContinue)
        //{
        //    AgvCompeletedResponse compeletedResponse = new AgvCompeletedResponse();
        //    try
        //    {
        //        _dbContext.ChangeTracker.Clear();
        //        var wcsTask = _dbContext.WcsTask
        //            .Where(t => t.taskType == 47)
        //            .Where(t => t.containerNo == taskContinue.palletInfoCode)
        //            .FirstOrDefault();
        //        if (wcsTask != null)
        //        {
        //            wcsTask.useFlag = 1;
        //            _dbContext.Update(wcsTask);
        //            _dbContext.WcsTaskLog.Where(t => t.objid == wcsTask.objid).Update(a => new WcsTaskLog { useFlag = 1 });
        //            _dbContext.SaveChanges();
        //            compeletedResponse.code = "0";
        //            compeletedResponse.message = "成功";
        //        }
        //        else
        //        {
        //            compeletedResponse.code = "1";
        //            compeletedResponse.message = "未找到当前任务";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogManager.Error(ex);
        //        compeletedResponse.code = "1";
        //        compeletedResponse.message = ex.Message;
        //    }
        //    return compeletedResponse;
        //    return null;
        //}
    }
}