using AI.Platform.Core;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Device;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;

namespace AI.Platform.Page.Pages.SiteConfiguration
{
    public partial class Device : ComponentBase
    {
        [Inject] private SqlSugarRepository<DeviceEntity> _DeviceRepository { get; set; }
        #region 模型定义

        public class DeviceDto
        {
            public int Id { get; set; }
            public string DeviceId { get; set; } = "";
            public string SiteBUID { get; set; } = "";
            public string SiteName { get; set; } = "";
            public string OilProductName { get; set; } = "";
            public decimal? TankCapacity { get; set; }
            public decimal? CurrentCapacity { get; set; }
            public DateTime? LastUpdatedTime { get; set; }
            public string Status { get; set; } = "";
            public string Location { get; set; } = "";
            public string Manufacturer { get; set; } = "";
            public string LicencePlate { get; set; } = "";
            public DateTime InstallationDate { get; set; }
            public DateTime CreateTime { get; set; }
            public DateTime UpdateTime { get; set; }
        }

        public class DeviceEditModel
        {
            public int Id { get; set; }
            public string DeviceId { get; set; } = "";
            public string SiteBUID { get; set; } = "";
            public string SiteName { get; set; } = "";
            public string OilProductName { get; set; } = "";
            public decimal? TankCapacity { get; set; }
            public decimal? CurrentCapacity { get; set; }
            public string Status { get; set; } = "正常";
            public string Location { get; set; } = "";
            public string Manufacturer { get; set; } = "";
            public DateTime InstallationDate { get; set; } = DateTime.Today;
            public string LicencePlate { get; set; }
        }

        public class SelectOption
        {
            public string? Value { get; set; }
            public string? Label { get; set; }
            public bool Disabled { get; set; }
        }

        #endregion

        #region 状态变量

        private string License = "";
        private string deviceNo = "";
        private bool _loading = false;
        private List<DeviceDto> _deviceList = new();
        private int _totalCount = 0;
        private int _currentPage = 1;
        private int _pageSize = 20;
        private bool _showNewDeviceDialog = false;
        private DeviceEditModel _deviceModel = new();

        #endregion

        #region 选项数据

        private readonly List<SelectOption> _oilProductOptions = new()
        {
            new SelectOption { Value = "92#汽油", Label = "92#汽油" },
            new SelectOption { Value = "95#汽油", Label = "95#汽油" },
            new SelectOption { Value = "0#柴油", Label = "0#柴油" },
            new SelectOption { Value = "-10#柴油", Label = "-10#柴油" }
        };

        private readonly List<SelectOption> _statusOptions = new()
        {
            new SelectOption { Value = "正常", Label = "正常" },
            new SelectOption { Value = "维护中", Label = "维护中" },
            new SelectOption { Value = "故障", Label = "故障" },
            new SelectOption { Value = "停用", Label = "停用" }
        };

        private readonly List<SelectOption> _manufacturerOptions = new()
        {
            new SelectOption { Value = "中石化设备", Label = "中石化设备" },
            new SelectOption { Value = "中石油设备", Label = "中石油设备" },
            new SelectOption { Value = "壳牌设备", Label = "壳牌设备" },
            new SelectOption { Value = "BP设备", Label = "BP设备" },
            new SelectOption { Value = "其他", Label = "其他" }
        };

        #endregion

        #region 生命周期方法

        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            await OnQuery();
        }

        #endregion

        #region 数据操作方法

        private async Task OnQuery()
        {
            try
            {
                _loading = true;
                StateHasChanged();

                await Task.Delay(300);

                _deviceList = await GenerateMockData();
                _totalCount = _deviceList.Count;

                ApplyFilter();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询失败: {ex.Message}");
            }
            finally
            {
                _loading = false;
                StateHasChanged();
            }
        }

        private async Task<List<DeviceDto>> GenerateMockData()
        {
            var Devices = await _DeviceRepository.AsQueryable()
                .Select(_ => new DeviceDto {
                    DeviceId = _.DeviceId,
                    OilProductName = _.OilProductName,
                    TankCapacity = _.TankCapacity,
                    CurrentCapacity = _.RemainingCapacity,
                    LastUpdatedTime = _.LastUpdatedTime,
                    Status = "正常",
                    LicencePlate = _.LicencePlate
                }).ToListAsync();
            return Devices;
        }

        private void ApplyFilter()
        {
            var query = _deviceList.AsQueryable();

            if (!string.IsNullOrEmpty(License))
            {
                query = query.Where(x => x.LicencePlate.Contains(License, StringComparison.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(deviceNo))
            {
                query = query.Where(x => x.DeviceId.Contains(deviceNo, StringComparison.OrdinalIgnoreCase));
            }

            _totalCount = query.Count();
            _deviceList = query
                .Skip((_currentPage - 1) * _pageSize)
                .Take(_pageSize)
                .ToList();
        }

        private int GetCapacityPercent(DeviceDto device)
        {
            if (device.TankCapacity <= 0) return 0;
            return (int)(device.CurrentCapacity / device.TankCapacity * 100);
        }

        private string GetProgressColor(int percent)
        {
            if (percent >= 80) return "#52c41a";
            if (percent >= 50) return "#faad14";
            return "#ff4d4f";
        }

        #endregion

        #region 格式化方法

        private string FormatNumber(decimal? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("N2", CultureInfo.CreateSpecificCulture("zh-CN")) + " L";
        }

        private string FormatDateTime(DateTime? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private int GetTotalPages()
        {
            if (_pageSize <= 0) return 0;
            return (int)Math.Ceiling(_totalCount / (double)_pageSize);
        }

        #endregion

        #region 事件处理方法

        private void OnNewDevice()
        {
            _deviceModel = new DeviceEditModel
            {
                Id = 0,
                DeviceId = $"DEV{new Random().Next(1000, 9999)}",
                SiteBUID = $"SITE{new Random().Next(100, 200)}",
                SiteName = "绿城加油站",
                OilProductName = "92#汽油",
                TankCapacity = 10000,
                CurrentCapacity = 7500,
                Status = "正常",
                Location = "A区1号位",
                Manufacturer = "中石化设备",
                InstallationDate = DateTime.Today
            };
            _showNewDeviceDialog = true;
        }

        private void OnEditDevice(DeviceDto device)
        {
            _deviceModel = new DeviceEditModel
            {
                Id = device.Id,
                DeviceId = device.DeviceId,
                SiteBUID = device.SiteBUID,
                SiteName = device.SiteName,
                OilProductName = device.OilProductName,
                TankCapacity = device.TankCapacity,
                CurrentCapacity = device.CurrentCapacity,
                Status = device.Status,
                Location = device.Location,
                Manufacturer = device.Manufacturer,
                InstallationDate = device.InstallationDate
            };
            _showNewDeviceDialog = true;
        }

        private async Task OnDeleteDevice(DeviceDto device)
        {
            // 这里可以添加确认对话框逻辑
            _deviceList = _deviceList.Where(x => x.Id != device.Id).ToList();
            _totalCount--;
            await OnQuery();
        }

        private async Task OnSaveDevice()
        {
            try
            {
                if (string.IsNullOrEmpty(_deviceModel.DeviceId))
                {
                    return;
                }

                if (string.IsNullOrEmpty(_deviceModel.SiteBUID))
                {
                    return;
                }

                if (string.IsNullOrEmpty(_deviceModel.SiteName))
                {
                    return;
                }

                if (string.IsNullOrEmpty(_deviceModel.OilProductName))
                {
                    return;
                }

                if (_deviceModel.TankCapacity <= 0)
                {
                    return;
                }

                _loading = true;
                StateHasChanged();
                await Task.Delay(500);

                if (_deviceModel.Id == 0)
                {
                    var newId = _deviceList.Max(d => d.Id) + 1;
                    var newDevice = new DeviceDto
                    {
                        Id = newId,
                        DeviceId = _deviceModel.DeviceId,
                        SiteBUID = _deviceModel.SiteBUID,
                        SiteName = _deviceModel.SiteName,
                        OilProductName = _deviceModel.OilProductName,
                        TankCapacity = _deviceModel.TankCapacity,
                        CurrentCapacity = _deviceModel.CurrentCapacity,
                        LastUpdatedTime = DateTime.Now,
                        Status = _deviceModel.Status,
                        Location = _deviceModel.Location,
                        Manufacturer = _deviceModel.Manufacturer,
                        InstallationDate = _deviceModel.InstallationDate,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    _deviceList.Add(newDevice);
                }
                else
                {
                    var existingDevice = _deviceList.FirstOrDefault(d => d.Id == _deviceModel.Id);
                    if (existingDevice != null)
                    {
                        existingDevice.DeviceId = _deviceModel.DeviceId;
                        existingDevice.SiteBUID = _deviceModel.SiteBUID;
                        existingDevice.SiteName = _deviceModel.SiteName;
                        existingDevice.OilProductName = _deviceModel.OilProductName;
                        existingDevice.TankCapacity = _deviceModel.TankCapacity;
                        existingDevice.CurrentCapacity = _deviceModel.CurrentCapacity;
                        existingDevice.Status = _deviceModel.Status;
                        existingDevice.Location = _deviceModel.Location;
                        existingDevice.Manufacturer = _deviceModel.Manufacturer;
                        existingDevice.InstallationDate = _deviceModel.InstallationDate;
                        existingDevice.UpdateTime = DateTime.Now;
                        existingDevice.LastUpdatedTime = DateTime.Now;
                    }
                }

                _showNewDeviceDialog = false;
                await OnQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存失败: {ex.Message}");
            }
            finally
            {
                _loading = false;
                StateHasChanged();
            }
        }

        private async Task OnPageChange(int page)
        {
            if (page < 1 || page > GetTotalPages()) return;
            _currentPage = page;
            await OnQuery();
        }

        private void OnPageInputChange(ChangeEventArgs e)
        {
            if (int.TryParse(e.Value?.ToString(), out int page))
            {
                _currentPage = Math.Max(1, Math.Min(page, GetTotalPages()));
            }
        }

        private async Task OnPageSizeChange(ChangeEventArgs e)
        {
            if (int.TryParse(e.Value?.ToString(), out int pageSize))
            {
                _pageSize = pageSize;
                _currentPage = 1;
                await OnQuery();
            }
        }

        private void OnOilProductChange(ChangeEventArgs e)
        {
            _deviceModel.OilProductName = e.Value?.ToString() ?? "";
        }

        private void OnStatusChange(ChangeEventArgs e)
        {
            _deviceModel.Status = e.Value?.ToString() ?? "";
        }

        private void OnManufacturerChange(ChangeEventArgs e)
        {
            _deviceModel.Manufacturer = e.Value?.ToString() ?? "";
        }

        #endregion
    }
}
