using DocumentFormat.OpenXml.Bibliography;
using Newtonsoft.Json;
using SimpleCore;
using SimpleCore.Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace StandardScene.Charge
{
    /// <summary>
    /// 充电桩数据服务 - 负责数据的持久化和管理
    /// </summary>
    public class ChargeStationDataService
    {
        private static ChargeStationDataService _instance;
        private static readonly object lockObj = new object();

        private List<ChargeStation> chargeStations;
        private readonly string dataFilePath;

        // 单例模式
        public static ChargeStationDataService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new ChargeStationDataService();
                        }
                    }
                }
                return _instance;
            }
        }

        private ChargeStationDataService()
        {
            // 数据文件路径：项目根目录/Config/ChargeStations.json
            var dataDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
            if (!Directory.Exists(dataDir))
            {
                Directory.CreateDirectory(dataDir);
            }

            dataFilePath = Path.Combine(dataDir, "ChargeStations.json");
            chargeStations = new List<ChargeStation>();

            LoadData();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                if (File.Exists(dataFilePath))
                {
                    var json = File.ReadAllText(dataFilePath);
                    chargeStations = JsonConvert.DeserializeObject<List<ChargeStation>>(json)
                                     ?? new List<ChargeStation>();
                    Diagnosis.Log($"加载充电桩数据成功，共 {chargeStations.Count} 条记录", "ChargeStation");
                }
                else
                {
                    chargeStations = new List<ChargeStation>();
                    Diagnosis.Log("充电桩数据文件不存在，已创建新列表", "ChargeStation");
                }
            }
            catch (Exception ex)
            {
                Diagnosis.Log($"加载充电桩数据失败: {ExceptionFormatter.FormatEx(ex)}", "ChargeStation", true);
                chargeStations = new List<ChargeStation>();
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        private bool SaveData()
        {
            try
            {
                lock (lockObj)
                {
                    var json = JsonConvert.SerializeObject(chargeStations, Formatting.Indented);
                    File.WriteAllText(dataFilePath, json);
                    //Diagnosis.Log($"保存充电桩数据成功，共 {chargeStations.Count} 条记录", "ChargeStation");
                    return true;
                }
            }
            catch (Exception ex)
            {
                Diagnosis.Log($"保存充电桩数据失败: {ExceptionFormatter.FormatEx(ex)}", "ChargeStation", true);
                return false;
            }
        }

        /// <summary>
        /// 获取所有充电桩
        /// </summary>
        public List<ChargeStation> GetAllStations()
        {
            lock (lockObj)
            {
                return new List<ChargeStation>(chargeStations);
            }
        }

        /// <summary>
        /// 根据编号获取充电桩
        /// </summary>
        public ChargeStation GetStationById(string stationId)
        {
            lock (lockObj)
            {
                return chargeStations.FirstOrDefault(s => s.StationId == stationId);
            }
        }

        /// <summary>
        /// 根据IP地址获取充电桩
        /// </summary>
        public ChargeStation GetStationByIp(string ipAddress, int port)
        {
            lock (lockObj)
            {
                return chargeStations.FirstOrDefault(s => s.IpAddress == ipAddress && s.Port == port);
            }
        }
        public ChargeStation GetStationByIp(string ipAddress)
        {
            lock (lockObj)
            {
                return chargeStations.FirstOrDefault(s => s.IpAddress == ipAddress);
            }
        }

        /// <summary>
        /// 添加充电桩
        /// </summary>
        public bool AddStation(ChargeStation station, out string errorMessage)
        {
            if (station == null)
            {
                errorMessage = "充电桩数据不能为空";
                return false;
            }

            // 验证数据
            if (!station.IsValid(out errorMessage))
            {
                return false;
            }

            lock (lockObj)
            {
                // 检查编号是否已存在
                if (chargeStations.Any(s => s.StationId == station.StationId))
                {
                    errorMessage = $"充电桩编号 {station.StationId} 已存在";
                    return false;
                }

                // 检查IP和端口是否已被使用
                if (chargeStations.Any(s => s.IpAddress == station.IpAddress && s.Port == station.Port))
                {
                    errorMessage = $"IP地址 {station.IpAddress}:{station.Port} 已被使用";
                    return false;
                }
                if (chargeStations.Any(s => s.SiteId == station.SiteId))
                {
                    errorMessage = $"SiteID {station.SiteId} 已被使用";
                    return false;
                }

                station.CreatedTime = DateTime.Now;
                station.ModifiedTime = DateTime.Now;

                chargeStations.Add(station);

                if (SaveData())
                {
                    Diagnosis.Log($"添加充电桩成功: {station}", "ChargeStation", true);
                    errorMessage = string.Empty;
                    return true;
                }
                else
                {
                    chargeStations.Remove(station);
                    errorMessage = "保存数据失败";
                    return false;
                }
            }
        }

        /// <summary>
        /// 更新充电桩
        /// </summary>
        public bool UpdateStation(ChargeStation station, out string errorMessage, bool isSave = false)
        {
            if (station == null)
            {
                errorMessage = "充电桩数据不能为空";
                return false;
            }

            // 验证数据
            if (!station.IsValid(out errorMessage))
            {
                return false;
            }

            lock (lockObj)
            {
                var existingStation = chargeStations.FirstOrDefault(s => s.StationId == station.StationId);
                if (existingStation == null)
                {
                    errorMessage = $"充电桩编号 {station.StationId} 不存在";
                    return false;
                }

                // 检查IP和端口是否与其他充电桩冲突
                if (chargeStations.Any(s => s.StationId != station.StationId &&
                                           s.IpAddress == station.IpAddress &&
                                           s.Port == station.Port))
                {
                    errorMessage = $"IP地址 {station.IpAddress}:{station.Port} 已被其他充电桩使用";
                    return false;
                }
                if (chargeStations.Any(s => s.StationId != station.StationId && s.SiteId == station.SiteId))
                {
                    errorMessage = $"SiteID {station.SiteId} 已被使用";
                    return false;
                }

                // 保留创建时间
                station.CreatedTime = existingStation.CreatedTime;
                station.ModifiedTime = DateTime.Now;

                var index = chargeStations.IndexOf(existingStation);

                //进行赋值
                if (isSave)
                {

                    existingStation.StationId = station.StationId;
                    existingStation.Name = station.Name;
                    existingStation.Type = station.Type;
                    existingStation.ChargeMethod = station.ChargeMethod;
                    existingStation.IpAddress = station.IpAddress;
                    existingStation.Port = station.Port;
                    existingStation.SetVoltage = station.SetVoltage;
                    existingStation.SetElectricCurrent = station.SetElectricCurrent;
                    existingStation.Enabled = station.Enabled;
                    existingStation.ShieldSiteMechanismStatus = station.ShieldSiteMechanismStatus;
                    existingStation.GroupCarType = station.GroupCarType;
                    existingStation.SiteId = station.SiteId;
                    existingStation.Remarks = station.Remarks;
                    station = existingStation;
                    station.ModifiedTime = DateTime.Now;



                }



                chargeStations[index] = station;

                if (SaveData())
                {
                    //Diagnosis.Log($"更新充电桩成功: {station}", "ChargeStation", true);
                    errorMessage = string.Empty;
                    return true;
                }
                else
                {
                    chargeStations[index] = existingStation;
                    errorMessage = "保存数据失败";
                    return false;
                }
            }
        }

        /// <summary>
        /// 删除充电桩
        /// </summary>
        public bool DeleteStation(string stationId, out string errorMessage)
        {
            lock (lockObj)
            {
                var station = chargeStations.FirstOrDefault(s => s.StationId == stationId);
                if (station == null)
                {
                    errorMessage = $"充电桩编号 {stationId} 不存在";
                    return false;
                }

                // 检查是否正在充电
                //if (station.Status == ChargeStationStatus.Charging)
                //{
                //    errorMessage = $"充电桩 {station.Name} 正在充电中，无法删除";
                //    return false;
                //}

                chargeStations.Remove(station);

                if (SaveData())
                {
                    Diagnosis.Log($"删除充电桩成功: {station}", "ChargeStation", true);
                    errorMessage = string.Empty;
                    return true;
                }
                else
                {
                    chargeStations.Add(station);
                    errorMessage = "保存数据失败";
                    return false;
                }
            }
        }

        /// <summary>
        /// 更新充电桩状态
        /// </summary>
        public bool UpdateStationStatus(string stationId, ChargeStationStatus status)
        {
            lock (lockObj)
            {
                var station = chargeStations.FirstOrDefault(s => s.StationId == stationId);
                if (station == null)
                {
                    return false;
                }

                station.Status = status;
                station.ModifiedTime = DateTime.Now;

                return SaveData();
            }
        }

        /// <summary>
        /// 获取空闲的充电桩
        /// </summary>
        public List<ChargeStation> GetIdleStations()
        {
            lock (lockObj)
            {
                return chargeStations
                    .Where(s => s.Enabled && s.Status == ChargeStationStatus.Idle)
                    .ToList();
            }
        }

        /// <summary>
        /// 获取充电中的充电桩数量
        /// </summary>
        public int GetChargingCount()
        {
            lock (lockObj)
            {
                return chargeStations.Count(s => s.Status == ChargeStationStatus.Charging);
            }
        }

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



