肖洋
2024-12-21 7c926c1e3ade5158e6b1b0b805cd1b9c142e4b6c
Code Management/WMS/WIDESEA_WMSServer/WIDESEA_StorageTaskServices/Task/Partial/Dt_TaskService.cs
@@ -1,7 +1,18 @@
using Masuit.Tools;
using Castle.Components.DictionaryAdapter.Xml;
using log4net.Core;
using Masuit.Tools;
using System.CodeDom;
using System.Threading.Tasks;
using WIDESEA_Common;
using WIDESEA_Common.CustomModels;
//using WIDESEA_Common.CustomModels;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.Const;
using WIDESEA_DTO.MOM;
using WIDESEA_DTO.WMS;
using WIDESEA_StorageTaskRepository;
using WIDESEAWCS_BasicInfoRepository;
using WIDESEAWCS_Model.Models;
namespace WIDESEA_StorageTaskServices;
@@ -43,8 +54,6 @@
                    return content.OK(data: taskDTO);
                }
            }
            // 调用CreateNewTask方法,创建新任务
            content = await CreateNewTask(input);
        }
@@ -66,49 +75,51 @@
    /// <returns></returns>
    private async Task<WebResponseContent> CreateNewTask(RequestTaskDto input)
    {
        WebResponseContent content = new WebResponseContent();
        //DtLocationInfo locationInfo = await RequestLocation(input);
        //if (locationInfo == null) throw new Exception("库位已满");
        var stationinfo = _stationManagerRepository.QueryFirst(x => x.stationChildCode == input.Position);
        if (stationinfo == null) throw new Exception("未知站台");
        if (stationinfo.stationType != 7)
        try
        {
            if (input.PalletCode == null || input.PalletCode.Trim() == "")
                return content.Error($"【{stationinfo.remark}】托盘条码为空");
        }
        var task = await CreateNewTaskByStation(input, stationinfo);
            WebResponseContent content = new WebResponseContent();
        // 尝试添加新任务
        if (task == null) return content.Error();
        var taskId = await BaseDal.AddDataAsync(task);
        bool isResult = taskId > 0;
        if (isResult)
        {
            // 创建WMS任务
            WMSTaskDTO taskDTO = new WMSTaskDTO()
            var stationinfo = _stationManagerRepository.QueryFirst(x => x.stationChildCode == input.Position);
            if (stationinfo == null) throw new Exception("未知站台");
            if (stationinfo.stationType != 7)
            {
                TaskNum = task.TaskNum.Value,
                Grade = 1,
                PalletCode = task.PalletCode,
                RoadWay = task.Roadway,
                SourceAddress = task.SourceAddress,
                TargetAddress = task.TargetAddress,
                TaskState = task.TaskState.Value,
                Id = 0,
                TaskType = task.TaskType,
            };
            content.OK(data: taskDTO);
                if (input.PalletCode == null || input.PalletCode.Trim() == "")
                    return content.Error($"【{stationinfo.remark}】托盘条码为空");
            }
            var task = await CreateNewTaskByStation(input, stationinfo);
            // 尝试添加新任务
            if (task == null) return content.Error();
            var taskId = await BaseDal.AddDataAsync(task);
            bool isResult = taskId > 0;
            if (isResult)
            {
                // 创建WMS任务
                WMSTaskDTO taskDTO = new WMSTaskDTO()
                {
                    TaskNum = task.TaskNum.Value,
                    Grade = 1,
                    PalletCode = task.PalletCode,
                    RoadWay = task.Roadway,
                    SourceAddress = task.SourceAddress,
                    TargetAddress = task.TargetAddress,
                    TaskState = task.TaskState.Value,
                    Id = 0,
                    TaskType = task.TaskType,
                };
                content.OK(data: taskDTO);
            }
            else
                content.Error("添加任务失败");
            return content;
        }
        else
            content.Error("添加任务失败");
        return content;
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
    /// <summary>
@@ -120,25 +131,32 @@
    /// <exception cref="Exception"></exception>
    private async Task<Dt_Task> CreateNewTaskByStation(RequestTaskDto input, Dt_StationManager stationManager)
    {
        Dt_Task task = null;
        switch (stationManager.stationType)
        try
        {
            case 6:
            case 1:
                task = await CreateInTaskAsync(input, stationManager); break;
            //case 2:
            case 3:  //异常排出给WCS处理
            //case 4:
            case 5:
                task = await CreateInToOutTaskAsync(input, stationManager); break;
            case 7:
                task = await CreateEmptyOutTaskAsync(input, stationManager); break;
            case 15:
                task = await CheckAbnormalTaskAsync(input, stationManager); break;
            default:
                throw new Exception("未知站台类型");
            Dt_Task task = null;
            switch (stationManager.stationType)
            {
                case 6:
                case 1:
                    task = await CreateInTaskAsync(input, stationManager); break;
                //case 2:
                case 3:  //异常排出给WCS处理
                         //case 4:
                case 5:
                    task = await CreateInToOutTaskAsync(input, stationManager); break;
                case 7:
                    task = await CreateEmptyOutTaskAsync(input, stationManager); break;
                case 15:
                    task = await CheckAbnormalTaskAsync(input, stationManager); break;
                default:
                    throw new Exception("未知站台类型");
            }
            return task;
        }
        return task;
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #region 直接出库任务
@@ -365,6 +383,7 @@
    #region 库位分配
    #region 获取货位
    /// <summary>
    ///
    /// </summary>
@@ -373,8 +392,6 @@
    /// <returns></returns>
    private async Task<DtLocationInfo> RequestLocation(RequestTaskDto requestTask, bool isCheckRequest = false)
    {
        #region 获取货位
        try
        {
            List<DtLocationInfo> locations;
@@ -399,17 +416,46 @@
            Console.WriteLine(err.Message.ToString());
            return null;
        }
        #endregion 获取货位
    }
    #endregion 获取货位
    #region 异常口入库获取库位
    private async Task<DtLocationInfo> RequestLocationByAbnormal(RequestTaskDto requestTask, bool isCheckRequest = false)
    {
        try
        {
            List<DtLocationInfo> locations;
            if (isCheckRequest)
            {
                locations = await _locationRepository.QueryDataAsync(x => x.LocationStatus == (int)LocationEnum.Free && x.RoadwayNo == requestTask.Roadways && x.EnalbeStatus == 1 && x.LocationType == 2 && x.Remark == "1");
            }
            else
            {
                locations = await _locationRepository.QueryDataAsync(x => x.LocationStatus == (int)LocationEnum.Free && x.RoadwayNo == requestTask.Roadways && x.EnalbeStatus == 1 && x.LocationType == 1);
            }
            if (locations == null)
            {
                return null;
            }
            return locations.OrderBy(x => x.Layer).ThenBy(x => x.Column).ThenBy(x => x.Row).FirstOrDefault();
        }
        catch (Exception err)
        {
            Console.WriteLine(err.Message.ToString());
            return null;
        }
    }
    #endregion
    #endregion 库位分配
    // 获取工艺申请
    private async Task<ProcessApplyDto> GetProcessApplyAsync(RequestTaskDto input, ResultTrayCellsStatus content)
    private Task<ProcessApplyDto> GetProcessApplyAsync(RequestTaskDto input, ResultTrayCellsStatus content)
    {
        // 创建一个ProcessApplyDto对象,并赋值
        return new ProcessApplyDto()
        return Task.FromResult(new ProcessApplyDto()
        {
            EquipmentCode = input.EquiCodeMOM,
            Software = "WMS",
@@ -418,7 +464,7 @@
            {
                SerialNo = item.SerialNo
            }).ToList()
        };
        });
    }
    #endregion 请求任务入库
@@ -486,12 +532,22 @@
            return content.Error(ex.Message);
        }
    }
    #endregion
    #region 异常口任务检测
    /// <summary>
    /// 异常排出口入库校验  所有异常交给WCS做原地址NG处理
    /// </summary>
    /// <param name="input"></param>
    /// <param name="stationManager"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<Dt_Task> CheckAbnormalTaskAsync(RequestTaskDto input, Dt_StationManager stationManager)
    {
        try
        {
            if (stationManager.stationType == 15) throw new Exception("");
            // 创建一个TrayCellsStatusDto对象,并赋值
            TrayCellsStatusDto trayCells = new TrayCellsStatusDto()
            {
@@ -504,32 +560,39 @@
            // 调用GetTrayCellStatusAsync方法,获取整盘电芯
            WebResponseContent content = await GetTrayCellStatusAsync(trayCells);
            // 如果状态为false,则返回content
            if (!content.Status) throw new Exception(content.Message);
            if (!content.Status)  //获取整盘电芯数据, 如异常 使用空框类型入库
            {
                ConsoleHelper.WriteErrorLine(content.Message);
                throw new Exception("MOM整盘电芯属性获取异常");
            }
            // 添加组盘信息
            // 将content.Data转换为ResultTrayCellsStatus对象
            var result = JsonConvert.DeserializeObject<ResultTrayCellsStatus>(content.Data.ToString());
            if (result.SerialNos.Count <= 0)
            if (result.SerialNos.Count <= 0)  //如调用成功 但电芯为0则定为空盘
            {
                ConsoleHelper.WriteErrorLine(result.MOMMessage);
                var taskNG = new Dt_Task
                DtLocationInfo EmptylocationInfo = await RequestLocationByAbnormal(input);
                if (EmptylocationInfo == null) throw new Exception("库位已满");
                var Epmtytask = new Dt_Task
                {
                    CurrentAddress = input.Position,
                    Grade = 1,
                    Grade = 3,  //优先处理异常排出口的任务 防止正常需排出异常口的任务堵线
                    Roadway = input.Roadways,
                    TargetAddress = stationManager.stationNGLocation,
                    TargetAddress = EmptylocationInfo.LocationCode,
                    Dispatchertime = DateTime.Now,
                    MaterialNo = "",
                    NextAddress = stationManager.stationNGChildCode,
                    NextAddress = input.Roadways,
                    OrderNo = null,
                    PalletCode = input.PalletCode,
                    SourceAddress = stationManager.stationLocation,
                    TaskState = (int)TaskInStatusEnum.Line_InFinish,
                    TaskType = (int)TaskOutboundTypeEnum.InToOut,
                    TaskType = (int)TaskInboundTypeEnum.InTray,
                    TaskNum = await BaseDal.GetTaskNo(),
                    Creater = "Systeam"
                };
                return taskNG;
                return Epmtytask;
            }
            //Console.WriteLine(result);
@@ -542,45 +605,64 @@
            var boxing = CreateBoxingInfo(result, input.PalletCode);
            if (boxing == null) throw new Exception("组盘失败");
            //// 调用GetProcessApplyAsync方法,获取工艺路线
            //ProcessApplyDto process = await GetProcessApplyAsync(input, result);
            if (!stationManager.Roadway.Contains("FR"))  //非分容库区 入库验证工艺路线
            {
                // 调用GetProcessApplyAsync方法,获取工艺路线
                ProcessApplyDto process = await GetProcessApplyAsync(input, result);
            //// 如果process为null,则返回content
            //if (process == null) return content;
                // 如果process为null,则返回content
                if (process == null) throw new Exception("工艺请求参数异常");
            //// 调用_processApplyService.GetProcessApplyAsync方法,获取工艺申请
            //content = await _processApplyService.GetProcessApplyAsync(process);
                // 调用_processApplyService.GetProcessApplyAsync方法,获取工艺申请
                content = await _processApplyService.GetProcessApplyAsync(process);
            //// 如果状态为false,则返回null
            //if (!content.Status) return content.Error("工艺申请失败");
                // 如果状态为false,则返回null
                if (!content.Status) throw new Exception("工艺申请失败");
            }
            ////// 调用GetProcessResponseAsync方法,获取工艺响应
            ////var processResponse = await GetProcessResponseAsync(process, input.Position);
            var isBox = await _boxingInfoRepository.AddDataNavAsync(boxing);
            DtLocationInfo locationInfo = null;
            if (stationManager.Roadway.Contains("FR"))
            {
                locationInfo = await RequestLocation(input, true);
            }
            else
            {
                locationInfo = await RequestLocationByAbnormal(input);
            }
            //DtLocationInfo locationInfo = await RequestLocation(input);
            if (locationInfo == null) throw new Exception("库位已满");
            var task = new Dt_Task
            {
                CurrentAddress = input.Position,
                Grade = 1,
                Grade = 3,  //优先处理异常排出口的任务 防止正常需排出异常口的任务堵线
                Roadway = input.Roadways,
                TargetAddress = stationManager.stationLocation,
                TargetAddress = locationInfo.LocationCode,
                Dispatchertime = DateTime.Now,
                MaterialNo = "",
                NextAddress = input.Roadways,
                OrderNo = null,
                //PalletCode = stockinfo.PalletCode,
                //SourceAddress = stockinfo.LocationCode,
                TaskState = (int)TaskOutStatusEnum.OutNew,
                TaskType = (int)TaskOutboundTypeEnum.OutTray,
                PalletCode = input.PalletCode,
                SourceAddress = stationManager.stationLocation,
                TaskState = (int)TaskInStatusEnum.Line_InFinish,
                TaskType = (int)TaskInboundTypeEnum.Inbound,
                TaskNum = await BaseDal.GetTaskNo(),
                Creater = "Systeam"
            };
            var isBox = await _boxingInfoRepository.AddDataNavAsync(boxing);
            ConsoleHelper.WriteSuccessLine($"修改前:" + locationInfo.LocationStatus.ToString());
            locationInfo.LocationStatus = (int)LocationEnum.FreeDisable;
            ConsoleHelper.WriteSuccessLine($"修改后:" + locationInfo.LocationStatus.ToString());
            await UpdateLocationAsync(locationInfo);
            return task;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
@@ -766,7 +848,7 @@
        {
            Dt_StationManager station = _stationManagerRepository.QueryFirst(x => x.stationChildCode == json.Position);
            DtStockInfo stockInfo = _stockInfoRepository.QueryFirst(X => X.IsFull && X.AreaCode == "CWSC3" && X.ProductionLine == "ZJ-7");
            DtStockInfo stockInfo = _stockInfoRepository.QueryFirst(X => X.IsFull && X.AreaCode == "CWSC3" && X.ProductionLine == station.productLine);
            if (stockInfo == null) throw new Exception("库内无满足条件的库存可出库");
            Dt_StationManager OutStation = _stationManagerRepository.QueryFirst(x => x.stationPLC == "1016" && x.stationType == 10);
@@ -801,4 +883,127 @@
            return content.Error($"失败:{ex.Message}");
        }
    }
}
    #region 火警出库
    public WebResponseContent EmergencyTask(object obj)
    {
        WebResponseContent content = new WebResponseContent();
        var emergencyTask = new DTSEmergencyTask();
        try
        {
            emergencyTask = JsonConvert.DeserializeObject<DTSEmergencyTask>(obj.ToString());
            if (emergencyTask == null) throw new Exception("火警参数为空");
            DtLocationInfo locationInfo = _locationRepository.QueryFirst(x => x.Row == emergencyTask.row && x.Column == emergencyTask.column && x.Layer == emergencyTask.layer && x.RoadwayNo == emergencyTask.Roadway);
            if (locationInfo == null)
            {
                throw new Exception("未知库位");
            }
            //查找消防站台
            var station = _stationManagerRepository.QueryFirst(t => t.Roadway == locationInfo.RoadwayNo
                 && t.stationType == (int)StationManager.FireStation
                 /*&& t. == "Enable"*/);
            if (station == null)
            {
                throw new Exception("消防站台未配置!");
            }
            //查找库存信息
            var stockInfo = _stockInfoRepository.QueryFirst(x => x.LocationCode == locationInfo.LocationCode && x.LocationInfo.RoadwayNo == locationInfo.RoadwayNo);
            //托盘码
            string barcode = string.Empty;
            if (stockInfo != null)
            {
                barcode = stockInfo.PalletCode;
            }
            else
            {
                //无库存信息,生成随机托盘码
                barcode = "M" + DateTime.Now.ToString("MMddHHmmss") + "-" + new Random().Next(100, 1000);
            }
            Dt_Task fireTask = BaseDal.QueryFirst(x => x.TaskType == 500 && x.SourceAddress == locationInfo.LocationCode && x.Roadway == station.Roadway);
            if (fireTask != null)
            {
                throw new Exception("已添加火警出库任务");
            }
            int taskNum = BaseDal.GetTaskNo().Result;
            Dt_Task task = new Dt_Task
            {
                CreateDate = DateTime.Now,
                Creater = "DTS",
                CurrentAddress = locationInfo.LocationCode,
                Grade = 1,
                Dispatchertime = DateTime.Now,
                PalletCode = barcode,
                Roadway = station.Roadway,
                SourceAddress = locationInfo.LocationCode,
                TaskState = (int)TaskOutStatusEnum.OutNew,
                TaskType = 500,
                TargetAddress = station.stationLocation,
                NextAddress = station.stationChildCode,
                TaskNum = taskNum, //_taskRepository.GetTaskNo().Result,
                TaskId = 0,
            };
            // 尝试添加新任务
            WMSTaskDTO taskDTO = new WMSTaskDTO()
            {
                TaskNum = task.TaskNum.Value,
                Grade = 1,
                PalletCode = task.PalletCode,
                RoadWay = task.Roadway,
                SourceAddress = task.SourceAddress,
                TargetAddress = task.TargetAddress,
                TaskState = task.TaskState.Value,
                Id = 0,
                TaskType = 500,
            };
            var configs = _configService.GetConfigsByCategory(CateGoryConst.CONFIG_SYS_IPAddress);
            var ipAddress = configs.FirstOrDefault(x => x.ConfigKey == SysConfigConst.WCSIPAddress)?.ConfigValue;
            var ReceiveByWMSTask = configs.FirstOrDefault(x => x.ConfigKey == SysConfigConst.ReceiveByWMSTask)?.ConfigValue;
            if (ReceiveByWMSTask == null || ipAddress == null)
            {
                throw new Exception("WMS IP 未配置");
            }
            var wmsIpAddrss = ipAddress + ReceiveByWMSTask;
            var respon = HttpHelper.Post(wmsIpAddrss, JsonConvert.SerializeObject(taskDTO));
            if (respon != null)
            {
                WebResponseContent respone = JsonConvert.DeserializeObject<WebResponseContent>(respon.ToString());
                if (respone.Status)
                {
                    var taskId = BaseDal.AddData(task);
                }
                else
                {
                    throw new Exception("WCS处理失败:" + respone.Message);
                }
            }
            else
            {
                throw new Exception("请求处理失败");
            }
            LogFactory.GetLog("DTS火警出库").Info(true, $"\r\r--------------------------------------");
            LogFactory.GetLog("DTS火警出库").Info(true, obj.ToJsonString());
            return content.OK();
        }
        catch (Exception ex)
        {
            LogFactory.GetLog("DTS火警出库").Info(true, $"\r\r--------------------------------------");
            LogFactory.GetLog("DTS火警出库").Info(true, ex.Message);
            return content.Error(ex.Message);
        }
    }
    #endregion
}