//
//  XXGCountryCodeButton.m
//  XXGPlayKit
//
//  Created by apple on 2025/3/16.
//

#import "XXGCountryCodeButton.h"
#import "XXGUIDriver.h"
#import "UIImage+XXGImage.h"
#import "XXGNavigationController.h"
#import "UIImage+XXGImage.h"
#import "UIColor+XXGColor.h"

@implementation XXGCountryCodeButton

- (instancetype)initWithCurrentViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.xxpk_currentViewController = viewController;
        [self xxpk_commonInit];
    }
    return self;
}

// 公共初始化方法
- (void)xxpk_commonInit {
    // 默认倒计时为60秒
    NSArray *xxpk_allCountries = [XXGLocaleString xxpk_loadCountries:[XXGCountry class]];
    
    // 获取当前地区代码
    NSString *currentCountryCode = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    // 查找匹配的国家及其索引
    __block XXGCountry *matchedCountry = nil;
    [xxpk_allCountries enumerateObjectsUsingBlock:^(XXGCountry *country, NSUInteger idx, BOOL *stop) {
        if ([country.xxpk_countryCode caseInsensitiveCompare:currentCountryCode] == NSOrderedSame) {
            matchedCountry = country;
            *stop = YES; // 找到第一个匹配项后停止遍历
        }
    }];
    self.xxpk_currentCountry = matchedCountry;
    
    // 设置按钮标题
    NSString *title = [NSString stringWithFormat:@"%@%@",XXGUIDriver.xxpk_data_ui.xxpk_code_jia, matchedCountry.xxpk_dialCode];
    [self setTitle:title forState:UIControlStateNormal];
    
    // 添加右侧箭头图片（假设图片名为"ic_arrow_right"）
    UIImage *originalImage = [UIImage xxpk_imageBundleOfName:XXGUIDriver.xxpk_data_ui.xxpk_img_code_pulldown];
    
    // 定义目标图片尺寸（建议使用逻辑点）
    CGSize targetImageSize = CGSizeMake(13, 13); // 示例尺寸
    
    // 创建缩放后的图片（保持宽高比）
    UIImage *scaledImage = [self xxpk_imageWithImage:originalImage scaledToSize:targetImageSize];
    
    // 设置不同状态的图片
    [self setImage:scaledImage forState:UIControlStateNormal];
    [self setImage:[scaledImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateHighlighted]; // 高亮状态可加颜色变化
    
    // 配置图片显示模式
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    // 调整图片和标题布局
    self.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft; // 核心布局方向
    CGFloat spacing = 3.0; // 图片与文字间距
    self.imageEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, -spacing);  // 图片向右偏移
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -spacing, 0, spacing);   // 文字向左偏移
    
    // 样式配置
    [self setBackgroundImage:[UIImage xxpk_imageWithColor:[XXGUIDriver.xxpk_mainColor xxpk_lighterByPercentage:8]] forState:UIControlStateNormal];
    [self setBackgroundImage:[UIImage xxpk_imageWithColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5f]]
                   forState:UIControlStateHighlighted];
    self.titleLabel.font = [UIFont systemFontOfSize:16];
    self.layer.cornerRadius = 2.f;
    self.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMinXMaxYCorner;
    self.layer.masksToBounds = YES;
    
    // 调整内边距
    self.contentEdgeInsets = UIEdgeInsetsMake(8, 12, 8, 12); // 整体内边距
    
    // 自适应尺寸（需在设置内容后调用）
    [self sizeToFit];
    
    // 添加点击事件
    [self addTarget:self action:@selector(xxpk_buttonClicked) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 图片缩放工具方法
- (UIImage *)xxpk_imageWithImage:(UIImage *)image scaledToSize:(CGSize)targetSize {
    // 创建绘图上下文
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);
    
    // 计算保持宽高比的缩放比例
    CGFloat widthRatio = targetSize.width / image.size.width;
    CGFloat heightRatio = targetSize.height / image.size.height;
    CGFloat scaleFactor = MIN(widthRatio, heightRatio);
    
    // 计算目标绘制区域
    CGRect scaledRect = CGRectMake(0, 0,
                                  image.size.width * scaleFactor,
                                  image.size.height * scaleFactor);
    
    // 居中绘制
    CGPoint origin = CGPointMake((targetSize.width - scaledRect.size.width) / 2.0,
                               (targetSize.height - scaledRect.size.height) / 2.0);
    [image drawInRect:CGRectMake(origin.x, origin.y,
                                scaledRect.size.width,
                                scaledRect.size.height)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

/// 点击按钮时调用，触发发送验证码回调并启动倒计时
- (void)xxpk_buttonClicked {
    XXGCountryCodeSelectorViewController *vc = [XXGCountryCodeSelectorViewController new];
    vc.xxpk_codeDelegate = self;
    [self.xxpk_currentViewController.navigationController pushViewController:vc animated:NO];
}

- (void)xxpk_countryCodeSelectorDidSelectCountry:(XXGCountry *)country {
    NSString *title = [NSString stringWithFormat:@"%@%@",XXGUIDriver.xxpk_data_ui.xxpk_code_jia, country.xxpk_dialCode];
    [self setTitle:title forState:UIControlStateNormal];
    self.xxpk_currentCountry = country;
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
