using Common;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Dm.filter.log;
using MegaRobo.C00225155.ControlDevices;
using MegaRobo.C00225155.DataAccess;
using MegaRobo.C00225155.Entities.Entity_DB;
using MegaRobo.Contract;
using MegaRobo.Entities;
using MegaRobo.Logger;
using MegaRobo.WpfInfrastructure.Abstractions;
using ServiceReference1;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MegaRobo.C00225155App.DevicesViewModels
{
    public class LabXToolViewModel : ViewModelBaseEx
    {
        private bool stop = false;
        private IDataAccessService _dataAccessService;
        private System.Timers.Timer statemoisturetimer;
        private string DeviceName = "Labx";

        private LabxService _labxService;

        //private List<Instrument> instrumentlist;
        //public List<Instrument> InstrumentList
        //{
        //    get { return instrumentlist; }
        //    set { SetProperty(ref instrumentlist, value); }
        //}


        //private Instrument selectedInstrument;
        ///// <summary>
        ///// 选中的设备
        ///// </summary>
        //public Instrument SelectedInstrument
        //{
        //    get { return selectedInstrument; }
        //    set { SetProperty(ref selectedInstrument, value); }
        //}

        //private List<string> methodlist;
        //public List<string> MethodList
        //{
        //    get { return methodlist; }
        //    set { SetProperty(ref methodlist, value); }
        //}

        //private string selectedmethod;
        //public string SelectedMethod
        //{
        //    get { return selectedmethod; }
        //    set { SetProperty(ref selectedmethod, value); }
        //}

        //private int instrumentnum;
        //public int InstrumentNum
        //{
        //    get => instrumentnum;
        //    set => SetProperty(ref instrumentnum, value);
        //}

        private double targetweight = 0;
        public double TargetWeight
        {
            get { return targetweight; }
            set { SetProperty(ref targetweight, value); }
        }

        private double uptolerance = 0;
        public double UpTolerance
        {
            get => uptolerance;
            set => SetProperty(ref uptolerance, value);
        }

        private double dntolerance = 0;
        public double DnTolerance
        {
            get => dntolerance;
            set => SetProperty(ref dntolerance, value);
        }

        private double powderweight = 0;
        public double PowderWeight
        {
            get => powderweight;
            set => SetProperty(ref powderweight, value);
        }

        private double powderct = 0;
        public double PowderCT
        {
            get => powderct;
            set => SetProperty(ref powderct, value);
        }

        private ObservableCollection<string> loginfo = new ObservableCollection<string>();
        public ObservableCollection<string> LogInfos
        {
            get => loginfo;
            set => SetProperty(ref loginfo, value);
        }


        public RelayCommand<string> ActionCommand { get; set; }
        public RelayCommand<object> SwitchInstrumentCommand { get; set; }

        private string state;

        public string DeviceState
        {
            get { return state; }
            set
            {
                SetProperty(ref state, value);
            }
        }

        protected override void LoadServices()
        {
            base.LoadServices();
            _labxService = this.CoreService.GetServiceInstance<LabxService>();
            _dataAccessService = this.CoreService.GetServiceInstance<IDataAccessService>();
        }

        protected override async void LoadDatas()
        {
            base.LoadDatas();
            //var list1 = await _dataAccessService.LoadTitrInstrument("C20S");
            //var list2 = await _dataAccessService.LoadTitrInstrument("T5");
            //var list3 = await _dataAccessService.LoadTitrInstrument("SevenExcellence");
        }

        protected override void Register()
        {
            base.Register();
            ActionCommand = new RelayCommand<string>(OnActioncommand);
            SwitchInstrumentCommand = new RelayCommand<object>(OnSwitchInstrument);
        }

        private async void OnSwitchInstrument(object arg)
        {
            //if (this.SelectedInstrument == null)
            //{
            //    WeakReferenceMessenger.Default.Send(new DesktopAlertMessage { Content = "请选择工作区域", Level = AlertMessageLevel.Warning });
            //    return;
            //}
            ////_titratorService = this.CoreService.GetServiceInstance<TitaratorService>(SelectedInstrument.Name + "_" + SelectedInstrument.Num);
            //TitrMethodList = await _dataAccessService.LoadTitrMethodName(SelectedInstrument.Code);
            //this.OnPropertyChanged(nameof(TitrMethodList));
        }

        private async void OnActioncommand(string? obj)
        {
            var Instrument = await _labxService.GetInstruments("自动天平XPR105");

            switch (obj)
            {
                case "0":
                    await _labxService.MTPowderModuleControlStep(Instrument.FirstOrDefault(), "Balance Step", "Balance Step", 0);
                    WriteLog($"关门完成");
                    break;
                case "1":
                    await _labxService.MTPowderModuleControlStep(Instrument.FirstOrDefault(), "Balance Step", "Balance Step", 1);
                    WriteLog($"开门完成");
                    break;
                case "2":
                    await _labxService.MTPowderModuleControlStep(Instrument.FirstOrDefault(), "Balance Step", "Balance Step", 2);
                    WriteLog($"置零完成");
                    break;
                case "3":
                    await _labxService.MTPowderModuleControlStep(Instrument.FirstOrDefault(), "Balance Step", "Balance Step", 3);
                    WriteLog($"去皮完成");
                    break;
                case "4":
                    WriteLog($"开始加样");
                    Stopwatch stopwatch = Stopwatch.StartNew();
                    PowderWeight = await _labxService.MTPowderModuleAddPowder(Instrument.FirstOrDefault(), "Dosing2", "Dosing2", 4, 140m, (decimal)TargetWeight, (decimal)UpTolerance, (decimal)DnTolerance);
                    stopwatch.Stop();
                    PowderCT = stopwatch.ElapsedMilliseconds;
                    break;
                case "5":
                    await _labxService.MTPowderModuleControlStep(Instrument.FirstOrDefault(), "Balance Step", "Balance Step", 5);
                    WriteLog($"粉末头复位完成");
                    break;
                case "6":
                    await _labxService.StartWaitingForHead(Instrument.FirstOrDefault(), "Dosing Head", "Dosing Head", 5);
                    WriteLog($"正在等待放置粉末加样头");
                    break;
                case "7":
                    await _labxService.AbortWaitingForHead();
                    WriteLog($"粉末加样头放置完成");
                    break;
            }
        }

        private void WriteLog(string info)
        {
            ObservableCollection<string> infoss = File_Operator.DeepCopy(LogInfos);
            if (infoss.Count > 300) infoss.Clear();
            infoss.Insert(0, $"{DateTime.Now}---{info}");
            LogInfos = File_Operator.DeepCopy(infoss);
        }
    }
}
