using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPASmartClient.Helper;
using BPASmartClient.DosingSystem.Model;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;

namespace BPASmartClient.DosingSystem.ViewModel
{
    public class ChangeDeviceNameViewModel : ObservableObject
    {
        public ChangeDeviceNameViewModel()
        {
            ActionManage.GetInstance.Register(new Action<object>((o) =>
            {
                if (o != null && o is string str) IpAddress = str;
            }), "ChangeDeviceNameViewOpen");

            CancleCommand = new RelayCommand(() => { ActionManage.GetInstance.Send("ChangeDeviceNameViewClose"); });
            ConfirmCommand = new RelayCommand(() =>
            {
                if (string.IsNullOrEmpty(DeviceName))
                {
                    ErrorInfo = "设备名称不能为空";
                    return;
                }
                int index = Array.FindIndex(DeviceListViewModel.devices.ToArray(), p => p.IpAddress == IpAddress);
                if (index >= 0 && index < DeviceListViewModel.devices.Count)
                {
                    if (DeviceListViewModel.devices.FirstOrDefault(p => p.DeviceName == DeviceName) != null)
                        ErrorInfo = "设备名称已存在";
                    else
                    {
                        NewRecipeViewModel.RawMaterialNames.Remove(DeviceListViewModel.devices.ElementAt(index).DeviceName);
                        NewRecipeViewModel.RawMaterialNames.Add(DeviceName);
                        DeviceListViewModel.devices.ElementAt(index).DeviceName = DeviceName;

                        DeviceInquire.GetInstance.GetDevice(IpAddress).SetDeviceName(DeviceName);//设置PLC名称
                        for (int i = 0; i < Json<LocaPar>.Data.Recipes.Count; i++)
                        {
                            for (int m = 0; m < Json<LocaPar>.Data.Recipes.ElementAt(i).RawMaterials.Count; m++)
                            {
                                Json<LocaPar>.Data.Recipes.ElementAt(i).RawMaterials.ElementAt(m).RawMaterialName = DeviceName;
                            }
                        }
                        ActionManage.GetInstance.Send("ChangeDeviceNameViewClose");
                    }
                }

            });
        }

        private static string IpAddress = string.Empty;

        public RelayCommand ConfirmCommand { get; set; }

        public RelayCommand CancleCommand { get; set; }


        public string ErrorInfo { get { return _mErrorInfo; } set { _mErrorInfo = value; OnPropertyChanged(); } }
        private string _mErrorInfo;


        public string DeviceName { get { return _mDeviceName; } set { _mDeviceName = value; OnPropertyChanged(); } }
        private string _mDeviceName;

    }
}
