using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPASmartClient.Helper;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.IO.Ports;
using System.IO;
using Newtonsoft.Json;
using BPASmartClient.Model;

namespace BPASmartClient.ViewModel
{
    public class ShopDeviceConfigViewModel : ObservableObject
    {
        private DeviceConfigModelJson configModel = new DeviceConfigModelJson();
        string FileName => deviceConfig.Count > 0 ? deviceConfig[0].ShopName : string.Empty;
        public static List<string> IDevices = new List<string>();
        public static List<string> IPeripherals = new List<string>();
        public ShopDeviceConfigViewModel()
        {
            ActionManage.GetInstance.Register(new Action<object[]>((o) =>
            {
                if (o != null && o is string[] par)
                {
                    if (par.Length == 2)
                    {
                        configModel.ShopName = par[0];
                        configModel.ShopId = par[1];
                        deviceConfig.Clear();
                        deviceConfig.Add(configModel);
                    }
                }
            }), "ShopPar");

            NewDeviceCommand = new RelayCommand<object>(NewDevice);
            RemoveDeviceCommand = new RelayCommand<object>(RemoveDevice);
            NewCommunicationCommand = new RelayCommand<object>(NewCommunication);
            RemoveCommunicationCommand = new RelayCommand<object>(RemoveCommunication);

            DataListInit();

            SaveData = new Action(() =>
            {
                if (deviceConfig.Count > 0)
                {
                    for (int i = 0; i < deviceConfig.ElementAt(0).deviceModels.Count; i++)
                    {
                        string name = deviceConfig.ElementAt(0).deviceModels.ElementAt(i).DeviceModule;
                        deviceConfig.ElementAt(0).deviceModels.ElementAt(i).DeviceNamespace = IDevices.FirstOrDefault(p => p.Contains(name));

                        for (int m = 0; m < deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.Count; m++)
                        {
                            string comName = deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.ElementAt(m).CommunicationModule;
                            deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.ElementAt(m).CommunicationNamespace = IPeripherals.FirstOrDefault(p => p.Contains(comName));
                        }
                    }
                    File.WriteAllText($"{LocaPath.GetInstance().GetDeviceConfigPath}{FileName}.json", JsonConvert.SerializeObject(deviceConfig));
                }
            });
        }

        #region 右键菜单按钮操作
        private void RemoveCommunication(object? obj)
        {
            if (obj != null && obj is CommunicationModel com)
            {
                if (com != null)
                {
                    int index = Array.FindIndex(deviceConfig.ElementAt(0).deviceModels.ToArray(), p => p.Id == com.DeviceModelId);
                    if (index >= 0 && index < deviceConfig.ElementAt(0).deviceModels.Count)
                    {
                        var res = deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.FirstOrDefault(p => p.CommunicationName == com.CommunicationName);
                        if (res != null)
                        {
                            deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.Remove(res);
                        }
                    }
                }
            }
        }

        private void NewCommunication(object? obj)
        {
            if (obj != null && obj is DeviceModel dm)
            {
                if (dm != null)
                {
                    string CommunicationName = string.Empty;
                    int num = 1;
                    while (true)
                    {
                        int index = Array.FindIndex(deviceConfig.ElementAt(0).deviceModels.ToArray(), p => p.DeviceName == dm.DeviceName);
                        if (index >= 0 && index < deviceConfig.ElementAt(0).deviceModels.Count)
                        {
                            var res = deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.FirstOrDefault(p => p.CommunicationName.Contains($"Communication_{num}"));
                            if (res == null)
                            {
                                deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.Add(new CommunicationModel()
                                {
                                    CommunicationName = $"Communication_{num}",
                                    DeviceModelId = deviceConfig.ElementAt(0).deviceModels.FirstOrDefault(p => p.DeviceName == dm.DeviceName)?.Id,
                                    communicationPar = new CommunicationPar() { IsNetworkPort = false }

                                });
                                break;
                            }
                        }
                        else break;
                        num++;
                    }
                }
            }
        }

        private void RemoveDevice(object? obj)
        {
            if (obj != null && deviceConfig.Count == 1)
            {
                string DeviceName = obj?.ToString();
                var res = deviceConfig.ElementAt(0).deviceModels.FirstOrDefault(p => p.DeviceName == DeviceName);
                if (res != null)
                    deviceConfig.ElementAt(0).deviceModels.Remove(res);
            }
        }

        private void NewDevice(object? obj)
        {
            if (obj != null && deviceConfig.Count == 1)
            {
                string DeviceName = string.Empty;
                int num = 1;
                while (true)
                {
                    var res = deviceConfig.ElementAt(0).deviceModels.FirstOrDefault(p => p.DeviceName == $"Device_{num}");
                    if (res == null)
                    {
                        deviceConfig.ElementAt(0).deviceModels.Add(new DeviceModel() { DeviceId = "0", DeviceName = $"Device_{num}", Id = Guid.NewGuid().ToString() });
                        break;
                    }
                    num++;
                }
            }
        }
        #endregion

        #region Command
        /// <summary>
        /// 新建设备
        /// </summary>
        public RelayCommand<object> NewDeviceCommand { get; set; }

        /// <summary>
        /// 删除设备
        /// </summary>
        public RelayCommand<object> RemoveDeviceCommand { get; set; }

        /// <summary>
        /// 新建通讯
        /// </summary>
        public RelayCommand<object> NewCommunicationCommand { get; set; }

        /// <summary>
        /// 删除通讯
        /// </summary>
        public RelayCommand<object> RemoveCommunicationCommand { get; set; }

        public Action SaveData { get; set; }
        #endregion

        #region 列表集合
        /// <summary>
        /// 设备信息列表
        /// </summary>
        public static ObservableCollection<DeviceConfigModelJson> deviceConfig { get; set; } = new ObservableCollection<DeviceConfigModelJson>();

        /// <summary>
        /// 端口号列表
        /// </summary>
        public static ObservableCollection<string> Ports { get; set; } = new ObservableCollection<string>();

        /// <summary>
        /// 波特率列表
        /// </summary>
        public static ObservableCollection<int> BaudRates { get; set; } = new ObservableCollection<int>();

        /// <summary>
        /// 奇偶校验列表
        /// </summary>
        public static ObservableCollection<string> Paritys { get; set; } = new ObservableCollection<string>();

        /// <summary>
        /// 设备模块
        /// </summary>
        public static ObservableCollection<string> DeviceModels { get; set; } = new ObservableCollection<string>();

        /// <summary>
        /// 通讯模块
        /// </summary>
        public static ObservableCollection<string> CommunicationModel { get; set; } = new ObservableCollection<string>();

        /// <summary>
        /// 店铺集合
        /// </summary>
        public static ObservableCollection<string> Shops { get; set; } = new ObservableCollection<string>();

        private void DataListInit()
        {
            Ports.Clear();
            System.IO.Ports.SerialPort.GetPortNames().ToList().ForEach((item) => { Ports.Add(item); });

            BaudRates.Clear();
            int[] rb = new int[] { 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 43000, 57600, 76800, 115200 };
            rb.ToList().ForEach((item) => { BaudRates.Add(item); });

            Paritys.Clear();
            Enum.GetNames(typeof(Parity)).ToList().ForEach((item) => { Paritys.Add(item); });

            DeviceModels.Clear();
            IDevices.ForEach((item) =>
            {
                var strs = item.Split(".");
                if (strs != null && strs.Length == 3)
                {
                    DeviceModels.Add(strs[1]);
                }
            });

            CommunicationModel.Clear();
            IPeripherals.ForEach((item) =>
            {
                var strs = item.Split(".");
                if (strs != null && strs.Length == 3)
                {
                    CommunicationModel.Add(strs[1]);
                }
            });

            Shops.Clear();
            DirectoryInfo directoryInfo = new DirectoryInfo(LocaPath.GetInstance().GetDeviceConfigPath);
            var files = directoryInfo.GetFiles();
            foreach (var item in files)
            {
                var res = Path.GetFileNameWithoutExtension(item.FullName);
                if (res != null && res.Length > 0 && item.FullName.Contains("json")) Shops.Add(res);
            }
        }
        #endregion



    }
}
