kazelee
2025-05-16 67f74c1d68ccbb69eb8436e70018357533ef9c0a
Services/DebugService.cs
@@ -1,30 +1,121 @@
using HH.WCS.Mobox3.AnGang.Models;
using HH.WCS.Mobox3.AnGang.config;
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using CsvHelper.Configuration;
using HH.WCS.Mobox3.AnGang.Helper;
using HH.WCS.Mobox3.AnGang.Helpers;
using HH.WCS.Mobox3.AnGang.Models;
using HH.WCS.Mobox3.AnGang.Services;
using Newtonsoft.Json;
using static HH.WCS.Mobox3.AnGang.Dtos.Request.AgvRequest;
using static HH.WCS.Mobox3.AnGang.Dtos.Request.DebugRequest;
using static HH.WCS.Mobox3.AnGang.Dtos.Response.AgvResponse;
using static HH.WCS.Mobox3.AnGang.Dtos.Response.DebugResponse;
using static HH.WCS.Mobox3.AnGang.Models.DebugModel;
namespace HH.WCS.Mobox3.AnGang.Debug {
    public class DebugService {
        /// <summary>
        /// 模拟 AGV 多次回报任务状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ReturnResults AgvSeriesReports(UpdateTaskState model) {
            var returnResults = new ReturnResults();
            returnResults.ResultList = new List<ReturnResult>();
            //if (!AgvHelper.IsTaskState(model.NextState)) {
            //    return returnResults;
            //}
            var agvCurrentState = 1; // 如果没有找到最新的 TaskAction,默认当前状态为 1(执行)
            // 查询 TaskAction 表中与当前任务号匹配的最新记录
            var db = DbHelper.GetDbClient();
            var taskAction = db.Queryable<TN_Task_Action>()
                .Where(a => a.S_TASK_CODE == model.TaskID)
                .OrderBy(a => a.T_CREATE, SqlSugar.OrderByType.Desc).First();
            if (taskAction != null) {
                // 如果有匹配,将当前任务状态设置为表单中的最新状态
                agvCurrentState = taskAction.N_ACTION_CODE;
            }
            if (!AgvHelper.IsNextStateOk(agvCurrentState, model.NextState)) {
                LogHelper.Info($"Debug: AGV 状态 '{model.NextState}' 不是 '{agvCurrentState}' 的 合法下一状态");
                return returnResults;
            }
            var agvTaskState = new AgvTaskState() {
                task_no = model.TaskID,
                forklift_no = model.ForkliftNo,
            };
            var result = new ReturnResult();
            // 当前状态没有达到最终状态时,循环加入返回列表
            while (agvCurrentState != model.NextState) {
                agvTaskState.state = agvCurrentState;
                result = AgvService.OperateAgvTaskStatus(agvTaskState);
                returnResults.ResultList.Add(result);
                agvCurrentState = AgvHelper.GetNextState(agvCurrentState);
            }
            // 将循环没有到达的最终状态,也加入返回列表
            agvTaskState.state = model.NextState;
            result = AgvService.OperateAgvTaskStatus(agvTaskState);
            returnResults.ResultList.Add(result);
            return returnResults;
        }
        /// <summary>
        /// 初始数据库建立
        /// </summary>
        /// <returns></returns>
        public string CreateDatabase() {
        public static string CreateDatabase(bool cover = true) {
            try {
                var db = DbHelper.GetDbClient();
                db.CodeFirst.InitTables<TN_CG_Detail>();
                db.CodeFirst.InitTables<TN_WorkOrder>();
                db.CodeFirst.InitTables<TN_CAR_IN>();
                //db.CodeFirst.InitTables<SYSHelper.OI_SYS_MAXID>();
                db.CodeFirst.InitTables<TN_Task_Action>();
                db.CodeFirst.InitTables<TN_Task>();
                db.CodeFirst.InitTables<TN_Location>();
                db.CodeFirst.InitTables<TN_Loc_Container>();
                var entityTypes = new Type[] {
                    typeof(TN_CAR_IN),
                    typeof(TN_CG_Detail),
                    typeof(TN_Container),
                    typeof(TN_Loc_Container),
                    typeof(TN_Location),
                    typeof(TN_Task),
                    typeof(TN_Task_Action),
                    typeof(SysHelper.OI_SYS_MAXID),
                };
                using (var tran = db.Ado.UseTran()) {
                    if (cover) {
                        // 删除所有表(按依赖关系倒序)
                        var tables = db.DbMaintenance.GetTableInfoList();
                        foreach (var table in tables.OrderByDescending(t => t.Name)) {
                            db.DbMaintenance.DropTable(table.Name);
                        }
                        // 创建新表
                        db.CodeFirst.InitTables(entityTypes);
                        //db.CodeFirst.BackupTable().InitTables(entityTypes);
                    }
                    else {
                        db.CodeFirst.InitTables(entityTypes);
                    }
                    tran.CommitTran();
                }
            }
            catch (Exception ex) {
                LogHelper.Info($"发生了异常");
@@ -34,6 +125,113 @@
            return "成功";
        }
        public static string InsertLocCntrCg() {
            string filePath = PathHelper.GetProjDir("./debug/loc_cntr_cg.csv");
            var db = DbHelper.GetDbClient();
            try {
                var configuration = new CsvConfiguration(CultureInfo.InvariantCulture) {
                    // 配置选项
                    Delimiter = ",",               // 分隔符
                    HasHeaderRecord = true,        // 有标题行
                    MissingFieldFound = null,      // 忽略缺失字段
                    HeaderValidated = null,        // 跳过标题验证
                    BadDataFound = context => { }  // 处理错误数据
                };
                var locCntrCgList = new List<LocCntrCg>();
                using (var reader = new StreamReader(filePath))
                using (var csv = new CsvReader(reader, configuration)) {
                    // 读取记录
                    locCntrCgList = csv.GetRecords<LocCntrCg>().ToList();
                }
                using (var tran = db.UseTran()) {
                    foreach (var locCntrCg in locCntrCgList) {
                        LogHelper.Info("LogCntrCg:" + JsonConvert.SerializeObject(locCntrCg));
                        if (string.IsNullOrEmpty(locCntrCg.LocCode)) break;
                        var loc = db.Queryable<TN_Location>().First(a => a.S_CODE == locCntrCg.LocCode);
                        if (loc == null) {
                            var newLoc = new TN_Location {
                                S_CODE = locCntrCg.LocCode,
                                S_AREA_CODE = locCntrCg.LocArea ?? ""
                            };
                            if (db.Insertable<TN_Location>(newLoc).ExecuteCommand() <= 0) {
                                tran.RollbackTran();
                                LogHelper.Info($"插入位置{locCntrCg.LocCode}失败");
                                return "插入失败";
                            }
                            loc = newLoc;
                        }
                        //if (loc.N_CURRENT_NUM == 0) {
                        //    loc.N_CURRENT_NUM = 1;
                        //    if (db.Updateable<TN_Location>(loc).UpdateColumns(
                        //        it => new { it.N_CURRENT_NUM, it.T_MODIFY }).ExecuteCommand() <= 0) {
                        //        tran.RollbackTran();
                        //        LogHelper.Info($"修改位置{locCntrCg.LocCode}失败");
                        //        continue;
                        //    }
                        //}
                        if (string.IsNullOrEmpty(locCntrCg.CntrCode)) {
                            LogHelper.Info("容器号为空,不再读取后面的数据");
                            continue;
                        }
                        var locCntrRel = db.Queryable<TN_Loc_Container>().First(a => a.S_LOC_CODE == locCntrCg.LocCode
                            && a.S_CNTR_CODE == locCntrCg.CntrCode);
                        if (locCntrRel == null) {
                            var newLocCntrRel = new TN_Loc_Container {
                                S_LOC_CODE = locCntrCg.LocCode,
                                S_CNTR_CODE = locCntrCg.CntrCode,
                                S_CNTR_TYPE = locCntrCg.CntrType ?? ""
                            };
                            loc.N_CURRENT_NUM = 1;
                            if (db.Insertable<TN_Loc_Container>(newLocCntrRel).ExecuteCommand() <= 0
                                && db.Updateable<TN_Location>(loc).UpdateColumns(c => c.N_CURRENT_NUM).ExecuteCommand() <= 0) {
                                tran.RollbackTran();
                                LogHelper.Info($"插入位置托盘关系{locCntrCg.LocCode}-{locCntrCg.CntrCode}失败");
                                return "插入失败";
                            }
                        }
                        if (string.IsNullOrEmpty(locCntrCg.ItemCode)) {
                            LogHelper.Info("物料号为空,不再读取后面的数据");
                            continue;
                        }
                        var cgDetail = db.Queryable<TN_CG_Detail>().First(a => a.S_CNTR_CODE == locCntrCg.CntrCode
                            && a.S_ITEM_CODE == locCntrCg.ItemCode);
                        if (cgDetail == null) {
                            var locList = new List<TN_CG_Detail>();
                            locList.Add(new TN_CG_Detail { S_CNTR_CODE = locCntrCg.CntrCode, S_ITEM_CODE = locCntrCg.ItemCode, S_BATCH_NO = locCntrCg.BatchNo ?? "" });
                            if (db.Insertable<TN_CG_Detail>(locList).ExecuteCommand() <= 0) {
                                tran.RollbackTran();
                                LogHelper.Info($"插入托盘物料关系{locCntrCg.CntrCode}-{locCntrCg}失败");
                                return "插入失败";
                            }
                        }
                    }
                    tran.CommitTran();
                }
                return "插入数据成功";
            }
            catch (FileNotFoundException) {
                return $"Error: File not found - {filePath}";
            }
            catch (Exception ex) {
                return $"Error reading CSV file: {ex.Message}";
            }
        }
    }
}