import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:country_flags/country_flags.dart';

class KRCountryFlag extends StatelessWidget {
  final String countryCode;
  final double? width;
  final double? height;
  final bool isCircle;
  final BoxFit fit;         // 填充模式
  final bool maintainSize;  // 是否保持宽高比
  final Color? bgColor;     // 背景色
  final bool clip;          // 是否裁剪

  const KRCountryFlag({
    Key? key,
    required this.countryCode,
    this.width,
    this.height,
    this.isCircle = true,
    this.fit = BoxFit.cover,    // 默认填充
    this.maintainSize = true,   // 默认保持宽高比
    this.bgColor = Colors.white,
    this.clip = true,           // 默认裁剪
  }) : super(key: key);

  String _getCountryCode(String code) {
    // 处理特殊国家代码
    final Map<String, String> specialCases = {
      'UK': 'gb',
      'USA': 'us',
      // 添加其他特殊情况...
    };
    
    return specialCases[code.toUpperCase()] ?? code.toLowerCase();
  }

  @override
  Widget build(BuildContext context) {
    // 计算实际尺寸
    final double actualWidth = width ?? 50.w;
    final double actualHeight = maintainSize ? actualWidth : (height ?? 50.w);
    
    Widget flagWidget = CountryFlag.fromCountryCode(
      _getCountryCode(countryCode),
      width: actualWidth,
      height: actualHeight,
    );

    // 添加填充模式
    flagWidget = SizedBox(
      width: actualWidth,
      height: actualHeight,
      child: FittedBox(
        fit: fit,
        child: flagWidget,
      ),
    );
    
    // 添加背景和形状
    flagWidget = Container(
      width: actualWidth,
      height: actualHeight,
      decoration: BoxDecoration(
        color: bgColor,
        shape: isCircle ? BoxShape.circle : BoxShape.rectangle,
        borderRadius: !isCircle ? BorderRadius.circular(8.w) : null,
      ),
      child: flagWidget,
    );

    // 最后添加裁剪
    if (clip && isCircle) {
      flagWidget = ClipOval(child: flagWidget);
    }
    
    return flagWidget;
  }
} 