using EasyTemplate.Tool;
using EasyTemplate.Tool.Dto.MemberManagement;
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 System.Threading.Tasks;
using ZhonTai.Admin.Contracts.Domain.VehicleTerminal.Company;

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

        #region 状态变量
        protected List<Customer> Customers { get; set; } = new();
        protected List<Customer> 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;
            StateHasChanged();

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

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

            ApplyFilter();
            Loading = false;
            StateHasChanged();
        }

        private async Task<List<Customer>> GetSampleCustomers()
        {
            return await _repository.AsQueryable()
                                           .Select(_ => new Customer{
                                               CustomerName = _.CustomerName,
                                               CustomerCode = _.CustomerCode,
                                               SiteID = _.SiteId,
                                               InvoiceTitle = _.InvoiceTitle,
                                               TaxNumber = _.TaxNumber,
                                               CompanyRegisteredAddress = _.RegisterAddress,
                                               CompanyPhone =_.RegisterPhone,
                                               ContactAddress = _.CompanyAddress,
                                               CompanyEmail =_.CompanyEmail,
                                               CardBalance = 0m,
                                               Status = _.Status == 1 ? "正常" : _.Status == 2 ? "禁用" : _.Status == 3 ? "注销" : "未知",
                                               RegisterTime = _.RegistrationTime
                                           }).ToListAsync();
        }

        protected void ApplyFilter()
        {
            var query = Customers.AsEnumerable();

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

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

            FilteredCustomers = query.ToList();
        }
        protected void HandleSearch()
        {
            ApplyFilter();
            StateHasChanged();
        }
        #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;
        }

        protected async Task HandleSave()
        {
            // 清除之前的错误消息
            ErrorMessage = null;

            // 验证必填字段
            if (string.IsNullOrWhiteSpace(CurrentCustomer.CustomerName))
            {
                ErrorMessage = "客户名称不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.CustomerCode))
            {
                ErrorMessage = "客户编号不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.InvoiceTitle))
            {
                ErrorMessage = "发票抬头不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.TaxNumber))
            {
                ErrorMessage = "税号不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.CompanyRegisteredAddress))
            {
                ErrorMessage = "公司注册地址不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.CompanyPhone))
            {
                ErrorMessage = "公司注册电话不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (string.IsNullOrWhiteSpace(CurrentCustomer.CompanyEmail))
            {
                ErrorMessage = "公司邮箱不能为空";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            // 验证邮箱格式
            if (!IsValidEmail(CurrentCustomer.CompanyEmail))
            {
                ErrorMessage = "公司邮箱格式不正确";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            // 验证电话号码格式
            if (!IsValidPhoneNumber(CurrentCustomer.CompanyPhone))
            {
                ErrorMessage = "公司注册电话格式不正确";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            // 检查客户编号是否重复（编辑时排除自身）
            if (IsCreating && Customers.Any(c => c.CustomerCode == CurrentCustomer.CustomerCode))
            {
                ErrorMessage = "客户编号已存在";
                await ShowAlert("错误", ErrorMessage);
                return;
            }

            if (!IsCreating)
            {
                // 编辑模式
                var existingCustomer = Customers.FirstOrDefault(c => c.Id == CurrentCustomer.Id);
                if (existingCustomer != null)
                {
                    // 更新现有客户
                    existingCustomer.CustomerName = CurrentCustomer.CustomerName;
                    existingCustomer.CustomerCode = CurrentCustomer.CustomerCode;
                    existingCustomer.Site = CurrentCustomer.Site;
                    existingCustomer.InvoiceTitle = CurrentCustomer.InvoiceTitle;
                    existingCustomer.TaxNumber = CurrentCustomer.TaxNumber;
                    existingCustomer.CompanyRegisteredAddress = CurrentCustomer.CompanyRegisteredAddress;
                    existingCustomer.CompanyPhone = CurrentCustomer.CompanyPhone;
                    existingCustomer.ContactAddress = CurrentCustomer.ContactAddress;
                    existingCustomer.CompanyEmail = CurrentCustomer.CompanyEmail;
                    existingCustomer.CardBalance = CurrentCustomer.CardBalance;
                    existingCustomer.Status = CurrentCustomer.Status;
                    existingCustomer.RegisterTime = CurrentCustomer.RegisterTime;

                    await ShowAlert("成功", "客户信息更新成功");
                }
            }
            else
            {
                CompanyEntity entity = new CompanyEntity();
                entity.CustomerName = CurrentCustomer.CustomerName;
                entity.CustomerCode = CurrentCustomer.CustomerCode;
                entity.SiteId = 1;
                entity.InvoiceTitle = CurrentCustomer.InvoiceTitle;
                entity.TaxNumber = CurrentCustomer.TaxNumber;
                entity.RegistrationTime = CurrentCustomer.RegisterTime;
                entity.RegisterAddress = CurrentCustomer.CompanyRegisteredAddress;
                entity.RegisterPhone = CurrentCustomer.CompanyPhone;
                entity.Status = 1;
                entity.CompanyAddress = CurrentCustomer.ContactAddress;
                entity.CompanyEmail = CurrentCustomer.CompanyEmail;
                var result = await _repository.AsInsertable(entity).ExecuteCommandAsync();
                // 新建模式
                Customers.Add(CurrentCustomer);
                await ShowAlert("成功", "客户创建成功");
            }

            ShowModal = false;
            await LoadCustomers();
        }
        #endregion

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

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

        protected async Task ConfirmDelete()
        {
            if (CustomerToDelete != null)
            {
                var index = Customers.FindIndex(c => c.Id == CustomerToDelete.Id);
                if (index >= 0)
                {
                    Customers.RemoveAt(index);
                    await ShowAlert("成功", "客户删除成功");
                    ShowDeleteDialog = false;
                    CustomerToDelete = null;
                    await LoadCustomers();
                }
            }
        }
        #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);
        }

        // 模拟从本地存储加载数据
        protected async Task LoadFromLocalStorage()
        {
            try
            {
                var json = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "customers");
                if (!string.IsNullOrEmpty(json))
                {
                    var loadedCustomers = JsonSerializer.Deserialize<List<Customer>>(json);
                    if (loadedCustomers != null)
                    {
                        Customers = loadedCustomers;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载数据失败: {ex.Message}");
            }
        }
        #endregion
    }
}