using EasyTemplate.Tool;
using EasyTemplate.Tool.Dto.MemberManagement;
using EasyTemplate.Tool.Entity.System.VehicleTerminal.BusinessUnitInfo;
using EasyTemplate.Tool.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 ZhonTai.Admin.Contracts.Domain.VehicleTerminal.ElectronicAccount;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.UserInfo;

namespace EasyTemplate.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? ErrorMessage { get; set; }
        #endregion

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

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

            // 模拟API调用延迟
            await Task.Delay(500);

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

            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
                {
                    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 void ApplyFilter()
        {
            var query = Customers.AsEnumerable();

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

            if (!string.IsNullOrWhiteSpace(SearchCustomerCode))
            {
                query = query.Where(c => c.AccountNo.Contains(SearchCustomerCode, StringComparison.OrdinalIgnoreCase));
            }

            FilteredCustomers = query.ToList();
        }

        protected void HandleSearch()
        {
            ApplyFilter();
        }
        #endregion

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

        protected void ShowEditModal(Customer customer)
        {
            // 创建副本以避免直接修改原始对象
            CurrentCustomer = new Customer
            {
                Id = customer.Id,
                CustomerName = customer.CustomerName,
                CustomerCode = customer.CustomerCode,
                Site = customer.Site,
                InvoiceTitle = customer.InvoiceTitle,
                TaxNumber = customer.TaxNumber,
                CompanyRegisteredAddress = customer.CompanyRegisteredAddress,
                CompanyPhone = customer.CompanyPhone,
                ContactAddress = customer.ContactAddress,
                CompanyEmail = customer.CompanyEmail,
                CardBalance = customer.CardBalance,
                Status = customer.Status,
                RegisterTime = customer.RegisterTime
            };
            ModalTitle = "编辑客户";
            ShowModal = true;
            IsCreating = false;
            ErrorMessage = null;
        }

        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(Customer customer)
        {
            NavigationManager.NavigateTo($"/cardManagement/corporateCard?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
    }
}