using System.Collections.Generic;
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Redis.Utility;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;
using Siger.Middlelayer.ToolRepository.Request;
using Siger.Middlelayer.ToolRepository.Response;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.ToolRepository.Entities;

namespace Siger.ApiTools.Controllers
{
    public class ToolMoniterController : BaseController
    {
        private readonly ISigerProjectToolRepository sigerProjectToolRepository;
        private readonly ISigerProjectToolSpindleTrueRepository sigerProjectToolSpindleTrueRepository;
        private readonly ISigerProjectToolCutterLocationTrueRepository _sigerProjectToolCutterLocationTrue;

        public ToolMoniterController(ISigerProjectToolRepository sigerProjectTool ,ISigerProjectToolSpindleTrueRepository sigerToolSpindleRepository, ISigerProjectToolCutterLocationTrueRepository sigerProjectToolCutterLocationTrue)
        {
            sigerProjectToolRepository = sigerProjectTool;
            sigerProjectToolSpindleTrueRepository = sigerToolSpindleRepository;
            _sigerProjectToolCutterLocationTrue = sigerProjectToolCutterLocationTrue;
        }

        [HttpGet]
        public IActionResult GetSpindleListBySection(int sectionId)
        {
            //检查设备运行状态
            var machineId = sigerProjectToolSpindleTrueRepository.GetMachineIdBySectionId(sectionId, ProjectId);
            if (machineId == 0)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var spindleList = sigerProjectToolSpindleTrueRepository.GetSpindleListBySection(machineId, ProjectId);

            return new ObjectResult(spindleList);
        }

        [HttpGet]
        public IActionResult GetCutterLocationListBySpindle(int spindle)
        {
            var data = _sigerProjectToolCutterLocationTrue.GetList(f => f.spindleid == spindle && f.status == (int)RowState.Valid);

            var dict = data.Select(f => f.name).Distinct();

            return new ObjectResult(dict);
        }

        /// <summary>
        ///  //实时监控线 加载刀位下拉框内容
        /// </summary>
        /// <param name="machine_id">machineid</param>
        /// <param name="spindle_id">spindleid 主键</param>
        /// <param name="program_no">程序号</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCutterLocationList(int machine_id, int spindle_id, string program_no)
        {
            var data = sigerProjectToolSpindleTrueRepository.getCutterLocationList(ProjectId,machine_id, spindle_id, program_no);
            if (!data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            return new ObjectResult(data);
        }
        /// <summary>
        /// 刀具监控仪表盘 所有设备一览
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public IActionResult GetAllToolMonitorData([FromBody]RequestToolMoniterdata request)
        {
            var type = 0;
            var searchType = AlarmGrade.Noconfig;
            if (!string.IsNullOrEmpty(request.machine_type))
            {
                if (request.machine_type == "7")
                    searchType = AlarmGrade.Normal;
                else if (request.machine_type == "0")
                    searchType = AlarmGrade.Noconfig;
                else
                {
                    int.TryParse(request.machine_type, out type);
                    searchType = (AlarmGrade)type;
                }
            }
            //================================================================================
            //查找当前设备的运行状态
            var MachineState = new CNCEquipmentStateRepository(CompanyId, ProjectId, false);
            var MachineUsage = new ToolMachineCycleUsageRepository(CompanyId, ProjectId, false);
            var lstState = MachineState.GetCNCEquipmentStates();
            if (!lstState.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var resultTmp = new ResponseToolsDashbord
            {
                alarmCount = new AlarmCount { },
                data = new Dictionary<int, List<DashBordToolsNode>>()
            };

            var dapperData = new ToolAlarmRepository(CompanyId, ProjectId);
            var ToolInfos = sigerProjectToolSpindleTrueRepository.GetMonitorData(ProjectId, lstState);
            if (!ToolInfos.Any())
            {
                return new ObjectResult(resultTmp);
            }

            var stime = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.AddMinutes(-2));
            var etime = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now);
            var Kmdata = dapperData.GetToolAlarm(lstState.Select(f=>f.MachineId).ToList(), stime, etime, request.alarm_grade).ToList();

            var lstDashbordTools = new List<DashBordToolsNode>();
            var machineGrop = ToolInfos.GroupBy(g => g.MachineID);
            var displayProgram = string.Empty;
            foreach (var m in machineGrop)
            {
                var Machine = m.ToList();
                var spindleGroup = Machine.GroupBy(g => g.SpindleName);

                if (!lstDashbordTools.Where(f => f.machine_id == m.Key.ToString()).Any())
                {
                    lstDashbordTools.Add(new DashBordToolsNode { Dispaylevel = 6, alarm_grade = 0, searchType = searchType, machine_id = m.Key.ToString(), machine_name = Machine[0].MachineName, bk_color = ApiCommon.Utilities.CommonUtility.GetAlarmColor(0) });
                }
                foreach (var s in spindleGroup)
                {
                    var tools = s.ToList();
                    var ToolMonitors = tools.GroupBy(g => g.Toollocation).OrderBy(o=>o.Key);
                    foreach (var toolNo in ToolMonitors)
                    {
                        var mm = string.Empty;
                        var procProgram = string.Empty;
                        var toollst = toolNo.ToList();
                        var currTool = toollst.FirstOrDefault();
                        var normal = true;
                        var tbroken = false;
                        var tdestroy = false;
                        var tquantiy = false;
                        var tload = false;
                        var tlife = false;

                        //配置主程序
                        var monitor = toollst.Find(f => f.IsProces == (int)ProcessProgram.MainProgram && f.cncProgram == f.Program && f.TooLife > 0);
                        if (monitor != null)
                        {
                            procProgram = ProgramType.mainProgram + monitor.cncProgram;
                            MachineState.SetLastProcess(monitor.MachineID, procProgram);
                        }
                        else
                        { //配置子程序
                            monitor = toollst.Find(f => f.IsProces == (int)ProcessProgram.ChildProgram && f.cncSubProgram == f.SubProgram && f.TooLife > 0);
                            if (monitor != null)
                            {
                                procProgram = ProgramType.subProgram + monitor.cncSubProgram;
                                MachineState.SetLastProcess(monitor.MachineID, procProgram);
                            }
                        }
                        if (monitor == null)
                        {
                            //最近配置
                            procProgram = MachineState.GetLastProcess(toollst.First().MachineID);
                            if (string.IsNullOrWhiteSpace(procProgram))
                                continue;

                            var pnType = procProgram.Substring(0, 1);
                            var _redipn = procProgram.Substring(1, procProgram.Length - 1);
                            if (pnType == ProgramType.mainProgram)
                                monitor = toollst.Find(f => f.Program == _redipn);
                            else
                                monitor = toollst.Find(f => f.SubProgram == _redipn);

                        }

                        // 配置的程序号与运行的程序号不一致 ，不显示额定寿命
                        if (string.IsNullOrEmpty(procProgram))
                            continue;
                        if (monitor == null )
                            continue;
                        displayProgram = monitor.IsProces == (int)ProcessProgram.MainProgram ? monitor.Program : monitor.SubProgram;
                        resultTmp.alarmCount.normal += 1;
                        var Dashbord = new DashBordToolsNode
                        {
                            machine_id = monitor.MachineID.ToString(),
                            machine_name = monitor.MachineName,
                            spindle_id = monitor.Spid.ToString(),
                            spindle_name = monitor.SpindleName,
                            cutter_location_id = monitor.id.ToString(),
                            cutter_location_name = monitor.Toollocation,
                            Dispaylevel = 0,
                            searchType = AlarmGrade.Normal,
                            bk_color = ApiCommon.Utilities.CommonUtility.GetAlarmColor(0),
                            section_list = GetSectionID(monitor.SectionID),
                            is_open = "1",
                            ratelife = monitor.TooLife==null?0: monitor.TooLife,
                            surplus_life= monitor.TooLife == null ? 0 : monitor.TooLife,
                            Programs = monitor.Program + "/" + monitor.SubProgram,
                            pn= monitor.Program,
                            spn= monitor.SubProgram,
                            toolname=monitor.ToolName,
                            drawingcode=monitor.DrawingCode
                        };

                        if (monitor.IsProces != 0)  //配置加工刀位信息
                        {
                          
                            var usage = MachineUsage.GetCycleUsage(monitor.MachineID, procProgram, monitor.SpindleName, monitor.Toollocation); 
                            if (usage != null)
                            {
                                Dashbord = SetUsage(Dashbord, Dashbord.ratelife, usage);
                            }
                        }
                        else  //未配置加工刀位信息
                        {
                            var mProram= ProgramType.mainProgram + monitor.cncProgram;
                            var sProgram= ProgramType.subProgram + monitor.cncSubProgram;
                            var usage = MachineUsage.GetCycleUsage(monitor.MachineID, mProram, monitor.SpindleName, monitor.Toollocation);
                            if (usage!=null)
                            {
                                Dashbord = SetUsage(Dashbord, Dashbord.ratelife, usage,false);
                            }
                            else
                            {
                                var subUsage = MachineUsage.GetCycleUsage(monitor.MachineID, sProgram, monitor.SpindleName, monitor.Toollocation);
                                if (subUsage!=null)
                                {
                                    Dashbord = SetUsage(Dashbord, Dashbord.ratelife, subUsage,false);
                                }
                            }
                            //未配置且tc,tl=0
                            if (Dashbord.ratelife == null || Dashbord.ratelife == 0)
                            {
                                normal = false;
                                continue;
                            }
                        }

                        if (Dashbord.surplus_life > 0)
                        {
                            var percent = Math.Round(Convert.ToDecimal(Dashbord.surplus_life) / Convert.ToDecimal(Dashbord.ratelife) * 100,1);
                            if (percent < 15 )
                            {
                                Dashbord.Dispaylevel = (int)AlarmGrade.ToolDieLine;
                                Dashbord.alarm_grade = (int)AlarmGrade.ToolDieLine;
                                normal = false;
                                tlife = true;
                                Dashbord.bk_color = ApiCommon.Utilities.CommonUtility.GetAlarmColor(AlarmGrade.ToolDieLine);
                                Dashbord.searchType = AlarmGrade.ToolDieLine;
                            }
                        }else
                        {
                            Dashbord.surplus_life = Dashbord.surplus_life == null ? 0 : Dashbord.surplus_life;
                            Dashbord.Dispaylevel = (int)AlarmGrade.ToolDieLine;
                            Dashbord.alarm_grade = (int)AlarmGrade.ToolDieLine;
                            normal = false;
                            tlife = true;
                   
                            Dashbord.bk_color = ApiCommon.Utilities.CommonUtility.GetAlarmColor(AlarmGrade.ToolDieLine);
                            Dashbord.searchType = AlarmGrade.ToolDieLine;
                        }
                        var tnAlarm = Kmdata.Where(f => f.MachineID == monitor.MachineID && f.Spindle_name == monitor.SpindleName && f.Cutter_location_name == monitor.Toollocation).FirstOrDefault();
                        //alarm
                        if (tnAlarm != null)
                        {
                            Dashbord.Dispaylevel = tnAlarm.Alarm_grade;
                            Dashbord.alarm_grade = tnAlarm.Alarm_grade;
                            normal = false;
                            Dashbord.alarm_grade = tnAlarm.Alarm_grade;
                            Dashbord.bk_color = ApiCommon.Utilities.CommonUtility.GetAlarmColor((AlarmGrade)tnAlarm.Alarm_grade);
                            Dashbord.searchType = (AlarmGrade)tnAlarm.Alarm_grade;

                            switch ((AlarmGrade)tnAlarm.Alarm_grade)
                            {
                                case AlarmGrade.Quality:
                                    tquantiy = true; //resultTmp.alarmCount.quality += 1;
                                    break;
                                case AlarmGrade.Wear:
                                    tload = true;// resultTmp.alarmCount.alarm += 1;
                                    break;
                                case AlarmGrade.Broken:
                                    tbroken = true;// resultTmp.alarmCount.tipping += 1;
                                    break;
                                case AlarmGrade.Destroyed:
                                    tdestroy = true; // resultTmp.alarmCount.cutter_broke += 1;
                                    break;
                            }
                        }
                        if (!normal)
                            resultTmp.alarmCount.normal -= 1;
                        if (tlife)
                            resultTmp.alarmCount.life += 1;
                        if (tload)
                            resultTmp.alarmCount.alarm += 1;
                        if (tquantiy)
                            resultTmp.alarmCount.quality += 1;
                        if (tbroken)
                        {
                            resultTmp.alarmCount.tipping += 1;
                        }
                        if (tdestroy)
                        {
                            resultTmp.alarmCount.cutter_broke += 1;
                        }
                        lstDashbordTools.Add(Dashbord);
                    }
                }
            }
            var lstByMc = lstDashbordTools.GroupBy(f => f.machine_id);
            foreach(var mc in lstByMc)
            {
                var toolsDiv = mc.ToList();
                if (searchType != AlarmGrade.Noconfig)
                    toolsDiv = toolsDiv.Where(f => f.searchType == searchType).ToList();
                
                if (toolsDiv.Count > 1)
                {
                    var showColor = toolsDiv.Max(m => m.alarm_grade);
                    //前端只读取第一个值
                    //此处后续可能产生影响,如果修改需要保证前后端一致
                    toolsDiv[0].alarm_grade = showColor;
                    toolsDiv[0].bk_color= ApiCommon.Utilities.CommonUtility.GetAlarmColor((AlarmGrade)showColor);
                    //v1.5新增程序号显示
                    //if (int.TryParse(mc.Key, out int mcID))
                    //{
                    //    var pn = lstState.FirstOrDefault(f => f.MachineId == mcID).PN;
                    //    var spn = lstState.FirstOrDefault(f => f.MachineId == mcID).SPN;
                    //    toolsDiv[0].pn = pn;
                    //    toolsDiv[0].spn = spn;
                    //}
                    toolsDiv[0].pn = toolsDiv[1].pn;
                    toolsDiv = toolsDiv.OrderByDescending(f => f.Dispaylevel).ToList();
                    //filtter
                    toolsDiv = toolsDiv.Where(f => f.surplus_life != null).ToList();
                    if (toolsDiv.Any())
                    {
                        resultTmp.data.Add(int.Parse(mc.Key), toolsDiv);
                    }
                }
            }
   
            MachineState.Dispose();
            MachineUsage.Dispose();
            
            return new ObjectResult(resultTmp);
        }

        DashBordToolsNode SetUsage(DashBordToolsNode dashbord,int? Toolife,ToolMachineCycleUsage usage,bool beCfg = true)
        {
            if ( beCfg )
            {
                if (usage.tc == 0 && usage.tl == 0)
                {
                    dashbord.ratelife = Toolife;
                    dashbord.surplus_life = Toolife - usage.usage;
                }else
                {
                    dashbord.ratelife = usage.tl;
                    dashbord.surplus_life = usage.tl - usage.tc;
                }
            }
            else //取设备值
            {
                dashbord.ratelife = usage.tl;
                dashbord.surplus_life = usage.tl - usage.tc;
            }
            dashbord.surplus_life = dashbord.surplus_life == null ? 0 : dashbord.surplus_life;
            return dashbord;
        }
        /// <summary>
        /// 获取产线层级
        /// </summary>
        /// <param name="sectionId"></param>
        /// <returns></returns>
        string GetSectionID(int sectionId)
        {
            var result = string.Empty;
            var ids = sigerProjectToolSpindleTrueRepository.GetParentLevelSectionIds(sectionId, ProjectId).Distinct().ToList().OrderByDescending(o=>o).ToList();

            for(int i=0;i <ids.Count;i++)
            {
                if (i != ids.Count-1)
                    result += ids[i].ToString() + ",";
                else
                    result += ids[i].ToString();
            }
            return result;
        }


        [HttpPost]
        public IActionResult GetProgramNolist([FromBody]RquestBlxProgramlist rquestBlx)
        {
            var data = sigerProjectToolSpindleTrueRepository.GetProcessProgramlist(ProjectId, rquestBlx.machine_id, rquestBlx.spindle_name);
            return new ObjectResult(data);
        }
        /// <summary>
        /// TMS1.6 刀具监控仪表盘
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [NoTokenValidateFilter]
        public IActionResult DashboardData([FromBody]RequestDashboard request)
        {
            //查找当前设备的运行状态
            var MachineState = new CNCEquipmentStateRepository(CompanyId, ProjectId, false);
            var MachineUsage = new ToolMachineCycleUsageRepository(CompanyId, ProjectId, false);
            var dapperData = new ToolAlarmRepository(CompanyId, ProjectId);
            var lstState = MachineState.GetCNCEquipmentStates();
            if (!lstState.Any())
            {
                MachineState.Dispose();
                MachineUsage.Dispose();
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var machine = _sigerProjectToolCutterLocationTrue.GetMachineBySection(request.sections,ProjectId);
            var stime = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.AddMinutes(-2));
            var etime = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now);
            var Kmdata = dapperData.GetToolAlarm(machine.Select(f => f.machine_id).ToList(), stime, etime, 0).ToList();

            var _dashbord = new ResponMoniterDisplay {
                 Machine=new List<ReponseMoniterDashboard>(),
                 Total=new ReponseMoniterDashboardTotal()
            };
            foreach (var mc in machine)
            {
                var cncEquipState = MachineState.GetCNCEquipmentState(mc.machine_id);
                if (cncEquipState == null)
                    continue;
                var cutterTrues = _sigerProjectToolCutterLocationTrue.GetCutterConfigsByMachine(mc.machine_id);
                if (!cutterTrues.Any())
                    continue;
                var procProgram = cncEquipState.PN + "/" + cncEquipState.SPN;
                var dashboardMachine = new ReponseMoniterDashboard
                {
                    SectionId=mc.section_id,
                    MachineId = mc.machine_id,
                    MachineName = mc.machine_name,
                    Progam = procProgram,
                    Setionlist = GetSectionID(mc.section_id),
                    Tools = new List<ReponseMoniterDashboardTools>()
                };
                foreach (var cutterObj in cutterTrues)
                {
                    var locate = $"主轴{cutterObj.SpindleName} - 刀位{cutterObj.CutterName}";
                    var toolname = string.Empty;
                    if (cutterObj.ToolId > 0)
                    {
                        var toolInfo = sigerProjectToolRepository.Get(cutterObj.ToolId);
                        toolname = toolInfo == null ? "" : toolInfo.name;
                    }
                    _dashbord.Total.NormalCount += 1;
                    var displayToolObj = new ReponseMoniterDashboardTools { Tooloacte = locate, Spindle = cutterObj.SpindleName, Tool = toolname, CutterName = cutterObj.CutterName };
                    var currentCutter = GetRunningCutterLoactionTrue(cutterObj.MachineId, cutterObj.SpindleName, cutterObj.CutterName, cncEquipState.PN, cncEquipState.SPN);
                    if (currentCutter == null)
                    {
                        //显示上一次配置最近配置
                        procProgram = MachineState.GetLastProcess(cutterObj.MachineId);
                        if (string.IsNullOrWhiteSpace(procProgram))
                            continue;
                        var pnType = procProgram.Substring(0, 1);
                        var lastProgram = procProgram.Substring(1, procProgram.Length - 1);
                        var lastCutter = GetLastCutterLocationTrue(cutterObj.MachineId, cutterObj.SpindleName, cutterObj.CutterName, lastProgram, pnType == ProgramType.mainProgram);
                        if (lastCutter == null)
                            continue;
                        var lastUsage = MachineUsage.GetCycleUsage(mc.machine_id, procProgram, cutterObj.SpindleName, cutterObj.CutterName);
                        displayToolObj.Ratedlife = lastCutter.ratedlife ?? 0;
                        if (lastUsage != null)
                        {
                            displayToolObj.Usage = lastUsage.usage;
                            displayToolObj.Surplus = displayToolObj.Ratedlife - lastUsage.usage;

                        }
                        var lpercent = Math.Round(Convert.ToDecimal(displayToolObj.Surplus) / Convert.ToDecimal(displayToolObj.Ratedlife) * 100, 1);
                        displayToolObj.Percent = lpercent;
                        if (lpercent < 15)
                        {
                            displayToolObj.AlarmGrade = AlarmGrade.ToolDieLine;
                            _dashbord.Total.LifeCount += 1;
                            _dashbord.Total.NormalCount -= 1;
                            if (lpercent < 0)
                                displayToolObj.Percent = 0;
                        }
                        displayToolObj.BackColor = ToolConst.Alarm.NORMAL_COLOR;
                        dashboardMachine.Tools.Add(displayToolObj);
                        continue;
                    }

                    if (currentCutter.is_processing_program == (int)ProcessProgram.NoConfig)
                        displayToolObj.PnNotRunning = 1;
                    else
                        dashboardMachine.Progam = currentCutter.is_processing_program == (int)ProcessProgram.MainProgram ? ProgramType.mainProgram + currentCutter.programno : ProgramType.subProgram + currentCutter.subprogramno;
                    displayToolObj.Ratedlife = currentCutter.ratedlife ?? 0;
                    
                    var usage = MachineUsage.GetCycleUsage(mc.machine_id, dashboardMachine.Progam, cutterObj.SpindleName, cutterObj.CutterName);
                    if (usage != null)
                    {
                        if (usage.tc == 0 && usage.tl == 0)
                        {
                            displayToolObj.Usage = usage.usage;
                            displayToolObj.Surplus = displayToolObj.Ratedlife - usage.usage;
                        }
                        else
                        {
                            displayToolObj.Ratedlife = usage.tl;
                            displayToolObj.Usage = usage.tc;
                            displayToolObj.Surplus = usage.tl - usage.tc;
                        }
                    }
                    //1.刀断刀是否报警
                    var tnAlarm = Kmdata.Find(f => f.MachineID == mc.machine_id && f.Spindle_name == cutterObj.SpindleName && f.Cutter_location_name == cutterObj.CutterName);
                    if (tnAlarm != null)
                    {
                        var Grade = (AlarmGrade)tnAlarm.Alarm_grade;
                        displayToolObj.AlarmGrade = Grade;
                        switch (Grade)
                        {
                            case AlarmGrade.Quality:
                                _dashbord.Total.QualityCount += 1;
                                _dashbord.Total.NormalCount -= 1;
                                break;
                            case AlarmGrade.Wear:
                                _dashbord.Total.WearCount += 1;
                                _dashbord.Total.NormalCount -= 1;
                                break;
                            case AlarmGrade.Broken:
                                _dashbord.Total.BrokenCount += 1;
                                _dashbord.Total.NormalCount -= 1;
                                break;
                            case AlarmGrade.Destroyed:
                                _dashbord.Total.BrokenCount += 1;
                                _dashbord.Total.NormalCount -= 1;
                                break;
                        }
                    }

                    var percent = Math.Round(Convert.ToDecimal(displayToolObj.Surplus) / Convert.ToDecimal(displayToolObj.Ratedlife) * 100, 1);
                    displayToolObj.Percent = percent;
                    if (percent < 15)
                    {
                        displayToolObj.AlarmGrade = AlarmGrade.ToolDieLine;
                        _dashbord.Total.LifeCount += 1;
                        _dashbord.Total.NormalCount -= 1;
                        if (percent < 0)
                            displayToolObj.Percent = 0;
                    }
                    displayToolObj.BackColor = ApiCommon.Utilities.CommonUtility.GetAlarmColor(displayToolObj.AlarmGrade);
                    dashboardMachine.Tools.Add(displayToolObj);
                }
                dashboardMachine.Tools.OrderByDescending(f => f.AlarmGrade);
                _dashbord.Machine.Add(dashboardMachine);
            }
            MachineState.Dispose();
            MachineUsage.Dispose();
            return new ObjectResult(_dashbord);
        }

        SigerProjectToolCutterLocationTrue GetRunningCutterLoactionTrue(int machineId, string spindleName, string cutterName, string cncPn,string cncSpn)
        {
            var spindleTrue = sigerProjectToolSpindleTrueRepository.Get(f => f.equipid == machineId && f.name == spindleName);
            if (spindleTrue == null)
                return null;
            var isProcessCutterTrue = _sigerProjectToolCutterLocationTrue.Get(f => f.spindleid == spindleTrue.id && f.name == cutterName && f.is_processing_program == (int)ProcessProgram.MainProgram && f.programno==cncPn);
            if (isProcessCutterTrue != null)
            {
                //先取PN 配置
                return isProcessCutterTrue;
            }
            else
            {
                //后取SPN 配置
                isProcessCutterTrue= _sigerProjectToolCutterLocationTrue.Get(f => f.spindleid == spindleTrue.id && f.name == cutterName && f.is_processing_program == (int)ProcessProgram.ChildProgram && f.subprogramno == cncSpn);
                return isProcessCutterTrue;
            }
            
        }
        /// <summary>
        ///  最近一次加工程序信息
        /// </summary>
        /// <param name="machineId">设备ID</param>
        /// <param name="spindleName">主轴号</param>
        /// <param name="cutterName">刀位号</param>
        /// <param name="program">程序号</param>
        /// <param name="IsMain">是否 主程序</param>
        /// <returns></returns>
        SigerProjectToolCutterLocationTrue GetLastCutterLocationTrue(int machineId, string spindleName,string cutterName, string program, bool IsMain)
        {
            var spindleTrue = sigerProjectToolSpindleTrueRepository.Get(f => f.equipid == machineId && f.name == spindleName);
            if (spindleTrue == null)
                return null;
            if (IsMain)
            {
                var cutterTrue = _sigerProjectToolCutterLocationTrue.Get(f => f.spindleid == spindleTrue.id && f.name == cutterName && f.programno==program && f.is_processing_program==(int)ProcessProgram.MainProgram);
                return cutterTrue;
            }else
            {
                var cutterTrue = _sigerProjectToolCutterLocationTrue.Get(f => f.spindleid == spindleTrue.id && f.name == cutterName && f.subprogramno == program && f.is_processing_program == (int)ProcessProgram.ChildProgram);
                return cutterTrue;
            }

        }

    }
}