using AI.Platform.Core;
using AI.Platform.Core.Dto.MemberManagement;
using AI.Platform.Core.Entity.System.VehicleTerminal.BusinessUnitInfo;
using AI.Platform.Core.Entity.System.VehicleTerminal.Company;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.ElectronicAccount;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;

namespace AI.Platform.Page.Pages.MemberManagement
{
    public partial class IndividualCustomer : ComponentBase
    {
        #region 依赖注入
        /// <summary>
        /// 注入实例
        /// </summary>
        [Inject] private SqlSugarRepository<CompanyEntity> _repository { get; set; }
        [Inject] private SqlSugarRepository<ElectronicAccountEntity> _Accountrepository { get; set; }
        [Inject] private SqlSugarRepository<UserInfoEntity> _UserInforepository { get; set; }
        [Inject]
        protected IJSRuntime JSRuntime { get; set; } = default!;
        [Inject]
        protected NavigationManager NavigationManager { get; set; } = default!;
        #endregion

        #region 状态变量
        protected List<UserInfoDto> Customers { get; set; } = new();
        protected List<UserInfoDto> FilteredCustomers { get; set; } = new();
        protected Customer CurrentCustomer { get; set; } = new();
        protected Customer? CustomerToDelete { get; set; }

        protected bool ShowModal { get; set; } = false;
        protected bool ShowDeleteDialog { get; set; } = false;
        protected bool IsCreating { get; set; } = false;
        protected string ModalTitle { get; set; } = "";
        protected bool Loading { get; set; } = false;
        protected string SearchCustomerName { get; set; } = "";
        protected string SearchCustomerCode { get; set; } = "";
        protected string SearchCustomerMobile { get; set; } = "";

        protected string? ErrorMessage { get; set; }

        protected int TotalCount { get; set; }
        protected int CurrentPage { get; set; } = 1;
        protected int PageSize { get; set; } = 20;
        #endregion

        #region 生命周期方法
        protected override async Task OnInitializedAsync()
        {
            await LoadCustomers();
        }
        #endregion

        #region 数据操作方法
        protected async Task LoadCustomers()
        {
            Loading = true;


            // 初始化示例数据
            if (Customers.Count == 0)
            {
               // Customers = await GetSampleCustomers();
            }

           await ApplyFilter();
            Loading = false;
        }

        private async Task<List<UserInfoDto>> GetSampleCustomers()
        {
          return  await _UserInforepository.AsQueryable()
                .LeftJoin<ElectronicAccountEntity>((a, b) => a.Id == b.UserId)
                 .LeftJoin<BusinessUnitInfoEntity>((a, b, c) => a.SiteId == c.Id)
                .Select((a, b, c) => new UserInfoDto
                {
                    Id = b.Id,
                    AccountNo = b.AccountNo,
                    AvatarUrl = a.AvatarUrl,
                    Balance = b.Balance,
                    LastActiveTime = a.LastActiveTime,
                    Mobile = a.Mobile,
                    Name = a.UserName,
                    RecentBehavior = a.RecentBehavior,
                    RegisterTime = a.RegisterTime,
                    StationName = c.Name
                }).ToListAsync();
        }

        protected async Task ApplyFilter()
        {
            var query = _UserInforepository.AsQueryable()
                .LeftJoin<ElectronicAccountEntity>((a, b) => a.Id == b.UserId)
                 .LeftJoin<BusinessUnitInfoEntity>((a, b, c) => a.SiteId == c.Id);

            if (!string.IsNullOrWhiteSpace(SearchCustomerName))
            {
                query = query.Where((a, b, c) => a.UserName.Contains(SearchCustomerName, StringComparison.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrWhiteSpace(SearchCustomerCode))
            {
                query = query.Where((a, b, c) => b.AccountNo.Contains(SearchCustomerCode, StringComparison.OrdinalIgnoreCase));
            }
            if (!string.IsNullOrWhiteSpace(SearchCustomerMobile))
            {
                query = query.Where((a, b, c) => a.Mobile.Contains(SearchCustomerMobile, StringComparison.OrdinalIgnoreCase));
            }
            var baseQuery = query.Select((a, b, c) => new UserInfoDto
            {
                Id = b.Id,
                AccountNo = b.AccountNo,
                AvatarUrl = a.AvatarUrl,
                Balance = b.Balance,
                LastActiveTime = a.LastActiveTime,
                Mobile = a.Mobile,
                Name = a.UserName,
                RecentBehavior = a.RecentBehavior,
                RegisterTime = a.RegisterTime,
                StationName = c.Name
            });
          TotalCount = await baseQuery.CountAsync();
            FilteredCustomers = await baseQuery.Skip((CurrentPage - 1) * PageSize)
                            .Take(PageSize)
                            .ToListAsync();
            Customers = FilteredCustomers;
        }

        protected void HandleSearch()
        {
            ApplyFilter();
        }
        // 页码变化
        protected async Task HandlePageChange(PaginationEventArgs args)
        {
            CurrentPage = args.Page;
            await LoadCustomers();
        }

        // 每页大小变化 - 使用 PaginationEventArgs
        protected async Task HandlePageSizeChange(PaginationEventArgs args)
        {
            PageSize = args.PageSize;
            CurrentPage = 1;
            await LoadCustomers();
        }
        #endregion

        #region 模态框操作
        protected void ShowCreateModal()
        {
            CurrentCustomer = new Customer
            {
                RegisterTime = DateTime.Now,
                Status = "正常"
            };
            ModalTitle = "新建客户";
            ShowModal = true;
            IsCreating = true;
            ErrorMessage = null;
        }

        protected void ShowEditModal(UserInfoDto customer)
        {
        }

        protected void CloseModal()
        {
            ShowModal = false;
            CurrentCustomer = new Customer();
            ErrorMessage = null;
        }

      
        #endregion

        #region 删除操作
        protected void ShowDeleteConfirm(Customer customer)
        {
            CustomerToDelete = customer;
            ShowDeleteDialog = true;
        }

        protected void CancelDelete()
        {
            ShowDeleteDialog = false;
            CustomerToDelete = null;
        }


        #endregion

        #region 卡管理操作
        protected void ShowCardManagement(UserInfoDto customer)
        {
           NavigationManager.NavigateTo($"/cardManagement/personalCard?customerId={customer.Id}");
        }
        #endregion

        #region 辅助方法
        protected string GetStatusColor(string status)
        {
            return status switch
            {
                "正常" => "#52c41a",    // 绿色
                "禁用" => "#f5222d",    // 红色
                "注销" => "#faad14",   // 橙色
                _ => "#d9d9d9"         // 灰色
            };
        }

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

        // 验证邮箱格式
        private bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
                return false;

            try
            {
                var regex = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
                return regex.IsMatch(email);
            }
            catch
            {
                return false;
            }
        }

        // 验证电话号码格式（简单的电话号码验证）
        private bool IsValidPhoneNumber(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
                return false;

            // 移除所有空格和连字符
            var cleanedPhone = phone.Replace(" ", "").Replace("-", "");

            // 检查是否只包含数字和可能的加号
            var regex = new Regex(@"^\+?[0-9\s\-\(\)]+$");
            return regex.IsMatch(phone);
        }

        // 模拟保存数据到本地存储
        protected async Task SaveToLocalStorage()
        {
            var json = JsonSerializer.Serialize(Customers);
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "customers", json);
        }

        #endregion
    }
}