using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace StandardScene.Charge
{
    /// <summary>
    /// 报警配置数据服务（单例模式）
    /// </summary>
    public class AlarmConfigDataService
    {
        private static AlarmConfigDataService _instance;
        private static readonly object _lock = new object();
        private List<AlarmConfig> _alarmConfigs;
        private readonly string _dataFilePath;

        private AlarmConfigDataService()
        {
            _dataFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "AlarmConfigs.json");
            LoadData();
        }

        /// <summary>
        /// 获取单例实例
        /// </summary>
        public static AlarmConfigDataService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new AlarmConfigDataService();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 从文件加载数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                // 确保数据目录存在
                var directory = Path.GetDirectoryName(_dataFilePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                if (File.Exists(_dataFilePath))
                {
                    var json = File.ReadAllText(_dataFilePath);
                    if (!string.IsNullOrWhiteSpace(json))
                    {
                        _alarmConfigs = JsonConvert.DeserializeObject<List<AlarmConfig>>(json);
                    }
                    
                    // 如果反序列化失败或为null，创建新列表
                    if (_alarmConfigs == null)
                    {
                        _alarmConfigs = new List<AlarmConfig>();
                    }
                }
                else
                {
                    _alarmConfigs = new List<AlarmConfig>();
                    InitializeDefaultAlarms();
                    SaveData();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载报警配置数据失败: {ex.Message}");
                _alarmConfigs = new List<AlarmConfig>();
                InitializeDefaultAlarms();
            }
        }

        /// <summary>
        /// 初始化默认报警配置
        /// </summary>
        private void InitializeDefaultAlarms()
        {
            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 1001,
            //    AlarmContent = "电压过高",
            //    Level = AlarmLevel.High,
            //    Enabled = true,
            //    Remarks = "电压超过额定值10%"
            //});

            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 1002,
            //    AlarmContent = "电压过低",
            //    Level = AlarmLevel.High,
            //    Enabled = true,
            //    Remarks = "电压低于额定值10%"
            //});

            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 1003,
            //    AlarmContent = "电流过大",
            //    Level = AlarmLevel.Critical,
            //    Enabled = true,
            //    Remarks = "电流超过额定值"
            //});

            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 2001,
            //    AlarmContent = "温度异常",
            //    Level = AlarmLevel.High,
            //    Enabled = true,
            //    Remarks = "温度超过安全范围"
            //});

            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 3001,
            //    AlarmContent = "通讯超时",
            //    Level = AlarmLevel.Medium,
            //    Enabled = true,
            //    Remarks = "通讯响应时间超过阈值"
            //});

            //_alarmConfigs.Add(new AlarmConfig
            //{
            //    AlarmCode = 3002,
            //    AlarmContent = "连接断开",
            //    Level = AlarmLevel.Critical,
            //    Enabled = true,
            //    Remarks = "网络连接中断"
            //});
        }

        /// <summary>
        /// 保存数据到文件
        /// </summary>
        private void SaveData()
        {
            try
            {
                var directory = Path.GetDirectoryName(_dataFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_alarmConfigs, Formatting.Indented);
                File.WriteAllText(_dataFilePath, json);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有报警配置
        /// </summary>
        public List<AlarmConfig> GetAllAlarmConfigs()
        {
            lock (_lock)
            {
                if (_alarmConfigs == null)
                {
                    _alarmConfigs = new List<AlarmConfig>();
                }
                return new List<AlarmConfig>(_alarmConfigs);
            }
        }

        /// <summary>
        /// 根据编号获取报警配置
        /// </summary>
        public AlarmConfig GetAlarmConfig(string alarmId)
        {
            lock (_lock)
            {
                return _alarmConfigs.FirstOrDefault(a => a.AlarmId == alarmId);
            }
        }
        /// <summary>
        /// 根据编号获取报警配置
        /// </summary>
        public AlarmConfig GetAlarmConfigAlarmCode(int alarmCode)
        {
            lock (_lock)
            {
                return _alarmConfigs.FirstOrDefault(a => a.AlarmCode == alarmCode);
            }
        }
        /// <summary>
        /// 根据报警编码获取报警配置
        /// </summary>
        public AlarmConfig GetAlarmConfigByCode(int alarmCode)
        {
            lock (_lock)
            {
                return _alarmConfigs.FirstOrDefault(a => a.AlarmCode == alarmCode);
            }
        }

        /// <summary>
        /// 添加报警配置
        /// </summary>
        public bool AddAlarmConfig(AlarmConfig alarmConfig, out string errorMessage)
        {
            lock (_lock)
            {
                if (!alarmConfig.IsValid(out errorMessage))
                {
                    return false;
                }

                // 检查编码是否已存在
                if (_alarmConfigs.Any(a => a.AlarmCode == alarmConfig.AlarmCode))
                {
                    errorMessage = $"报警编码 {alarmConfig.AlarmCode} 已存在";
                    return false;
                }

                _alarmConfigs.Add(alarmConfig);
                SaveData();
                errorMessage = string.Empty;
                return true;
            }
        }

        /// <summary>
        /// 更新报警配置
        /// </summary>
        public bool UpdateAlarmConfig(AlarmConfig alarmConfig, out string errorMessage)
        {
            lock (_lock)
            {
                if (!alarmConfig.IsValid(out errorMessage))
                {
                    return false;
                }

                var index = _alarmConfigs.FindIndex(a => a.AlarmId == alarmConfig.AlarmId);
                if (index == -1)
                {
                    errorMessage = "报警配置不存在";
                    return false;
                }

                // 检查编码是否与其他配置冲突
                if (_alarmConfigs.Any(a => a.AlarmId != alarmConfig.AlarmId && a.AlarmCode == alarmConfig.AlarmCode))
                {
                    errorMessage = $"报警编码 {alarmConfig.AlarmCode} 已被其他配置使用";
                    return false;
                }

                alarmConfig.ModifiedTime = DateTime.Now;
                _alarmConfigs[index] = alarmConfig;
                SaveData();
                errorMessage = string.Empty;
                return true;
            }
        }

        /// <summary>
        /// 删除报警配置
        /// </summary>
        public bool DeleteAlarmConfig(string alarmId, out string errorMessage)
        {
            lock (_lock)
            {
                var alarmConfig = _alarmConfigs.FirstOrDefault(a => a.AlarmId == alarmId);
                if (alarmConfig == null)
                {
                    errorMessage = "报警配置不存在";
                    return false;
                }

                _alarmConfigs.Remove(alarmConfig);
                SaveData();
                errorMessage = string.Empty;
                return true;
            }
        }

        /// <summary>
        /// 重新加载数据
        /// </summary>
        public void Reload()
        {
            lock (_lock)
            {
                LoadData();
            }
        }
    }
}

