using Common.DevicesModels;
using Common.Models;
using CommunityToolkit.Mvvm.Input;
using MegaRobo.C00225155.DataAccess;
using MegaRobo.C00225155.Entities.Entity_DB;
using MegaRobo.C00225155App.MenuViews;
using MegaRobo.Contract;
using MegaRobo.WpfInfrastructure.Abstractions;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Xceed.Wpf.Toolkit.Core;

namespace MegaRobo.C00225155App.MenuViewModels
{
    public class AdditivePipetteConfigViewModel : ViewModelBaseEx
    {
        protected IDataAccessService dataAccessService;

        private ObservableCollection<Liquid_lml_Dose_Show> _proudcts_1ml = new ObservableCollection<Liquid_lml_Dose_Show>();
        public ObservableCollection<Liquid_lml_Dose_Show> Products_1ml_Dose
        {
            get => _proudcts_1ml;
            set => SetProperty(ref _proudcts_1ml, value);
        }

        private ObservableCollection<Liquid_lml_React_Show> _proudcts = new ObservableCollection<Liquid_lml_React_Show>();
        public ObservableCollection<Liquid_lml_React_Show> Products_1ml_React
        {
            get => _proudcts;
            set => SetProperty(ref _proudcts, value);
        }

        private Liquid_lml_Dose_Show _selectedProduct_1ml;
        /// <summary>
        /// 选中的投料站1ml的移液枪液体
        /// </summary>
        public Liquid_lml_Dose_Show SelectedProduct_1ml_Dose
        {
            get => _selectedProduct_1ml;
            set => SetProperty(ref _selectedProduct_1ml, value);
        }

        private Liquid_lml_React_Show _selectedProduct;
        /// <summary>
        /// 选中的反应站1ml的移液枪液体
        /// </summary>
        public Liquid_lml_React_Show SelectedProduct_1ml_React
        {
            get => _selectedProduct;
            set => SetProperty(ref _selectedProduct, value);
        }

        // 投料站1ml移液枪液体命令
        public ICommand LoadDataCommand_1ml { get; set; }
        public ICommand AddEntityCommand_1ml { get; set; }
        public ICommand DeleteEntityCommand_1ml { get; set; }

        // 反应站1ml移液枪液体命令
        public ICommand LoadDataCommand_1ml_React { get; set; }
        public ICommand AddEntityCommand_1ml_React { get; set; }
        public ICommand DeleteEntityCommand_1ml_React { get; set; }

       
        public override void Initialize(ICoreService coreService, string title, params object[] args)
        {
            base.Initialize(coreService, title, args);
        }

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

        protected override void LoadDatas()
        {
            base.LoadDatas();
            LoadDataFromDb_1ml();
            LoadDataFromDb_1ml_React();
        }

        protected override void Register()
        {
            base.Register();

            //投料站1ml
            LoadDataCommand_1ml = new RelayCommand(LoadDataFromDb_1ml);
            AddEntityCommand_1ml = new RelayCommand(AddData_1ml);
            DeleteEntityCommand_1ml = new RelayCommand(DeleteData_1ml);

            //反应站1ml
            LoadDataCommand_1ml_React = new RelayCommand(LoadDataFromDb_1ml_React);
            AddEntityCommand_1ml_React = new RelayCommand(AddData_1ml_React);
            DeleteEntityCommand_1ml_React = new RelayCommand(DeleteData_1ml_React);
        }

        #region 投料站1ml移液枪液体方法
        private async void LoadDataFromDb_1ml()
        {
            // 先取消原有集合的事件订阅（避免内存泄漏）
            if (Products_1ml_Dose != null)
            {
                foreach (var item in Products_1ml_Dose)
                {
                    item.PropertyChanged -= Liquid1mlProduct_Show_PropertyChanged;
                }
                Products_1ml_Dose.CollectionChanged -= Products_1ml_CollectionChanged;
            }

            var liquid1mlProductList = await this.dataAccessService.LoadEntitiesAsync<Liquid_lml_Dose>();
            if (liquid1mlProductList.Count == 0) return;
            List<Liquid_lml_Dose_Show> liquid1MlProduct_Shows = new List<Liquid_lml_Dose_Show>();
            for (int i = 0; i < liquid1mlProductList.Count; i++)
            {
                var showItem = new Liquid_lml_Dose_Show()
                {
                    Id = liquid1mlProductList[i].Id,
                    TipType = liquid1mlProductList[i].TipType,
                    LiquidName = liquid1mlProductList[i].LiquidName,
                    Ratio = liquid1mlProductList[i].Ratio,
                    LiquidParamId = liquid1mlProductList[i].LiquidParamId,
                    ContainerPlateIndex = liquid1mlProductList[i].ContainerPlateIndex,
                    PlatformCode = liquid1mlProductList[i].PlatformCode,
                    AspireHeight = liquid1mlProductList[i].AspireHeight,
                    DispenHeight = liquid1mlProductList[i].DispenHeight,
                    LiqLedetec = liquid1mlProductList[i].LiqLedetec,
                };
                showItem.PropertyChanged += Liquid1mlProduct_Show_PropertyChanged;
                liquid1MlProduct_Shows.Add(showItem);
            }
            Products_1ml_Dose = new ObservableCollection<Liquid_lml_Dose_Show>(liquid1MlProduct_Shows);
            Products_1ml_Dose.CollectionChanged += Products_1ml_CollectionChanged;
        }
 
        private void Products_1ml_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // 新元素添加时，订阅其PropertyChanged事件
            if (e.NewItems != null)
            {
                foreach (Liquid_lml_Dose_Show item in e.NewItems)
                {
                    item.PropertyChanged += Liquid1mlProduct_Show_PropertyChanged;
                }
            }

            // 元素移除时，取消订阅（避免内存泄漏）
            if (e.OldItems != null)
            {
                foreach (Liquid_lml_Dose_Show item in e.OldItems)
                {
                    item.PropertyChanged -= Liquid1mlProduct_Show_PropertyChanged;

                }
            }
        }

        // 模型属性变化时触发的处理方法（核心逻辑）
        private async void Liquid1mlProduct_Show_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender is not Liquid_lml_Dose_Show changedItem) return;

            // 仅处理Ratio属性的变化
            if (e.PropertyName == nameof(Liquid_lml_Dose_Show.Ratio))
            {
                if (changedItem.Ratio <= 0)
                {
                    changedItem.Ratio = 1.0000; // 自动修正为0
                }
                // 强制保留4位小数（与XAML的StringFormat=F4保持一致）
                //changedItem.Ratio = Math.Round(changedItem.Ratio, 4);

                var resu = await dataAccessService.LoadEntityAsync<Liquid_lml_Dose>(f => f.Id == changedItem.Id);
                if (resu != null)
                {
                    resu.Id = SelectedProduct_1ml_Dose.Id;
                    resu.TipType = SelectedProduct_1ml_Dose.TipType;
                    resu.LiquidName = SelectedProduct_1ml_Dose.LiquidName;
                    resu.Ratio = SelectedProduct_1ml_Dose.Ratio;
                    resu.LiquidParamId = SelectedProduct_1ml_Dose.LiquidParamId;
                    resu.ContainerPlateIndex = SelectedProduct_1ml_Dose.ContainerPlateIndex;
                    resu.PlatformCode = SelectedProduct_1ml_Dose.PlatformCode;
                    resu.AspireHeight = SelectedProduct_1ml_Dose.AspireHeight;
                    resu.DispenHeight = SelectedProduct_1ml_Dose.DispenHeight;
                    resu.LiqLedetec = SelectedProduct_1ml_Dose.LiqLedetec;
                    await dataAccessService.UpdateEntityAsync<Liquid_lml_Dose>(resu);
                }
            }
        }

        private async void AddData_1ml()
        {
            var liquid1mlProductList = await this.dataAccessService.LoadEntitiesAsync<Liquid_lml_Dose>();
            if (liquid1mlProductList.Count == 0) return;
            int id = liquid1mlProductList.OrderBy(x => x.Id).ToList().LastOrDefault().Id;
            Liquid_lml_Dose_Show liquid = new Liquid_lml_Dose_Show() { Id = id + 1, TipType =3,  LiquidName = "water", Ratio = 1.0000, LiquidParamId = 0, ContainerPlateIndex = 0, PlatformCode = 0, AspireHeight = 1600, DispenHeight = 1600, LiqLedetec = 0, };
            Liquid_lml_Dose liquid1Ml = new Liquid_lml_Dose() { Id = id + 1, TipType = 3, LiquidName = "water", Ratio = 1.0000, LiquidParamId = 0, ContainerPlateIndex = 0, PlatformCode = 0, AspireHeight = 1600, DispenHeight = 1600, LiqLedetec = 0, };
            await dataAccessService.CreateLiquid1mlPipetteProductModel(liquid1Ml);
            Products_1ml_Dose.Add(liquid);
        }

        private async void DeleteData_1ml()
        {
            if (SelectedProduct_1ml_Dose == null) return;
            var resu = await dataAccessService.LoadEntityAsync<Liquid_lml_Dose>(f => f.Id == SelectedProduct_1ml_Dose.Id);
            await dataAccessService.DeleteEntityAsync<Liquid_lml_Dose>(resu);
            Products_1ml_Dose.Remove(SelectedProduct_1ml_Dose);
        }

        #endregion

        #region 反应站1ml移液枪液体方法
        private async void LoadDataFromDb_1ml_React()
        {
            // 先取消原有集合的事件订阅（避免内存泄漏）
            if (Products_1ml_React != null)
            {
                foreach (var item in Products_1ml_React)
                {
                    item.PropertyChanged -= Liquid1mlProduct_Show_PropertyChanged_React;
                }
                Products_1ml_React.CollectionChanged -= Products_1ml_CollectionChanged_React;
            }

            var liquid1mlProductList_React = await this.dataAccessService.LoadEntitiesAsync<Liquid_lml_React>();
            if (liquid1mlProductList_React.Count == 0) return;
            List<Liquid_lml_React_Show> liquid1MlProduct_Shows_React = new List<Liquid_lml_React_Show>();
            for (int i = 0; i < liquid1mlProductList_React.Count; i++)
            {
                var showItem = new Liquid_lml_React_Show()
                {
                    Id = liquid1mlProductList_React[i].Id,
                    TipType = liquid1mlProductList_React[i].TipType,
                    LiquidName = liquid1mlProductList_React[i].LiquidName,
                    FuncType= liquid1mlProductList_React[i].FuncType,
                    Ratio = liquid1mlProductList_React[i].Ratio,
                    LiquidParamId = liquid1mlProductList_React[i].LiquidParamId,
                    ContainerPlateIndex = liquid1mlProductList_React[i].ContainerPlateIndex,
                    PlatformCode = liquid1mlProductList_React[i].PlatformCode,
                    AspireHeight = liquid1mlProductList_React[i].AspireHeight,
                    DispenHeight = liquid1mlProductList_React[i].DispenHeight,
                    LiqLedetec = liquid1mlProductList_React[i].LiqLedetec,
                };
                showItem.PropertyChanged += Liquid1mlProduct_Show_PropertyChanged_React;
                liquid1MlProduct_Shows_React.Add(showItem);
            }
            Products_1ml_React = new ObservableCollection<Liquid_lml_React_Show>(liquid1MlProduct_Shows_React);
            Products_1ml_React.CollectionChanged += Products_1ml_CollectionChanged_React;
        }

        private void Products_1ml_CollectionChanged_React(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // 新元素添加时，订阅其PropertyChanged事件
            if (e.NewItems != null)
            {
                foreach (Liquid_lml_React_Show item in e.NewItems)
                {
                    item.PropertyChanged += Liquid1mlProduct_Show_PropertyChanged_React;
                }
            }

            // 元素移除时，取消订阅（避免内存泄漏）
            if (e.OldItems != null)
            {
                foreach (Liquid_lml_React_Show item in e.OldItems)
                {
                    item.PropertyChanged -= Liquid1mlProduct_Show_PropertyChanged_React;

                }
            }
        }

        // 模型属性变化时触发的处理方法（核心逻辑）
        private async void Liquid1mlProduct_Show_PropertyChanged_React(object sender, PropertyChangedEventArgs e)
        {
            if (sender is not Liquid_lml_React_Show changedItem) return;

            // 仅处理Ratio属性的变化
            if (e.PropertyName == nameof(Liquid_lml_React_Show.Ratio))
            {
                if (changedItem.Ratio <= 0)
                {
                    changedItem.Ratio = 1.0000; // 自动修正为0
                }
                // 强制保留4位小数（与XAML的StringFormat=F4保持一致）
                //changedItem.Ratio = Math.Round(changedItem.Ratio, 4);

                var resu = await dataAccessService.LoadEntityAsync<Liquid_lml_React>(f => f.Id == changedItem.Id);
                if (resu != null)
                {
                    resu.Id = SelectedProduct_1ml_React.Id;
                    resu.TipType = SelectedProduct_1ml_React.TipType;
                    resu.LiquidName = SelectedProduct_1ml_React.LiquidName;
                    resu.FuncType = SelectedProduct_1ml_React.FuncType;
                    resu.Ratio = SelectedProduct_1ml_React.Ratio;
                    resu.LiquidParamId = SelectedProduct_1ml_React.LiquidParamId;
                    resu.ContainerPlateIndex = SelectedProduct_1ml_React.ContainerPlateIndex;
                    resu.PlatformCode = SelectedProduct_1ml_React.PlatformCode;
                    resu.AspireHeight = SelectedProduct_1ml_React.AspireHeight;
                    resu.DispenHeight = SelectedProduct_1ml_React.DispenHeight;
                    resu.LiqLedetec = SelectedProduct_1ml_React.LiqLedetec;
                    await dataAccessService.UpdateEntityAsync<Liquid_lml_React>(resu);
                }
            }
        }

        private async void AddData_1ml_React()
        {
            var liquid1mlProductList = await this.dataAccessService.LoadEntitiesAsync<Liquid_lml_React>();
            if (liquid1mlProductList.Count == 0) return;
            int id = liquid1mlProductList.OrderBy(x => x.Id).ToList().LastOrDefault().Id;
            Liquid_lml_React_Show liquid = new Liquid_lml_React_Show() { Id = id + 1, TipType =2, LiquidName = "water", FuncType="开盖取样",Ratio = 1.0000, LiquidParamId = 0, ContainerPlateIndex = 0, PlatformCode = 0, AspireHeight = 1600, DispenHeight = 1600, LiqLedetec = 0, };
            Liquid_lml_React liquid1Ml = new Liquid_lml_React() { Id = id + 1, TipType = 2, LiquidName = "water", FuncType = "开盖取样", Ratio = 1.0000, LiquidParamId = 0, ContainerPlateIndex = 0, PlatformCode = 0, AspireHeight = 1600, DispenHeight = 1600, LiqLedetec = 0, };
            await dataAccessService.CreateLiquid1mlPipetteProductModel_React(liquid1Ml);
            Products_1ml_React.Add(liquid);
        }

        private async void DeleteData_1ml_React()
        {
            if (SelectedProduct_1ml_React == null) return;
            var resu = await dataAccessService.LoadEntityAsync<Liquid_lml_React>(f => f.Id == SelectedProduct_1ml_React.Id);
            await dataAccessService.DeleteEntityAsync<Liquid_lml_React>(resu);
            Products_1ml_React.Remove(SelectedProduct_1ml_React);
        }

        #endregion
    }
}
