using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using SlnMesnac.Business.@base;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Task = System.Threading.Tasks.Task;
using SlnMesnac.WPF.Page.IndexPage;
using System.Windows.Documents;
using SlnMesnac.TouchSocket;
using HslCommunication.Enthernet;
using SlnMesnac.Config;
using System.Threading;
using SlnMesnac.Common;
using SlnMesnac.Model.domain;
using System.Windows.Controls;
using SlnMesnac.Plc;
using SlnMesnac.Extensions;
using SlnMesnac.Business;
using Microsoft.IdentityModel.Logging;
using SlnMesnac.Model.dto;
using ATC_MaterialBind.Entity;
using System.Data;
using System.Dynamic;
using System.Drawing;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
using SlnMesnac.WPF.Attribute;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.WPF.ViewModel.IndexPage
* 唯一标识：ffdc8ddd-928f-4910-b6ac-d6d6426c39d0
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-09-05 15:05:57
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.WPF.ViewModel.IndexPage
{
    [RegisterAsSingletonAttribute]
    public partial class IndexContentViewModel : ObservableObject
    {
        private ILogger<IndexContentViewModel> _logger;
        private ILogger<BaseTaskInfoBusiness> _taskBusinessLogger;
        private DispatcherTimer _timer;
        private AppConfig _appConfig;
        private readonly MaterialBindBusiness? _materialBindBusiness;
        private ControlOffLineScanHelper _controlOffLineScanHelper;
        private bool QBarCode = false;
        private bool KBarCode = false;
        private static string StationCode;
        private IStationQualityInfoService _stationQualityInfoService;
        private IT_SY_TraceStateService _syTraceStateService;
        private IT_RP_ProductChangeInfoService _ProductChangeInfoService;
        private IT_RP_StationMaterialInventoryService _stationMaterialInventoryService;
        private IT_RP_InventoryConsume_RecordService _inventoryConsumeRecordService;
        public Action<List<StationQualityInfo>> _Action;
        private TaskInfo1 taskInfo;
        private AppsettingsConfig _appSettings = new AppsettingsConfig();
        private string WritePLCAddress = "D6000";
        private String _lastCode = string.Empty;
        private int stationid = 3;
        public IndexContentViewModel()
        {
            taskInfo = new TaskInfo1();
            LogMessages = new ObservableCollection<string>();
            _appConfig = App.ServiceProvider.GetService<AppConfig>();

            _logger = App.ServiceProvider.GetService<ILogger<IndexContentViewModel>>();
            _materialBindBusiness = App.ServiceProvider.GetService<MaterialBindBusiness>();
            _stationQualityInfoService = App.ServiceProvider.GetService<IStationQualityInfoService>();
            _syTraceStateService = App.ServiceProvider.GetService<IT_SY_TraceStateService>();
            _ProductChangeInfoService = App.ServiceProvider.GetService<IT_RP_ProductChangeInfoService>();
            _stationMaterialInventoryService = App.ServiceProvider.GetService<IT_RP_StationMaterialInventoryService>();
            _inventoryConsumeRecordService = App.ServiceProvider.GetService<IT_RP_InventoryConsume_RecordService>();
            _controlOffLineScanHelper = ControlOffLineScanHelper.Instance;
            _controlOffLineScanHelper.InstanceSerialPort(_appConfig.ComPort);
            StationCode = _appConfig.StationCode;
            OKCount = _appSettings.ReadAppSettings("ProductConfig:OKCount");
            //_appSettings.WriteAppSettings("ProductConfig", "OKCount", "2");
            NGCount = _appSettings.ReadAppSettings("ProductConfig:NGCount");
            this.Init();
        }
        private void Init()
        {
            _controlOffLineScanHelper.RecAutoDataAction += ShowBarCode;
            LoadStationInfo();
            #region 测试数据
            //LoadHDataInfo();
            //LoadEDataInfo();
            //LoadTaskInfo();
            //Thread.Sleep(5000);

            //_tcpServer.SendReplyGetManualException(
            //         _appConfig.visionConfig.Where(x => x.VisionPort == 7001).First().VisionPort.ToString()
            //    );

            //_StateRefreshBusiness.UpdateManipulatorStateByResposne(
            //    new Model.AirportApiEntity.ManipulatorStateRequestEntity() 
            //    { ManipulatorNo = "1", SignalSendTime = DateTime.Now.ToString()});
            //List<AirportTask> AirportTaskItem = _taskservice.GetTaskInfos();
            //TaskItems = new ObservableCollection<AirportTask>(AirportTaskItem);
            // TaskItems = new ObservableCollection<AirportTask>
            // {
            //     new AirportTask { TaskCode = "1", StationName = "1#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "2", StationName = "2#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "3", StationName = "3#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "4", StationName = "4#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "5", StationName = "5#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            //     new TaskItem { TaskCode = "6", StationName = "6#站台", TaskDetails = "入库：P04->C01", Status = "任务状态：执行中" },
            // };

            //RefreshLogMessage($"1#站台任务下发站台任务下发站台任务下发站台任务下发站台任务下发站台任务下发");
            //RefreshLogMessage($"2#站台任务下发");
            //RefreshLogMessage($"3#站台任务下发");
            //RefreshLogMessage($"4#站台任务下发");
            //RefreshLogMessage($"5#站台任务下发");
            //RefreshLogMessage($"6#站台任务下发");
            //RefreshLogMessage($"7#站台任务下发");
            //RefreshLogMessage($"2#站台任务下发");
            //RefreshLogMessage($"3#站台任务下发");
            //RefreshLogMessage($"4#站台任务下发");
            //RefreshLogMessage($"5#站台任务下发");
            //RefreshLogMessage($"6#站台任务下发");
            //RefreshLogMessage($"7#站台任务下发");

            //FlightItems = new ObservableCollection<FlightItem>
            //{
            //    new FlightItem { flightNumber = "航班号：CZ3021", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3022", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3023", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3024", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3025", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3026", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //    new FlightItem { flightNumber = "航班号：CZ3027", scheduledTime = "计划/变更：11:28", destination = "经停/目的：深圳",flightStatus="状态：到达",baggageClaim="转盘：1" },
            //};
            #endregion

            #region 更新时间显示
            //_currentDateTime = DateTime.Now;
            //_timer = new DispatcherTimer
            //{
            //    Interval = TimeSpan.FromSeconds(1) // 每秒更新一次
            //};
            //_timer.Tick += (s, e) =>
            //{
            //    CurrentDateTime = DateTime.Now;
            //};
            //_timer.Start();
            #endregion
        }

        private void LoadStationInfo()
        {
            //Products = new List<TaskInfo1> { new TaskInfo1 { TaskNo = "Some product", KBarCode = "Very cool product",QBarCode = "1",Station1 = "1", Station2 = "1", Station3 = "1", Station4 = "1", Station5 = "1", Station6 = "1" } };
            if (StationCode == "80_3")
            {
                stationid = 11;
                ColumnConfig = new ColumnConfig { Columns = new List<Column> { new Column { Header = "任务编号", DataField = "TaskNo" }, new Column { Header = "壳体条码", DataField = "KBarCode" }, new Column { Header = "前盖条码", DataField = "QBarCode" }, new Column { Header = "前盖轴封", DataField = "Station1" }, new Column { Header = "曲轴压入转子", DataField = "Station2" }, new Column { Header = "曲轴压入前盖", DataField = "Station3" }, new Column { Header = "电机壳压轴承", DataField = "Station4" }, new Column { Header = "前盖轴封检漏", DataField = "Station5" }, new Column { Header = "转子充磁", DataField = "Station6" }, new Column { Header = "记录时间", DataField = "RecordTime" } } };
            }
            else if (StationCode == "20_2")
            {
                stationid = 3;
                WritePLCAddress = "D6002";
                ColumnConfig = new ColumnConfig { Columns = new List<Column> { new Column { Header = "任务编号", DataField = "TaskNo" }, new Column { Header = "壳体条码", DataField = "KBarCode" }, new Column { Header = "控制器条码", DataField = "QBarCode" }, new Column { Header = "电机壳组件绝缘测试", DataField = "Station1" }, new Column { Header = "记录时间", DataField = "RecordTime" } } };
            }
            else if (StationCode == "200")
            {
                stationid = 24;
                ColumnConfig = new ColumnConfig { Columns = new List<Column> { new Column { Header = "任务编号", DataField = "TaskNo" }, new Column { Header = "壳体条码", DataField = "KBarCode" }, new Column { Header = "控制器条码", DataField = "QBarCode" }, new Column { Header = "记录时间", DataField = "RecordTime" } } };
            }
            else if (StationCode == "120_2")
            {
                stationid = 17;
                ColumnConfig = new ColumnConfig { Columns = new List<Column> { new Column { Header = "任务编号", DataField = "TaskNo" }, new Column { Header = "壳体条码", DataField = "KBarCode" }, new Column { Header = "静盘条码", DataField = "QBarCode" }, new Column { Header = "静盘排气阀片安装", DataField = "Station1" }, new Column { Header = "静盘反向气密性检测", DataField = "Station2" }, new Column { Header = "动静盘高度差测量", DataField = "Station3" }, new Column { Header = "动静盘BP环选配", DataField = "Station4" }, new Column { Header = "动静盘拍照", DataField = "Station5" },  new Column { Header = "记录时间", DataField = "RecordTime" } } };
               

            }
            else if (StationCode == "150")
            {
                stationid = 19;
                ColumnConfig = new ColumnConfig { Columns = new List<Column> { new Column { Header = "任务编号", DataField = "TaskNo" }, new Column { Header = "壳体条码", DataField = "KBarCode" }, new Column { Header = "后盖条码", DataField = "QBarCode" }, new Column { Header = "静盘背面和机壳端面高度测量", DataField = "Station1" }, new Column { Header = "记录时间", DataField = "RecordTime" } } };
            }


        }
        private void ShowBarCode(string BarCode)
        {
            RefreshLogMessage("扫描条码:" + BarCode.Substring(0, 20));
            if (BarCode.Substring(0, 20) == _lastCode)
            {
                RefreshLogMessage(BarCode.Substring(0, 20) + "已存在扫描记录，不允许重复扫描！");
                return;
            }
            _lastCode = BarCode.Substring(0, 20);
            JudgeMaterialType2(BarCode.Substring(0,20));

        }

        private void JudgeMaterialType2(string BarCode)
        {
            try
            {
                string BarCode1 = BarCode.Substring(6, 1);
                string BarCode2 = BarCode.Substring(7, 1);
                if (BarCode1 == "Q" || BarCode2 == "Q")
                {
                    //判断型号
                    if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                    {
                        var QProductType = JudgeProductType(BarCode);
                        if (!QProductType)
                        {
                            RefreshLogMessage(BarCode + "不符合当前型号！");
                            ClearText("全部");
                            return;
                        }
                    }
                    var flag2 = IsExistBarCodeRelationShip(BarCode, "2");
                    if (flag2)
                    {
                        RefreshLogMessage(BarCode + "已存在扫描绑定记录，不允许重复扫描！");
                        ClearText("全部");
                        return;
                    }
                    QBarCode = true;
                    ZJBoxCode = BarCode;
                    ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    ZJBusiness(BarCode);
                }
                if (BarCode1 == "K" || BarCode2 == "K")
                {
                    //判断型号
                    if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                    {
                        var KProductType = JudgeProductType(BarCode);
                        if (!KProductType)
                        {
                            RefreshLogMessage(BarCode + "不符合当前型号！");
                            ClearText("全部");
                            return;
                        }
                    }
                    var flag0 = IsExistBarCodeRelationShip(BarCode, "0");
                    if (flag0)
                    {
                        RefreshLogMessage(BarCode + "已存在扫描绑定记录，不允许重复扫描！");
                        ClearText("全部");
                        return;
                    }
                    QBarCode = true;
                    ZJBoxCode = BarCode;
                    ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    KXQCode_Bind(BarCode);
                }
                if (BarCode1 == "J" || BarCode2 == "J")
                {
                    if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                    {
                        var JProductType = JudgeProductType(BarCode);
                        if (!JProductType)
                        {
                            RefreshLogMessage(BarCode + "不符合当前型号！");
                            ClearText("全部");
                            return;
                        }
                    }
                    var flag3 = IsExistBarCodeRelationShip(BarCode, "3");
                    if (flag3)
                    {
                        RefreshLogMessage(BarCode + "已存在扫描绑定记录，不允许重复扫描！");
                        ClearText("全部");
                        return;
                    }
                    QBarCode = true;
                    ZJBoxCode = BarCode;
                    ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    ZJBusiness(BarCode);
                }
                if (BarCode1 == "H" || BarCode2 == "H")
                {
                    if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                    {
                        var HProductType = JudgeProductType(BarCode);
                        if (!HProductType)
                        {
                            RefreshLogMessage(BarCode + "不符合当前型号！");
                            ClearText("全部");
                            return;
                        }
                    }
                    var flag4 = IsExistBarCodeRelationShip(BarCode, "4");
                    if (flag4)
                    {
                        RefreshLogMessage(BarCode + "已存在扫描绑定记录，不允许重复扫描！");
                        ClearText("全部");
                        return;
                    }
                    QBarCode = true;
                    ZJBoxCode = BarCode;
                    ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    ZJBusiness(BarCode);
                }
                if (BarCode1 == "M" || BarCode2 == "M")
                {
                    if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                    {
                        var KTProductType = JudgeKTProductType(BarCode);
                        if (!KTProductType)
                        {
                            RefreshLogMessage(BarCode + "不符合当前型号！");
                            ClearText("全部");
                            return;
                        }
                    }
                    var flag5 = IsExistBarCodeRelationShip(BarCode, "1");
                    if (flag5)
                    {
                        RefreshLogMessage(BarCode + "已存在扫描绑定记录，不允许重复扫描！");
                        ClearText("全部");
                        return;
                    }
                    KBarCode = true;
                    KTBoxCode = BarCode;
                    KTBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    KTBusiness(BarCode);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
            }
        }

        private void JudgeMaterialType(string BarCode)
        {
            try
            {
                string BarCode1 = BarCode.Substring(6, 1);
                switch (BarCode1)
                {
                    case "Q":

                        //判断型号
                        if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                        {
                            var QProductType = JudgeProductType(BarCode);
                            if (!QProductType)
                            {
                                RefreshLogMessage(BarCode + "不符合当前型号！");
                                return;
                            }
                        }

                        //var flag2 = IsExistBarCodeRelationShip(BarCode, "2");
                        //if (flag2)
                        //{
                        //    RefreshLogMessage(BarCode + "已存在扫描记录，不允许重复扫描！");
                        //    return;
                        //}
                        QBarCode = true;
                        ZJBoxCode = BarCode;
                        ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ZJBusiness(BarCode);
                        break;
                    case "K":
                        //判断型号
                        if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                        {
                            var KProductType = JudgeProductType(BarCode);
                            if (!KProductType)
                            {
                                RefreshLogMessage(BarCode + "不符合当前型号！");
                                return;
                            }
                        }
                       
                        //var flag0 = IsExistBarCodeRelationShip(BarCode, "0");
                        //if (flag0)
                        //{
                        //    RefreshLogMessage(BarCode + "已存在扫描记录，不允许重复扫描！");
                        //    return;
                        //}
                        QBarCode = true;
                        ZJBoxCode = BarCode;
                        ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        KXQCode_Bind(BarCode);
                        break;
                    case "J":
                        if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                        {
                            var JProductType = JudgeProductType(BarCode);
                            if (!JProductType)
                            {
                                RefreshLogMessage(BarCode + "不符合当前型号！");
                                return;
                            }
                        }
                      
                        //var flag3 = IsExistBarCodeRelationShip(BarCode, "3");
                        //if (flag3)
                        //{
                        //    RefreshLogMessage(BarCode + "已存在扫描记录，不允许重复扫描！");
                        //    return;
                        //}
                        QBarCode = true;
                        ZJBoxCode = BarCode;
                        ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ZJBusiness(BarCode);
                        break;
                    case "H":
                        if (_appSettings.ReadAppSettings("ChangeTypeConfig:OpenFlag") == "1")
                        {
                            var HProductType = JudgeProductType(BarCode);
                            if (!HProductType)
                            {
                                RefreshLogMessage(BarCode + "不符合当前型号！");
                                return;
                            }
                        }
                       
                        //var flag4 = IsExistBarCodeRelationShip(BarCode, "4");
                        //if (flag4)
                        //{
                        //    RefreshLogMessage(BarCode + "已存在扫描记录，不允许重复扫描！");
                        //    return;
                        //}
                        QBarCode = true;
                        ZJBoxCode = BarCode;
                        ZJBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ZJBusiness(BarCode);

                        break;
                    case "M":
                        //var flag1 = IsExistBarCodeRelationShip(BarCode, "1");
                        //if (flag1)
                        //{
                        //    RefreshLogMessage(BarCode + "已存在扫描记录，不允许重复扫描！");
                        //    return;
                        //}
                        KBarCode = true;
                        KTBoxCode = BarCode;
                        KTBoxTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        KTBusiness(BarCode);
                        break;
                    default:
                        break;
                }

            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 统计扫描得OKNG数量
        /// </summary>
        /// <param name="type"></param>
        private void AddProductCount(String type)
        {
            if (type == "OK")
            {
                OKCount = (int.Parse(OKCount) + 1).ToString();
                _appSettings.WriteAppSettings("ProductConfig", "OKCount", OKCount);
            }
            else
            {
                NGCount = (int.Parse(NGCount) + 1).ToString();
                _appSettings.WriteAppSettings("ProductConfig", "NGCount", NGCount);
                //string count2 = _appSettings.ReadAppSettings("ProductConfig:NGCount");
                //NGCount = NGCount;
            }

        }
        private bool JudgeBatchCount(List<T_RP_StationMaterialInventory> t_RP_StationMaterialInventories)
        {
            bool iflag = false;
            try
            {
                foreach (T_RP_StationMaterialInventory t_RP in t_RP_StationMaterialInventories)
                {
                    T_RP_StationMaterialInventory t_RP_StationMaterialInventory = new T_RP_StationMaterialInventory();
                    t_RP_StationMaterialInventory = GetBatchNo(t_RP.materialTypeId);
                    int count = int.Parse(t_RP.remark);
                    int batchcount = t_RP_StationMaterialInventory.inputcount - count;
                    if (batchcount < 0)
                    {
                        RefreshLogMessage(t_RP.materialTypeId + "物料库存不足，请及时维护!");
                        iflag = true;
                        return iflag;
                    }
                }
                return iflag;
            }
            catch (Exception ex)
            {
                return iflag;
            }
        }

        private async void AddInventoryConsume_Record()
        {
            try
            {
                List<T_RP_StationMaterialInventory> t_RP_StationMaterialInventories = null;
                t_RP_StationMaterialInventories = GetMaterialInventoryCount();
                if (t_RP_StationMaterialInventories != null)
                {
                    if (t_RP_StationMaterialInventories.Count > 0)
                    {
                        bool icountflag = JudgeBatchCount(t_RP_StationMaterialInventories);
                        if (icountflag)
                        {
                            return;
                        }
                        foreach (T_RP_StationMaterialInventory t_RP in t_RP_StationMaterialInventories)
                        {
                            T_RP_StationMaterialInventory t_RP_StationMaterialInventory = new T_RP_StationMaterialInventory();
                            t_RP_StationMaterialInventory = GetBatchNo(t_RP.materialTypeId);
                            //判断批次库存是否满足扣料


                            if (t_RP_StationMaterialInventory != null)
                            {
                                bool iflag = await RealtimeInventoryDeduction(t_RP_StationMaterialInventory, t_RP.remark);
                                if (iflag)
                                {
                                    //存库
                                    T_RP_InventoryConsume_Record t_RP_InventoryConsume_Record = new T_RP_InventoryConsume_Record();
                                    t_RP_InventoryConsume_Record.materialtypeid = t_RP.materialTypeId;
                                    t_RP_InventoryConsume_Record.batchno = t_RP_StationMaterialInventory.batchno;
                                    t_RP_InventoryConsume_Record.consumecount = t_RP.remark;
                                    t_RP_InventoryConsume_Record.stationid = stationid;
                                    t_RP_InventoryConsume_Record.createTime = DateTime.Now;
                                    _inventoryConsumeRecordService.InsertAsync(t_RP_InventoryConsume_Record);
                                }
                            }
                            else
                            {
                                RefreshLogMessage(t_RP.materialTypeId + "物料库存不足，请及时维护!");
                                return;
                            }
                        }

                    }


                }
                
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 获取工位物料构成
        /// </summary>
        private List<T_RP_StationMaterialInventory> GetMaterialInventoryCount()
        {
            List<T_RP_StationMaterialInventory> t_RP_StationMaterialInventories = null;
            try
            {
                t_RP_StationMaterialInventories = _stationMaterialInventoryService.GetMaterialShip(stationid);
                return t_RP_StationMaterialInventories;
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
                return t_RP_StationMaterialInventories;
            }
        }
        private T_RP_StationMaterialInventory GetBatchNo(string materialTypeId)
        {
            T_RP_StationMaterialInventory t_RP_StationMaterialInventory = null;
            try
            {
                t_RP_StationMaterialInventory = _stationMaterialInventoryService.GetBatchNoByMaterialTypeID(materialTypeId, stationid);
                return t_RP_StationMaterialInventory;
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
                return t_RP_StationMaterialInventory;
            }
        }

        private async Task<bool> RealtimeInventoryDeduction(T_RP_StationMaterialInventory t_RP_StationMaterialInventory, string count)
        {
            bool iFlag = false;
            try
            {
                int icount = int.Parse(count);
                if (t_RP_StationMaterialInventory.inputcount > 0)
                {
                    t_RP_StationMaterialInventory.inputcount = t_RP_StationMaterialInventory.inputcount - icount;
                    t_RP_StationMaterialInventory.updateTime = DateTime.Now;
                    iFlag = await _stationMaterialInventoryService.UpdateAsync(t_RP_StationMaterialInventory);
                    return iFlag;
                }
                else
                {
                    //库存不足提示

                    return iFlag;
                }
              
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
                return iFlag;
            }
        }

        private async void ZJBusiness(string BarCode)
        {
            try
            {
                if (StationCode == "80_3")
                {
                    List<StationQualityInfo> stationQualityInfos = await _stationQualityInfoService.GetProductQuality(BarCode, StationCode);
                    if (stationQualityInfos != null && stationQualityInfos.Count > 0)
                    {
                        //StationQualityInfos = new ObservableCollection<StationQualityInfo>(stationQualityInfos);
                        taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                        stationQualityInfos.ForEach(x =>
                        {
                            if (x.TableName == "T_RP_StationPara_40")
                            {
                                taskInfo.Station1 = x.State == "1" ? "OK" : "NG";
                            }
                            else if (x.TableName == "T_RP_StationPara_50")
                            {
                                taskInfo.Station2 = x.State == "1" ? "OK" : "NG";
                            }
                            else if (x.TableName == "T_RP_StationPara_60")
                            {
                                taskInfo.Station3 = x.State == "1" ? "OK" : "NG";
                            }
                            //else if (x.TableName == "T_RP_StationPara_70")
                            //{
                            //    taskInfo.Station4 = x.State == "1" ? "OK" : "NG";
                            //}
                            else if (x.TableName == "T_RP_StationPara_80_1")
                            {
                                taskInfo.Station5 = x.State == "1" ? "OK" : "NG";
                            }
                            else if (x.TableName == "T_RP_StationPara_80_2")
                            {
                                taskInfo.Station6 = x.State == "1" ? "OK" : "NG";
                            }
                        });
                        var flag = stationQualityInfos.FindAll(x => x.State != "1");
                        if (flag != null && flag.Count != 0)
                        {
                            var Writeflag = _materialBindBusiness.NG_BJSignal(WritePLCAddress,2);
                            _Action?.Invoke(stationQualityInfos);
                            KBarCode = false;
                            QBarCode = false;
                            ClearText("全部");
                            AddProductCount("NG");

                        }
                        else
                        {
                            _Action?.Invoke(stationQualityInfos);
                            if (KBarCode && QBarCode)
                            {
                                var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                taskInfo.QBarCode = ZJBoxCode;
                                taskInfo.KBarCode = KTBoxCode;
                                RefreshDataGrid(taskInfo);
                                MaterialBing(KTBoxCode, ZJBoxCode);
                                AddProductCount("OK");
                                AddInventoryConsume_Record();

                                //_Action?.Invoke(null);

                            }
                        }

                    }
                    else
                    {
                        _Action?.Invoke(stationQualityInfos);
                        if (KBarCode && QBarCode)
                        {
                            var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            MaterialBing(KTBoxCode, ZJBoxCode);
                            AddProductCount("OK");
                            AddInventoryConsume_Record();
                            //_Action?.Invoke(null);

                        }
                    }
                }
                else if (StationCode == "120_2")
                {
                    JCode_Bind(BarCode);
                }
                else if (StationCode == "20_2")
                {
                    KXQCode_Bind(BarCode);
                }
                else if (StationCode == "200")
                {
                    KXQCode_Bind(BarCode);
                }
                else if (StationCode == "150")
                {
                    if (KBarCode && QBarCode)
                    {
                        if (!string.IsNullOrEmpty(ZJBoxCode) && !string.IsNullOrEmpty(KTBoxCode))
                        {
                            AddProductCount("OK");
                            var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            UpdateTrace(KTBoxCode, ZJBoxCode);
                            AddInventoryConsume_Record();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");

            }
        }
        public async void KTBusiness(string barcode)
        {
            //壳体与前盖绑定
            try
            {
                if (StationCode == "150")
                {
                    HCode_Bind(barcode);
                    return;
                }
                if (StationCode == "20_2")
                {
                    //控制器互锁
                    KCode_Bind(barcode);
                    return;
                }
                else
                {
                    if (StationCode == "80_3")
                    {
                        List<StationQualityInfo> stationQualityInfos = await _stationQualityInfoService.GetProductQuality(barcode, StationCode);
                        if (stationQualityInfos != null && stationQualityInfos.Count > 0)
                        {
                            //StationQualityInfos = new ObservableCollection<StationQualityInfo>(stationQualityInfos);
                            taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                            stationQualityInfos.ForEach(x =>
                            {
                                if (x.TableName == "T_RP_StationPara_70")
                                {
                                    taskInfo.Station4 = x.State == "1" ? "OK" : "NG";
                                }
                            });
                            var flag = stationQualityInfos.FindAll(x => x.State != "1");
                            if (flag != null && flag.Count != 0)
                            {
                                var Writeflag = _materialBindBusiness.NG_BJSignal(WritePLCAddress,2);
                                _Action?.Invoke(stationQualityInfos);
                                KBarCode = false;
                                QBarCode = false;
                                ClearText("全部");
                                AddProductCount("NG");
                            }
                            else
                            {
                                _Action?.Invoke(stationQualityInfos);
                                if (KBarCode && QBarCode)
                                {
                                    var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                    taskInfo.QBarCode = ZJBoxCode;
                                    taskInfo.KBarCode = KTBoxCode;
                                    RefreshDataGrid(taskInfo);
                                    MaterialBing(KTBoxCode, ZJBoxCode);
                                    AddProductCount("OK");
                                    AddInventoryConsume_Record();

                                    //_Action?.Invoke(null);
                                    return;

                                }
                            }

                        }
                        else
                        {
                            _Action?.Invoke(stationQualityInfos);
                            if (KBarCode && QBarCode)
                            {
                                var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                taskInfo.QBarCode = ZJBoxCode;
                                taskInfo.KBarCode = KTBoxCode;
                                RefreshDataGrid(taskInfo);
                                MaterialBing(KTBoxCode, ZJBoxCode);
                                AddProductCount("OK");
                                AddInventoryConsume_Record();

                                //_Action?.Invoke(null);
                                return;


                            }
                        }
                    }

                    if (KBarCode && QBarCode)
                    {
                        if (!string.IsNullOrEmpty(ZJBoxCode) && !string.IsNullOrEmpty(KTBoxCode))
                        {
                            taskInfo.RecordTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") ;
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            //Fresh_TaskInfo_dgv(taskInfo);
                            if (StationCode == "80_3")
                            {
                                MaterialBing(barcode, ZJBoxCode);
                            }
                            else if (StationCode == "120_2")
                            {
                                UpdateTrace(barcode, ZJBoxCode);
                            }
                            //else if (StationCode == "20_2")
                            //{
                            //    MaterialBing(barcode, ZJBoxCode);
                            //}
                            else if (StationCode == "200")
                            {
                                UpdateTrace(barcode, ZJBoxCode);
                            }
                            AddProductCount("OK");
                            var WritePLCFlag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            AddInventoryConsume_Record();

                        }

                    }
                    //else
                    //{
                    //    ClearText();
                    //}
                }

            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");
            }
        }
        private async void KCode_Bind(string BarCode)
        {
            try
            {
                if (BarCode.Length != 0 && BarCode != "")
                {
                    List<StationQualityInfo> stationQualityInfos = await _stationQualityInfoService.GetProductQuality(BarCode, StationCode);
                    if (stationQualityInfos != null && stationQualityInfos.Count > 0)
                    {
                        taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                        stationQualityInfos.ForEach(x =>
                        {
                            if (x.TableName == "T_RP_StationPara_20_1")
                            {
                                taskInfo.Station1 = x.State == "1" ? "OK" : "NG";
                            }
                        });
                        var flag = stationQualityInfos.FindAll(x => x.State != "1");
                        if (flag != null && flag.Count != 0)
                        {
                            var Writeflag = _materialBindBusiness.NG_BJSignal(WritePLCAddress, 2);
                            _Action?.Invoke(stationQualityInfos);
                            KBarCode = false;
                            QBarCode = false;
                            ClearText("全部");
                            AddProductCount("NG");
                        }
                        else
                        {
                            _Action?.Invoke(stationQualityInfos);
                            if (KBarCode && QBarCode)
                            {
                                AddProductCount("OK");
                                var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                taskInfo.QBarCode = ZJBoxCode;
                                taskInfo.KBarCode = KTBoxCode;
                                RefreshDataGrid(taskInfo);
                                MaterialBing(KTBoxCode, ZJBoxCode);
                                AddInventoryConsume_Record();
                            }
                        }
                    }
                    else
                    {
                        _Action?.Invoke(stationQualityInfos);
                        if (KBarCode && QBarCode)
                        {
                            var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            MaterialBing(KTBoxCode, ZJBoxCode);
                            AddProductCount("OK");
                            AddInventoryConsume_Record();

                            //_Action?.Invoke(null);

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                LogHelper.LogInformation(ex.ToString());

            }

        }
        private async void HCode_Bind(string BarCode)
        {
            try
            {
                if (BarCode.Length != 0 && BarCode != "")
                {
                    List<StationQualityInfo> stationQualityInfos = await _stationQualityInfoService.GetProductQuality(BarCode, StationCode);
                    if (stationQualityInfos != null && stationQualityInfos.Count > 0)
                    {
                        taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                        stationQualityInfos.ForEach(x =>
                        {
                            if (x.TableName == "T_RP_StationPara_130")
                            {
                                taskInfo.Station1 = x.State == "1" ? "OK" : "NG";
                            }
                        });
                        var flag = stationQualityInfos.FindAll(x => x.State != "1");
                        if (flag != null && flag.Count != 0)
                        {
                            var Writeflag = _materialBindBusiness.NG_BJSignal(WritePLCAddress,2);
                            _Action?.Invoke(stationQualityInfos);
                            KBarCode = false;
                            QBarCode = false;
                            ClearText("全部");
                            AddProductCount("NG");
                        }
                        else
                        {
                            _Action?.Invoke(stationQualityInfos);
                            if (KBarCode && QBarCode)
                            {
                                AddProductCount("OK");
                                var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                taskInfo.QBarCode = ZJBoxCode;
                                taskInfo.KBarCode = KTBoxCode;
                                RefreshDataGrid(taskInfo);
                                UpdateTrace(KTBoxCode,ZJBoxCode);
                                AddInventoryConsume_Record();

                            }
                        }
                    }
                    else
                    {
                        _Action?.Invoke(stationQualityInfos);
                        if (KBarCode && QBarCode)
                        {
                            var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            UpdateTrace(KTBoxCode, ZJBoxCode);
                            AddProductCount("OK");
                            AddInventoryConsume_Record();

                            //_Action?.Invoke(null);

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                LogHelper.LogInformation(ex.ToString());

            }
        }
        /// <summary>
        /// 更新工位Trace表数据
        /// </summary>
        private async void UpdateTrace(string BarCode,string ZJBarCode)
        {
            try
            {
                var GetFlag = _syTraceStateService.GetByProductCode(BarCode);

                if (GetFlag != null)
                {
                    //动静盘上线工位
                    if (StationCode == "120_2")
                    {
                        if (GetFlag.semibarcodeB != ZJBarCode)
                        {
                            GetFlag.semibarcodeB = ZJBarCode;
                            GetFlag.currentstationid = "17";

                        }
                    }
                    else if (StationCode == "200")
                    {
                        if (GetFlag.semibarcode2 != ZJBarCode)
                        {
                            GetFlag.semibarcode2 = ZJBarCode;
                            GetFlag.currentstationid = "24";

                        }
                    }
                    //后盖
                    else if (StationCode == "150")
                    {
                        if (GetFlag.semibarcodeC != ZJBarCode)
                        {
                            GetFlag.semibarcodeC = ZJBarCode;
                            GetFlag.currentstationid = "19";
                        }
                    }
                    bool flag = await _syTraceStateService.UpdateAsync(GetFlag);
                    if (flag)
                    {
                        LogHelper.LogInformation("更新工位数据成功" + StringChange.ModeToJson(GetFlag));
                    }
                }
                else
                {
                    T_SY_TraceState t_SY_TraceState = null;
                    string MBarcoe = _stationQualityInfoService.GetNewMainBarcode();
                    string productID = _ProductChangeInfoService.GetProductType().productid.ToString();

                    if (StationCode == "120_2")
                    {
                        t_SY_TraceState = new T_SY_TraceState
                        {
                            barcode = MBarcoe,
                            begintime = DateTime.Now,
                            productbarcode = BarCode,
                            currentstationid = "17",
                            semibarcodeB = ZJBarCode,
                            state = "1",
                            productid = productID
                        };
                    }
                    else if (StationCode == "150")
                    {
                        t_SY_TraceState = new T_SY_TraceState
                        {
                            barcode = MBarcoe,
                            begintime = DateTime.Now,
                            productbarcode = BarCode,
                            currentstationid = "19",
                            semibarcodeC = ZJBarCode,
                            state = "1",
                            productid = productID

                        };
                    }
                    else if (StationCode == "200")
                    {
                        t_SY_TraceState = new T_SY_TraceState
                        {
                            barcode = MBarcoe,
                            begintime = DateTime.Now,
                            productbarcode = BarCode,
                            currentstationid = "24",
                            semibarcode2 = ZJBarCode,
                            state = "1",
                            productid = productID

                        };
                    }
                    var flag = await _syTraceStateService.InsertAsync(t_SY_TraceState);

                }
                ClearText("全部");
            }
            catch (Exception ex)
            {
                LogHelper.LogInformation(ex.ToString());
            }
        }
        private async void MaterialBing(string ProductCode, string ZJBarCode)
        {
            try
            {
                T_SY_TraceState t_SY_TraceState = new T_SY_TraceState();
                //判断是否已经存在绑定关系，存在则更新
                var GetFlag = _syTraceStateService.GetByProductCode(ProductCode);
                if (GetFlag != null)
                {
                    if (StationCode == "20_2")
                    {
                        GetFlag.semibarcode2 = ZJBarCode;
                        GetFlag.currentstationid = "3";
                    }
                    else
                    {
                        GetFlag.semibarcodeA = ZJBarCode;
                        GetFlag.currentstationid = "11";
                    }
                    var flag = await _syTraceStateService.UpdateAsync(GetFlag);
                    if (flag)
                    {
                        _logger.LogInformation("更新工位数据成功" + StringChange.ModeToJson(GetFlag));
                    }

                }
                else
                {
                    string MBarcoe = _stationQualityInfoService.GetNewMainBarcode();
                    //_logger.LogInformation(MBarcoe);
                    //查询型号
                    T_RP_ProductChangeInfo t_RP_ProductChangeInfo = _ProductChangeInfoService.GetProductType();
                    string productID = "";
                    if (t_RP_ProductChangeInfo != null)
                    {
                        productID = t_RP_ProductChangeInfo.productid.ToString();
                    }
                  
                    //插入关系表
                    if (StationCode == "80_3")
                    {
                        t_SY_TraceState = new T_SY_TraceState
                        {
                            barcode = MBarcoe,
                            begintime = DateTime.Now,
                            productbarcode = ProductCode,
                            currentstationid = "11",
                            semibarcodeA = ZJBarCode,
                            state = "1",
                            productid = productID
                        };
                    }
                    else if (StationCode == "20_2")
                    {
                        t_SY_TraceState = new T_SY_TraceState
                        {
                            barcode = MBarcoe,
                            begintime = DateTime.Now,
                            productbarcode = ProductCode,
                            currentstationid = "3",
                            semibarcode2 = ZJBarCode,
                            state = "1",
                            productid = productID

                        };
                    }
                    var flag = await _syTraceStateService.InsertAsync(t_SY_TraceState);
                    //var flag = true;
                    if (flag)
                    {
                        _logger.LogInformation("更新工位数据成功" + StringChange.ModeToJson(t_SY_TraceState));
                    }
                }
                //清空条码
                ClearText("全部");
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");

            }
        }
        private void KXQCode_Bind(string BarCode)
        {
            try
            {
                if (BarCode.Length != 0 && BarCode != "")
                {
                    taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                    taskInfo.RecordTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    if (KBarCode && QBarCode)
                    {
                        AddProductCount("OK");
                        taskInfo.QBarCode = ZJBoxCode;
                        taskInfo.KBarCode = KTBoxCode;
                        RefreshDataGrid(taskInfo);
                        if (StationCode == "200")
                        {
                            UpdateTrace(KTBoxCode,ZJBoxCode);
                        }
                        else
                        {
                            MaterialBing(KTBoxCode, ZJBoxCode);
                        }

                        var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                        AddInventoryConsume_Record();

                        //ClearText();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogInformation(ex.ToString());
            }
        }
        private async void JCode_Bind(string BarCode)
        {
            try
            {
                if (BarCode.Length != 0 && BarCode != "")
                {
                    List<StationQualityInfo> stationQualityInfos = await _stationQualityInfoService.GetProductQuality(BarCode, StationCode);
                    if (stationQualityInfos != null && stationQualityInfos.Count > 0)
                    {
                        taskInfo.TaskNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                        stationQualityInfos.ForEach(x =>
                        {
                            if (x.TableName == "T_RP_StationPara_100")
                            {
                                taskInfo.Station1 = x.State == "1" ? "OK" : "NG";
                            }
                            if (x.TableName == "T_RP_StationPara_100_1")
                            {
                                taskInfo.Station2 = x.State == "1" ? "OK" : "NG";
                            }
                            if (x.TableName == "T_RP_StationPara_110_1")
                            {
                                taskInfo.Station3 = x.State == "1" ? "OK" : "NG";
                            }
                            if (x.TableName == "T_RP_StationPara_110_2")
                            {
                                taskInfo.Station4 = x.State == "1" ? "OK" : "NG";
                            }
                            if (x.TableName == "T_RP_StationPara_120_1")
                            {
                                taskInfo.Station5 = x.State == "1" ? "OK" : "NG";
                            }
                        });
                        var flag = stationQualityInfos.FindAll(x => x.State != "1");
                        if (flag != null && flag.Count != 0)
                        {
                            var Writeflag = _materialBindBusiness.NG_BJSignal(WritePLCAddress, 2);
                            _Action?.Invoke(stationQualityInfos);
                            ClearText("全部");
                            AddProductCount("NG");
                        }
                        else
                        {
                            _Action?.Invoke(stationQualityInfos);
                            if (KBarCode && QBarCode)
                            {
                                AddProductCount("OK");
                                var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                                taskInfo.QBarCode = ZJBoxCode;
                                taskInfo.KBarCode = KTBoxCode;
                                RefreshDataGrid(taskInfo);
                                UpdateTrace(KTBoxCode, ZJBoxCode);
                                AddInventoryConsume_Record();

                            }
                        }

                    }
                    else
                    {
                        _Action?.Invoke(stationQualityInfos);
                        if (KBarCode && QBarCode)
                        {
                            var Writeflag = _materialBindBusiness.OK_FXSignal(WritePLCAddress);
                            taskInfo.QBarCode = ZJBoxCode;
                            taskInfo.KBarCode = KTBoxCode;
                            RefreshDataGrid(taskInfo);
                            UpdateTrace(KTBoxCode, ZJBoxCode);
                            AddProductCount("OK");
                            AddInventoryConsume_Record();

                            //_Action?.Invoke(null);

                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.LogInformation(ex.ToString());

            }
        }

        private void ClearText(string Material)
        {
            //清空壳体条码显示
            if (Material == "壳体")
            {
                KTBoxCode = string.Empty;
                KTBoxTime = string.Empty;
            }
            //清空组件条码显示
            else if (Material == "组件")
            {
                ZJBoxCode = string.Empty;
                ZJBoxTime = string.Empty;
            }
            else
            {
                KTBoxCode = string.Empty;
                KTBoxTime = string.Empty;
                ZJBoxCode = string.Empty;
                ZJBoxTime = string.Empty;
            }
           
            KBarCode = false;
            QBarCode = false;
        }
        private bool JudgeProductType(string Barcode)
        {
            bool flag = false;
            try
            {
                string ProductType = _appSettings.ReadAppSettings("ChangeTypeConfig:ProductType");
                string ScanBarCodeType = Barcode.Substring(0, ProductType.Length);
                if (ProductType == ScanBarCodeType)
                {
                    flag = true;
                }
                return flag;
            }
            catch (Exception ex)
            {
                return flag;
            }
        }
        /// <summary>
        /// 壳体型号判断
        /// </summary>
        /// <param name="Barcode"></param>
        /// <returns></returns>
        private bool JudgeKTProductType(string Barcode)
        {
            bool flag = false;
            try
            {
                string ProductType = _appSettings.ReadAppSettings("ChangeTypeConfig:KTProductType");
                string ScanBarCodeType = Barcode.Substring(0, ProductType.Length);
                if (ProductType == ScanBarCodeType)
                {
                    flag = true;
                }
                return flag;
            }
            catch (Exception ex)
            {
                return flag;
            }
        }
        /// <summary>
        /// 判断是否已经存在绑定关系
        /// </summary>
        private bool IsExistBarCodeRelationShip(string Barcode, string MaterialType)
        {
            bool flag = false;
            try
            {
                var TraceState = _syTraceStateService.GetRelationShipByProductCodeAndIsdis(Barcode, MaterialType, StationCode);
                if (TraceState != null)
                {
                    return true;
                }
                else
                {
                    return flag;
                }
            }
            catch (Exception ex)
            {
                return flag;
            }
        }


        public async void RefreshDataGrid(TaskInfo1 taskInfo)
        {
            await App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                taskInfo.RecordTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                TaskInfoDataGrid.OrderBy(x=>x.RecordTime);
                TaskInfoDataGrid.Add(taskInfo);
            }));

        }

        #region 参数定义
        /// <summary>
        /// 任务列表
        /// </summary>
        private ObservableCollection<AirportTask> _taskItems = new ObservableCollection<AirportTask>();
        public ObservableCollection<AirportTask> TaskItems
        {
            get => _taskItems;
            set => SetProperty(ref _taskItems, value);
        }
        /// <summary>
        /// 日志信息
        /// </summary>
        private ObservableCollection<string> _logMessages = new ObservableCollection<string>();

        public ObservableCollection<string> LogMessages
        {
            get => _logMessages;
            set => SetProperty(ref _logMessages, value);
        }
        private string _OKCount = "0";

        /// <summary>
        /// OK数显示
        /// </summary>
        public string OKCount
        {
            get => _OKCount;
            set
            {
                if (_OKCount != value)
                {
                    SetProperty(ref _OKCount, value);
                }

            }
        }
        private string _NGCount = "0";

        /// <summary>
        /// OK数显示
        /// </summary>
        public string NGCount
        {
            get => _NGCount;
            set
            {
                if (_NGCount != value)
                {
                    SetProperty(ref _NGCount, value);
                }
            }
        }
        /// <summary>
        /// 壳体条码扫描时间显示
        /// </summary>
        private string _KTBoxTime = string.Empty;
        public string KTBoxTime
        {
            get => _KTBoxTime;
            set
            {
                if (_KTBoxTime != value)
                {
                    SetProperty(ref _KTBoxTime, value);
                }
            }
        }
        private string _KTBoxCode = string.Empty;

        /// <summary>
        /// 壳体条码显示
        /// </summary>
        public string KTBoxCode
        {
            get => _KTBoxCode;
            set
            {
                if (_KTBoxCode != value)
                {
                    SetProperty(ref _KTBoxCode, value);
                }
            }
        }
        /// <summary>
        /// 组件条码扫描时间显示
        /// </summary>
        private string _ZJBoxTime = string.Empty;
        public string ZJBoxTime
        {
            get => _ZJBoxTime;
            set
            {
                if (_ZJBoxTime != value)
                {
                    SetProperty(ref _ZJBoxTime, value);
                }
            }
        }
        private string _ZJBoxCode = string.Empty;

        /// <summary>
        /// 组件条码显示
        /// </summary>
        public string ZJBoxCode
        {
            get => _ZJBoxCode;
            set
            {
                if (_ZJBoxCode != value)
                {
                    SetProperty(ref _ZJBoxCode, value);
                }
            }
        }
        /// <summary>
        /// 日期时间
        /// </summary>
        private DateTime _currentDateTime;
        public DateTime CurrentDateTime
        {
            get => _currentDateTime;
            set
            {
                if (_currentDateTime != value)
                {
                    SetProperty(ref _currentDateTime, value);
                }
            }
        }
        /// <summary>
        /// 工位信息
        /// </summary>
        private ObservableCollection<StationQualityInfo> _stationQualityInfos1 = new ObservableCollection<StationQualityInfo>();
        public ObservableCollection<StationQualityInfo> StationQualityInfos
        {
            get => _stationQualityInfos1;
            set => SetProperty(ref _stationQualityInfos1, value);
        }
        #endregion
        #region 初始化datagrid
        private ObservableCollection<TaskInfo1> _TaskInfoDataGrid = new ObservableCollection<TaskInfo1>();
        public ObservableCollection<TaskInfo1> TaskInfoDataGrid
        {
            get => _TaskInfoDataGrid;
            set => SetProperty(ref _TaskInfoDataGrid, value);
        }
        #endregion
        /// <summary>
        /// 刷新日志
        /// </summary>
        /// <param name="msg"></param>
        public void RefreshLogMessage(string msg)
        {
            try
            {
                App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    LogMessages.Add($"{DateTime.Now}: {msg}");
                    while (LogMessages.Count > 10)
                    {
                        LogMessages.RemoveAt(0);
                    }
                    var orderedList = LogMessages.OrderByDescending(x => x);  // 排序后转为 List
                    LogMessages = new ObservableCollection<string>(orderedList);
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常:{ex.Message}");

            }

        }
        /// <summary>
        /// 系统运行日志输出
        /// </summary>
        /// <param name="message"></param>
        private async void PrintMessageToListBox(string message)
        {
            await Task.Run(() =>
            {
                try
                {
                    string formattedMessage = $"{DateTime.Now.ToString("HH:mm:ss.ss")} ==> {message}";

                    lock (LogMessages)
                    {
                        LogMessages.Add(formattedMessage);

                        while (LogMessages.Count > 120)
                        {
                            LogMessages.RemoveAt(0);
                        }

                        var orderedList = LogMessages.OrderByDescending(x => x).ToList();  // 排序后转为 List

                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"日志数据绑定异常:{ex.Message}");
                }
            });
        }
        /// <summary>
        /// 添加任务
        /// </summary>
        [RelayCommand]
        private void AddTask()
        {
            //生成任务号
            //输入航班号
            //任务状态默认等待
            AddTaskContent AddTaskContent = new AddTaskContent();
            AddTaskContent._Taskaction = task =>
            {
                if (task != null)
                {
                    var x = TaskItems.ToList().Find(x => x.conveyorno == task.conveyorno);
                    if (x != null)
                    {
                        x.id = task.id;
                        x.taskno = task.taskno;
                        x.flightno = task.flightno;
                        x.manipulatorno = task.manipulatorno;
                        x.agvno = task.agvno;
                        x.taskstate = task.taskstate;
                        TaskItems = new ObservableCollection<AirportTask>(TaskItems);
                    }
                    else
                    {
                        TaskItems.Add(task);
                    }
                }
            };
            AddTaskContent.ShowDialog();
            if ((bool)AddTaskContent.DialogResult)
            {
                RefreshLogMessage("任务添加成功!");
            }


        }

        /// <summary>
        /// 处理任务
        /// </summary>
        /// <param name="taskCode"></param>
        [RelayCommand]
        private void HandleTask(AirportTask taskCode)
        {
            var info = taskCode;
            if (info != null)
            {

                DetailTaskContent DetailTaskContent = new DetailTaskContent();
                DetailTaskContent.AirportTask = taskCode;
                DetailTaskContent.ShowDialog();
            }
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="taskCode"></param>
        [RelayCommand]
        private void DeleteTask(AirportTask task)
        {
            if (task.taskstate != "等待")
            {
                MessageBox.Show("任务已下发,不允许删除!");
            }
            else
            {
                if (MessageBox.Show("请确认是否删除该任务?", "Confirm Message", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    //根据任务号删除任务
                    TaskItems.Remove(task);
                    //清表
                    //TaskItems = new ObservableCollection<AirportTask>(TaskItems);
                    //LoadTaskInfo();
                }

            }
        }

        /// <summary>
        /// 手动呼叫
        /// </summary>
        [RelayCommand]
        private void ManualCall()
        {
            MessageBox.Show("手动呼叫");
        }

        /// <summary>
        /// 手动终止
        /// </summary>
        [RelayCommand]
        private void ManualTerminate()
        {
            MessageBox.Show("手动终止");
        }

        /// <summary>
        /// 复位
        /// </summary>
        [RelayCommand]
        private void Reset()
        {
            OKCount = "0";
            NGCount = "0";
            _appSettings.WriteAppSettings("ProductConfig", "OKCount", OKCount);
            _appSettings.WriteAppSettings("ProductConfig", "NGCount", NGCount);
            //TaskInfo1 TaskInfo1 = new TaskInfo1 { TaskNo = "Some product", KBarCode = "Very cool product", QBarCode = "1", Station1 = "1", Station2 = "1", Station3 = "1", Station4 = "1", Station5 = "1", Station6 = "1", RecordTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
            //RefreshDataGrid(TaskInfo1);

        }
        //private DataGrid dataGrid;
        //private ObservableCollection<ExpandoObject> _TaskInfoDataGrid;
        //public ObservableCollection<ExpandoObject> TaskInfoDataGrid
        //{
        //    get { return _TaskInfoDataGrid; }
        //    set { SetProperty(ref _TaskInfoDataGrid, value); }
        //}
        public ColumnConfig ColumnConfig { get; set; }
        public IEnumerable<TaskInfo1> Products { get; set; }
       

    }
    public class ColumnConfig
    {
        public IEnumerable<Column> Columns { get; set; }
    }

    public class Column
    {
        public string Header { get; set; }
        public string DataField { get; set; }
    }
}

