using Common.Models;
using CommunityToolkit.Mvvm.Messaging;
using MegaRobo.Entities;
using MegaRobo.Logger;
using Newtonsoft.Json.Linq;
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation.Text;
using System.Windows.Data;

namespace MegaRobo.C00225155.AppServer.ExecuteWorks
{
    /// <summary>
    /// 这里主要写检测工站的和PLC通讯的函数
    /// </summary>
    public partial class StationService_ReactionProcessing : StationServiceBase
    {
        //#region  PLC点位写/读
        ///// <summary>
        ///// 旋转平台---等待信号的锁
        ///// </summary>
        //private static readonly AsyncLock _lockWaitSignal_Rotater = new AsyncLock();
        //private static readonly AsyncLock _lockWaitSignal_SixAxis = new AsyncLock();
        //private static readonly AsyncLock _lockWaitSignal_XYZ = new AsyncLock();
        //private static readonly AsyncLock _lockWaitSignal_XZ = new AsyncLock();
        //private static readonly AsyncLock _lockWaitSignal_Upload = new AsyncLock();
        //private static readonly AsyncLock _lockWaitSignal_Dnload = new AsyncLock();
        //private static readonly AsyncLock _lockDetect_Electricty = new AsyncLock();
        //private static readonly AsyncLock _lockDetect_Acid = new AsyncLock();
        //private static readonly AsyncLock _lockDetect_Moisture = new AsyncLock();
        //private static readonly AsyncLock _lockSixAxisDoAction = new AsyncLock();

        //public async Task<ushort> ReadScannedValueAsync_Upload(ushort address)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        return this.ModbusClient.Command.ReadValue<ushort>(address);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站读取PLC信号异常",
        //            Content = $"ReadUpload读取 {address} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"ReadScannedValueAsync_Upload读取 {address} 时发生错误: {ex.Message}");
        //    }
        //    return 0;
        //}

        //public async Task<ushort> ReadScannedValueAsync_Dnload(ushort address)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        return this.ModbusClient.Command.ReadValue<ushort>(address);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站读取PLC信号异常",
        //            Content = $"ReadDnload读取 {address} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"ReadScannedValueAsync_Dnload读取 {address} 时发生错误: {ex.Message}");
        //    }
        //    return 0;
        //}

        //public async Task<ushort> ReadScannedValueAsync_SixAxis(ushort address)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        return this.ModbusClient.Command.ReadValue<ushort>(address);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站读取PLC信号异常",
        //            Content = $"ReadSixAxis读取 {address} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"ReadScannedValueAsync_SixAxis读取 {address} 时发生错误: {ex.Message}");
        //    }
        //    return 0;
        //}

        //public async Task<ushort> ReadScannedValueAsync_XYZ(ushort address)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        return this.ModbusClient.Command.ReadValue<ushort>(address);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站读取PLC信号异常",
        //            Content = $"ReadXYZ读取 {address} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"ReadScannedValueAsync_XYZ读取 {address} 时发生错误: {ex.Message}");
        //    }
        //    return 0;
        //}

        //public async Task<ushort> ReadScannedValueAsync_XZ(ushort address)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        return this.ModbusClient.Command.ReadValue<ushort>(address);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站读取PLC信号异常",
        //            Content = $"ReadXZ读取 {address} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"ReadScannedValueAsync_XZ读取 {address} 时发生错误: {ex.Message}");
        //    }
        //    return 0;
        //}

        //public async Task WriteCommandAsync_Upload(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //        while (await ReadScannedValueAsync_Upload(address) != value)
        //        {
        //            this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //            await Task.Delay(30);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteUpload写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_Upload写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WriteCommandAsync_Dnload(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //        while (await ReadScannedValueAsync_Dnload(address) != value)
        //        {
        //            this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //            await Task.Delay(30);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteDnload写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_Dnload写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WriteCommandAsync_Six(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteSix写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_Six写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WriteCommandAsync_SixAxis(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //        while (await ReadScannedValueAsync_SixAxis(address) != value)
        //        {
        //            this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //            await Task.Delay(30);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteSixAxis写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_SixAxis写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WriteCommandAsync_XYZ(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //        while (await ReadScannedValueAsync_XYZ(address) != value)
        //        {
        //            this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //            await Task.Delay(30);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteXYZ写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_XYZ写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WriteCommandAsync_XZ(ushort address, ushort value)
        //{
        //    appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //    try
        //    {
        //        this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //        //await Task.Delay(30);
        //        while (await ReadScannedValueAsync_XZ(address) != value)
        //        {
        //            this.ModbusClient.Command.WriteValue<ushort>(address, value);
        //            await Task.Delay(30);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //        {
        //            Header = $"检测站写入PLC信号异常",
        //            Content = $"WriteXZ写入 {address}值{value} 时发生错误: {ex.Message}",
        //            OkButtonContent = "继续",
        //            CancelButtonContent = "取消",
        //        });
        //        this.Logger.LogError($"WriteCommandAsync_XZ写入 {address}值{value} 时发生错误: {ex.Message}");
        //        return;
        //    }
        //}

        //public async Task WaitForActionFinishAsync_Upload(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockWaitSignal_Upload.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForUpload等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_Upload等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_DnLoad(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockWaitSignal_Dnload.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForDnLoad等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_DnLoad等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_SixAxis(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockWaitSignal_SixAxis.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForSixAxis等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_SixAxis等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_Electricty(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockDetect_Electricty.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForElectricty等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_Electricty等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_Acid(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockDetect_Acid.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForAcid等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_Acid等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_Moisture(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockDetect_Moisture.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_SixAxis(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForMoisture等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_Moisture等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_XYZ(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockWaitSignal_XYZ.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_XYZ(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForXYZ等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_XYZ等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}

        //public async Task WaitForActionFinishAsync_XZ(ushort point, ushort waitValue, CancellationToken cancellationToken)
        //{
        //    using (await _lockWaitSignal_XZ.LockAsync(cancellationToken))
        //    {
        //        try
        //        {
        //            ushort result = 0;
        //            do
        //            {
        //                appConfigService.StationPropList[1].ManualResetEvent.WaitOne(); //暂停标志
        //                result = await ReadScannedValueAsync_XZ(point);
        //                await Task.Delay(100, cancellationToken);
        //            } while (result != waitValue && !cancellationToken.IsCancellationRequested);
        //        }
        //        catch (Exception ex)
        //        {
        //            WeakReferenceMessenger.Default.Send(new ConfirmMessage()
        //            {
        //                Header = $"检测站等待PLC信号异常",
        //                Content = $"WaitForXZ等待{point}是否是{waitValue} 时发生错误: {ex.Message}",
        //                OkButtonContent = "继续",
        //                CancelButtonContent = "取消",
        //            });
        //            this.Logger.LogError($"WaitForActionFinishAsync_XZ等待{point}是否是{waitValue} 时发生错误: {ex.Message}");
        //            return;
        //        }
        //    }
        //}
        //#endregion

        private async Task RefreshReactBottleState(int boxId, int posId, SampleBottleStateEnum state)
        {
            //if (workService.ProjectPro.ReactBottleBoxList.FirstOrDefault(f => f.BoxId == boxId) != null)
            //{
            //    SampleBottleBoxModel reactBottleBoxModel = workService.ProjectPro.ReactBottleBoxList.FirstOrDefault(f => f.BoxId == boxId);
            //    if (reactBottleBoxModel.ReactBottleList.FirstOrDefault(f => f.PosId_InBox - 1 == posId) != null)
            //    {
            //        reactBottleBoxModel.ReactBottleList.FirstOrDefault(f => f.PosId_InBox - 1 == posId).ReactBoxState = state;
            //    }
            //}

            ////更新界面显示结果
            //SampleBottleModel bottleModel = null;
            //bottleModel = workService.ProjectPro.ReactBottleBoxListByOrder[boxId - 1].ReactBottleList.FirstOrDefault(f => f.PosId_InBox - 1 == posId);
            //if (state == ReactBottleStateEnum.Detecting)
            //{
            //    if (!OngoingDetectResultList.Any(f => f.BoxId == bottleModel.BoxId && f.BottleId == bottleModel.PosId_InBox))
            //    {
            //        ReactBottleResult_Show result = new ReactBottleResult_Show
            //        {
            //            Guid = bottleModel.reactBottleResult.Guid,
            //            BoxId = bottleModel.reactBottleResult.BoxId,
            //            BottleId = bottleModel.reactBottleResult.BottleId,
            //            SampleName = bottleModel.reactBottleResult.SampleName,
            //            bDetectFinish = false
            //        };
            //        OngoingDetectResultList.Add(result);
            //        UpdateResultEvent?.Invoke(this, OngoingDetectResultList);
            //    }
            //}
            //else if (state == ReactBottleStateEnum.FinishDetect)
            //{
            //    if (OngoingDetectResultList.Any(f => f.BoxId == bottleModel.BoxId && f.BottleId == bottleModel.PosId_InBox))
            //    {
            //        ReactBottleResult_Show result = OngoingDetectResultList.FirstOrDefault(f => f.BoxId == bottleModel.BoxId && f.BottleId == bottleModel.PosId_InBox && f.Guid == bottleModel.reactBottleResult.Guid);
            //        if (result != null)
            //        {
            //            result.bDetectFinish = true;
            //            //OngoingDetectResultList.Add(result);
            //            UpdateResultEvent?.Invoke(this, OngoingDetectResultList);
            //        }
            //    }
            //}
            await Task.Delay(1);
        }

    }
}
