using AntDesign;
using AI.Platform.Page.Pages.Order;
using AI.Platform.Core;
using AI.Platform.Core.Dto.CardManagement;
using AI.Platform.Core.Dto.RechargeRecords;
using AI.Platform.Core.Entity.System.VehicleTerminal.BusinessUnitInfo;
using AI.Platform.Core.Entity.System.VehicleTerminal.CardInfo;
using AI.Platform.Core.Entity.System.VehicleTerminal.Company;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Company;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Device;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Driver;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.ElectronicAccount;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Payment;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;
using static AI.Platform.Page.Pages.Report.FuelTransactionReport;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace AI.Platform.Page.Pages.CardManagement
{
    public class FilterModel
    {
        public string OrderNo { get; set; } = string.Empty;
        public string Mobile { get; set; }
        public DateTime? StartTime { get; set; }
        public DateTime? EndTime { get; set; }
    }


    public class AccountInfo
    {
        public long Id { get; set; }
        public string AccountNo { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string Phone { get; set; } = string.Empty;
        public bool IsSelected { get; set; }
        public long AccountId { get; set; }
    }

    public class OilTypeOption
    {
        public string Type { get; set; } = string.Empty;
        public bool Selected { get; set; }
    }

    public class CardAllocationModel
    {
        public string CardNo { get; set; } = string.Empty;
        public DateTime? AvailableStartTime { get; set; } 
        public DateTime? AvailableEndTime { get; set; } 
        public decimal? SingleConsumptionLimit { get; set; }
        public decimal? TotalConsumptionLimit { get; set; } 
        public int? TotalConsumptionCountLimit { get; set; } 
        public int? DailyRefuelCountLimit { get; set; }
        public decimal? DailyConsumptionLimit { get; set; }
        public decimal? Longitude { get; set; }
        public decimal? Latitude { get; set; }
        public decimal? AllowedDistance { get; set; }
        public List<string> AllowedOilTypes { get; set; } = new();
    }
    public partial class CorporateCard : ComponentBase
    {
        #region 依赖注入
        /// <summary>
        /// 注入实例
        /// </summary>
        [Inject] private SqlSugarRepository<CardInfoEntity> _CardInforepository { get; set; }
        [Inject] private SqlSugarRepository<CompanyEntity> _Companyrepository { get; set; }
        [Inject] private SqlSugarRepository<ElectronicAccountEntity> _Accountrepository { get; set; }
        [Inject] private SqlSugarRepository<UserInfoEntity> _UserInforepository { get; set; }
        [Inject] private SqlSugarRepository<UserCardRelationEntity> _UserCardRelationrepository { get; set; }
        [Inject] private SqlSugarRepository<CompanyCardRuleEntity> _CompanyCardRuleRepository { get; set; }
        [Inject]
        protected IJSRuntime JSRuntime { get; set; } = default!;
        #endregion

        #region 
        public FilterModel Filter { get; set; } = new();
        public List<CardInfoDto> cardInfoDtos { get; set; } = new();
        public bool Loading { get; set; }
        public int TotalCount { get; set; }
        public int CurrentPage { get; set; } = 1;
        public int PageSize { get; set; } = 20;
        public string CardNo { get; set; } = string.Empty;
        public string CompanyName { get; set; }
        // 选项数据
        public List<string> DeviceOptions { get; set; } = new();
        public List<string> PlateNumberOptions { get; set; } = new();
        public List<string> OilTypeOptions { get; set; } = new();
        public List<string> PaymentMethodOptions { get; set; } = new();
        public List<string> PaymentStatusOptions { get; set; } = new();
        public List<string> OrderStatusOptions { get; set; } = new();
        public List<string> DriverOptions { get; set; } = new();
        #endregion

        #region 
        private bool _showCardAllocationModal = false;
        private bool _showSelectAccountModal = false;
        private CardInfoDto? _selectedCard;
        private List<AccountInfo> _assignedAccounts = new();
        private List<AccountInfo> _availableAccounts = new();
        private List<AccountInfo> _filteredAccounts = new();
        private CardAllocationModel _cardAllocation = new();
        private List<OilTypeOption> _oilTypes = new();
        private string _accountSearchKeyword = string.Empty;
        [Parameter]
        public int? CustomerId { get; set; }
        #endregion

        #region 生命周期方法
        protected override void OnInitialized()
        {
            InitializeData();
            _ = LoadDataAsync();
        }
        #endregion

        #region 初始化方法
        private void InitializeData()
        {

            // 设置默认时间范围（最近7天）
            Filter.StartTime = DateTime.Today.AddDays(-7);
            Filter.EndTime = DateTime.Today;

            // 初始化油品类型
            InitializeOilTypes();

            // 初始化账户数据
            InitializeAccountData();
        }

        private void InitializeOilTypes()
        {
            _oilTypes = new List<OilTypeOption>
            {
                new OilTypeOption { Type = "0#", Selected = false },
                new OilTypeOption { Type = "92#", Selected = false },
                new OilTypeOption { Type = "95#", Selected = false },
                new OilTypeOption { Type = "98#", Selected = false }
            };
        }
     
        private async Task InitializeAccountData()
        {
            // 模拟可用账户数据
            //_availableAccounts = new List<AccountInfo>
            //{
            //    new AccountInfo { AccountNo = "ACC001", Name = "张三", Phone = "13800138001" },
            //    new AccountInfo { AccountNo = "ACC002", Name = "李四", Phone = "13800138002" },
            //    new AccountInfo { AccountNo = "ACC003", Name = "王五", Phone = "13800138003" },
            //    new AccountInfo { AccountNo = "ACC004", Name = "赵六", Phone = "13800138004" },
            //    new AccountInfo { AccountNo = "ACC005", Name = "钱七", Phone = "13800138005" }
            //};
            //_filteredAccounts = _availableAccounts;
            _availableAccounts = await _UserInforepository.AsQueryable().
                 LeftJoin<ElectronicAccountEntity>((a, b) => a.Id == b.UserId)
                 .Select((a, b) => new AccountInfo
                 {
                     Id = a.Id,
                     AccountNo = b.AccountNo,
                     Name = a.UserName,
                     Phone = a.Mobile
                 }).ToListAsync();
            _filteredAccounts = _availableAccounts;
        }
        #endregion

        #region 数据操作方法
        private void ResetFilter()
        {
            Filter = new FilterModel
            {
                StartTime = DateTime.Today.AddDays(-7),
                EndTime = DateTime.Today
            };
            CurrentPage = 1;
        }

        protected async Task LoadDataAsync()
        {
            Loading = true;

            try
            {

                cardInfoDtos = await GenerateMockData();
                TotalCount = cardInfoDtos.Count(); 
            }
            finally
            {
                Loading = false;
                StateHasChanged();
            }
        }

        private async Task<List<CardInfoDto>> GenerateMockData()
        {
            var query = _CardInforepository.AsQueryable()
                .LeftJoin<CompanyEntity>((a, b) => a.AccountId == b.AccountId)
                .LeftJoin<ElectronicAccountEntity>((a, b, c) => c.Id == a.AccountId)
                .LeftJoin<BusinessUnitInfoEntity>((a, b, c, e) => e.Id == a.IssueSiteId);
            query = query.Where((a, b, c, e) => a.CardType == 2);
            if (!string.IsNullOrEmpty(CardNo))
                query = query.Where((a, b, c, e) => a.CardNo == CardNo);

            if (!string.IsNullOrEmpty(CompanyName))
                query = query.Where((a, b, c, e) => b.CustomerName == CompanyName);

            if (CustomerId != null)
            {
                query = query.Where((a, b, c, e) => c.Id == CustomerId);
            }
            var baseQuery = query.Select((a, b, c, e) => new CardInfoDto
            {
                AccountID = c.Id,
                StationName = e.Name,
                CompanyName = b.CustomerName,
                CardNo = a.CardNo,
                Id = a.Id,
                CardType = a.CardType == 1 ? "个人卡" : a.CardType == 2 ? "公司卡" : a.CardType == 3 ? "司机卡" : "未知",
                AccountBalance = c.Balance,
                IssueTime = a.IssueTime,
                LossTime = a.LossTime,
                Status = a.Status == 1 ? "正常" : a.Status == 2 ? "挂失" : a.Status == 3 ? "注销" : a.Status == 4 ? "冻结" : "未知"
            });
            TotalCount = await baseQuery.CountAsync();
            return await baseQuery
                           .Skip((CurrentPage - 1) * PageSize)
                           .Take(PageSize)
                           .ToListAsync(); 
        }

        // 格式化方法
        protected string FormatCurrency(decimal? value)
        {
            if (value == null) return "-";
            return value.Value.ToString("C", CultureInfo.CreateSpecificCulture("zh-CN"));
        }

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

        #endregion

        #region 卡分配相关方法
        // 显示卡分配模态框的方法
        protected async Task ShowCardAllocationModal(CardInfoDto card)
        {
            _selectedCard = card;
            _showCardAllocationModal = true;

            // 显示已分配的账户
            _assignedAccounts = await _UserCardRelationrepository.AsQueryable()
                                    .LeftJoin<UserInfoEntity>((a, b) => a.UserId == b.Id)
                                    .LeftJoin<CardInfoEntity>((a, b, c) => a.CardId == c.Id)
                                    .LeftJoin<ElectronicAccountEntity>((a, b, c, e) => b.Id == e.UserId)
                                    .Where((a, b, c, e) => c.Id == _selectedCard.Id && a.UserId != null)
                                    .Select((a, b, c, e) => new AccountInfo
                                    {
                                        Id = b.Id,
                                        AccountNo = e.AccountNo,
                                        AccountId = e.Id,
                                        Name = b.UserName,
                                        Phone = b.Mobile
                                    }).ToListAsync();
            // 重置油品类型选择
            InitializeOilTypes();

            StateHasChanged();
        }

        protected void CloseCardAllocationModal()
        {
            _showCardAllocationModal = false;
            _selectedCard = null;
            _cardAllocation = new CardAllocationModel();
            _assignedAccounts = new List<AccountInfo>();
            StateHasChanged();
        }

        // 显示选择账户模态框的方法
        protected void ShowSelectAccountModal()
        {
            _accountSearchKeyword = string.Empty;
            FilterAccounts();
            _showSelectAccountModal = true;
            StateHasChanged();
        }

        protected void CloseSelectAccountModal()
        {
            _showSelectAccountModal = false;
            StateHasChanged();
        }

        protected void FilterAccounts()
        {
            if (string.IsNullOrWhiteSpace(_accountSearchKeyword))
            {
                _filteredAccounts = _availableAccounts
                    .Where(a => !_assignedAccounts.Any(assigned => assigned.Id == a.Id))
                    .ToList();
            }
            else
            {
                _filteredAccounts = _availableAccounts
                    .Where(a => !_assignedAccounts.Any(assigned => assigned.Id == a.Id))
                    .Where(a => a.AccountNo.Contains(_accountSearchKeyword, StringComparison.OrdinalIgnoreCase) ||
                               a.Name.Contains(_accountSearchKeyword, StringComparison.OrdinalIgnoreCase) ||
                               a.Phone.Contains(_accountSearchKeyword, StringComparison.OrdinalIgnoreCase))
                    .ToList();
            }
        }

        // 账户搜索输入变化
        protected void OnAccountSearchInput(ChangeEventArgs e)
        {
            _accountSearchKeyword = e.Value?.ToString() ?? string.Empty;
            FilterAccounts();
            StateHasChanged();
        }

        protected async Task SelectAccount(AccountInfo account)
        {
            //_selectedCard
            if (!_assignedAccounts.Any(a => a.Id == account.Id))
            {
                UserCardRelationEntity entity = new UserCardRelationEntity();
                entity.UserId = account.Id;
                entity.CardId = _selectedCard.Id;
                // entity.Id = 4;
                _UserCardRelationrepository.AsInsertable(entity).ExecuteReturnIdentity();
                _assignedAccounts.Add(account);
                CloseSelectAccountModal();
                StateHasChanged();
            }
        }

        protected void RemoveAccount(AccountInfo account)
        {
            _assignedAccounts.Remove(account);
            StateHasChanged();
        }

        protected void HandleOilTypeChange(ChangeEventArgs e, OilTypeOption oilType)
        {
            var isChecked = (bool?)e.Value ?? false;
            oilType.Selected = isChecked;

            // 更新卡分配模型中的油品类型列表
            _cardAllocation.AllowedOilTypes = _oilTypes
                .Where(o => o.Selected)
                .Select(o => o.Type)
                .ToList();
        }

        protected async Task SaveCardAllocation()
        {
            try
            {
                // 验证数据 _selectedCard?.CardNo
                if (string.IsNullOrEmpty(_selectedCard.CardNo))
                {
                    await ShowAlert("错误", "卡号不能为空");
                    return;
                }

                if (_cardAllocation.AvailableEndTime <= _cardAllocation.AvailableStartTime)
                {
                    await ShowAlert("错误", "结束时间必须晚于开始时间");
                    return;
                }

                if (_oilTypes.Where(_ => _.Selected).Count() <= 0)
                {
                    await ShowAlert("警告", "请至少选择一种允许的油品类型");
                    return;
                }
                //查询是否有规则
                var CompanyCardRule = new CompanyCardRuleEntity();
                var account = await _CompanyCardRuleRepository.AsQueryable()
                    .Where(_ => _.UserAccountId == 1 && _.CompanyAccountId == 1).ToListAsync();

                string ProductsName = string.Join(",", _oilTypes.Where(_ => _.Selected).Select(o => o.Type));
                CompanyCardRule.SiteId = 1;
                CompanyCardRule.CompanyAccountId = _selectedCard.AccountID;
                CompanyCardRule.UserAccountId = _assignedAccounts.Where(_ => _.IsSelected).FirstOrDefault()?.AccountId;
                CompanyCardRule.CardNumber = _selectedCard.CardNo;
                CompanyCardRule.ValidStartTime = _cardAllocation.AvailableStartTime;
                CompanyCardRule.ValidEndTime = _cardAllocation.AvailableEndTime;
                CompanyCardRule.OilProducts = ProductsName;
                CompanyCardRule.SingleAmountLimit = _cardAllocation.SingleConsumptionLimit;
                CompanyCardRule.TotalAmountLimit = _cardAllocation.TotalConsumptionLimit;
                CompanyCardRule.TotalCountLimit = _cardAllocation.TotalConsumptionCountLimit;
                CompanyCardRule.RefuelTimesPerUse = _cardAllocation.DailyRefuelCountLimit;
                CompanyCardRule.DailyAmountLimit = _cardAllocation.DailyConsumptionLimit;
                CompanyCardRule.Latitude = _cardAllocation.Latitude;
                CompanyCardRule.Longitude = _cardAllocation.Longitude;
                CompanyCardRule.UsageDistance = _cardAllocation.AllowedDistance;
                if (account.Count() > 0)
                {
                    _CompanyCardRuleRepository.UpdateAsync(CompanyCardRule);
                }
                else
                {
                   _CompanyCardRuleRepository.AsInsertable(CompanyCardRule).ExecuteReturnIdentity();
                }

                await ShowAlert("成功", "卡分配设置已保存");
                CloseCardAllocationModal();
            }
            catch (Exception ex)
            {
                await ShowAlert("错误", $"保存失败: {ex.Message}");
            }
        }

        private async Task ShowAlert(string title, string message)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"{title}: {message}");
        }
        #endregion

        #region 事件处理方法
        protected async Task HandleQuery()
        {
            CurrentPage = 1;
            await LoadDataAsync();
        }

        protected async Task HandleReset()
        {
            ResetFilter();
            await LoadDataAsync();
        }

        protected async Task OnPageChange(int page)
        {
            CurrentPage = page;
            await LoadDataAsync();
        }

        protected async Task OnPageSizeChange(int pageSize)
        {
            PageSize = pageSize;
            CurrentPage = 1;
            await LoadDataAsync();
        }

        // 选中左侧列表中的账户
        private async Task SelectAccountInList(AccountInfo account)
        {
            foreach (var acc in _assignedAccounts ?? new List<AccountInfo>())
            {
                acc.IsSelected = false;
            }
            // 设置当前账户为选中状态
            account.IsSelected = true;

            string selectedAccountNo = account.AccountNo;
            var CompanyCardRule = await _CompanyCardRuleRepository.AsQueryable()
    .Where(_ => _.UserAccountId == account.AccountId && _.CompanyAccountId == _selectedCard.AccountID).FirstAsync();
            if (CompanyCardRule != null)
            {
                _cardAllocation = new CardAllocationModel()
                {
                    CardNo = _selectedCard.CardNo,
                    AvailableStartTime = CompanyCardRule.ValidStartTime,
                    AvailableEndTime = CompanyCardRule.ValidEndTime,
                    SingleConsumptionLimit = CompanyCardRule.SingleAmountLimit,
                    TotalConsumptionLimit = CompanyCardRule.TotalAmountLimit,
                    TotalConsumptionCountLimit = CompanyCardRule.TotalCountLimit,
                    DailyRefuelCountLimit = CompanyCardRule.RefuelTimesPerUse,
                    DailyConsumptionLimit = CompanyCardRule.DailyAmountLimit,
                    Latitude = CompanyCardRule.Latitude,
                    Longitude = CompanyCardRule.Longitude,
                    AllowedDistance = CompanyCardRule.UsageDistance,
                };
                _oilTypes = new List<OilTypeOption>
                {
                    new OilTypeOption { Type = "0#", Selected = false },
                    new OilTypeOption { Type = "92#", Selected = false },
                    new OilTypeOption { Type = "95#", Selected = false },
                    new OilTypeOption { Type = "98#", Selected = false }
                };
                var OilProducts = CompanyCardRule.OilProducts.Split(',');
                foreach (var product in OilProducts)
                {
                    var item = _oilTypes.FirstOrDefault(x => x.Type == product);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
                //OilProducts.ForEach(_ => {
                //    var item = _oilTypes.FirstOrDefault(x => x.Type == _);
                //    if (item != null)
                //    {
                //        item.Selected = true;
                //    }
                //});
            }
            else
            {
                _cardAllocation = new CardAllocationModel();
                _oilTypes = new List<OilTypeOption>
                {
                    new OilTypeOption { Type = "0#", Selected = false },
                    new OilTypeOption { Type = "92#", Selected = false },
                    new OilTypeOption { Type = "95#", Selected = false },
                    new OilTypeOption { Type = "98#", Selected = false }
                };
            }
        }
        private string FormatDateTime(DateTime? dateTime)
        {
            return dateTime?.ToString("yyyy-MM-ddTHH:mm") ?? "";
        }

        private void HandleDateTimeChange(ChangeEventArgs e, string type)
        {
            if (e.Value is string value && !string.IsNullOrEmpty(value))
            {
                var dateTime = DateTime.Parse(value);
                if (type == "start")
                {
                    _cardAllocation.AvailableStartTime = dateTime;
                }
                else
                {
                    _cardAllocation.AvailableEndTime = dateTime;
                }
            }
            else
            {
                if (type == "start")
                {
                    _cardAllocation.AvailableStartTime = null;
                }
                else
                {
                    _cardAllocation.AvailableEndTime = null;
                }
            }
        }
        // 切换选择账户弹窗中的选中状态
        private void ToggleAccountSelection(AccountInfo account)
        {
            account.IsSelected = !account.IsSelected;
        }

        // 选择单个账户并添加到左侧列表
        private void SelectSingleAccount(AccountInfo account)
        {
            // 确保账户没有被重复添加
            if (_assignedAccounts?.Any(a => a.AccountNo == account.AccountNo) == true)
            {
                // 可以在这里添加提示信息
                return;
            }

            // 添加到左侧列表
            _assignedAccounts ??= new List<AccountInfo>();
            _assignedAccounts.Add(new AccountInfo
            {
                AccountNo = account.AccountNo,
                Name = account.Name,
                Phone = account.Phone
            });

            // 关闭弹窗
            CloseSelectAccountModal();
        }
        #endregion
    }
}