import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'package:cached_network_image/cached_network_image.dart';

class CacheAvatar extends StatefulWidget {
  final String url;
  final Size? size;
  final double? circular;
  const CacheAvatar({super.key, required this.url, this.size, this.circular});

  @override
  State<CacheAvatar> createState() => _CacheAvatarState();
}

class _CacheAvatarState extends State<CacheAvatar> {
  // 从URL中提取文件名
  String _getFileNameFromUrl(String url) {
    try {
      Uri uri = Uri.parse(url);
      List<String> pathSegments = uri.pathSegments;
      if (pathSegments.isNotEmpty) {
        return pathSegments.last;
      }
    } catch (e) {
      print('Error parsing URL: $e');
    }
    // 如果无法解析URL，使用哈希值作为文件名
    return '${url.hashCode}.jpg';
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(widget.circular!=null?widget.circular!:8),
      child: SizedBox(
        width: widget.size!=null?widget.size?.width:48,
        height: widget.size!=null?widget.size?.height:50,
        child: CachedNetworkImage(
          imageUrl: widget.url,
          fit: BoxFit.cover,
          cacheKey: _getFileNameFromUrl(widget.url), // 使用文件名作为缓存key
          placeholder: (context, url) => Shimmer.fromColors(
            baseColor: Colors.grey.shade300,
            highlightColor: Colors.grey.shade100,
            child: Container(color: Colors.white),
          ),
          errorWidget: (context, url, error) => Container(
            color: Colors.grey.shade200,
            child: const Icon(Icons.error_outline, color: Colors.grey),
          ),
        ),
      ),
    );
  }
}