//
//  FWADView.m
//  FeasyWIFI
//
//  Created by ericj on 2020/7/14.
//  Copyright © 2020 Feasycom. All rights reserved.
//

#import "FWADView.h"
#import "FWADRootClass.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <AFNetworking/AFNetworking.h>

#define kRequestURL @"https://api.feasycom.com/lanch"

@interface FWADView ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;// 图片
@property (weak, nonatomic) IBOutlet UIButton *secondBtn;// 按钮
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layout_btn_top;
@property (nonatomic) NSInteger seconds;// 倒计时
@end

@implementation FWADView

+ (UIImage *)getLaunchImage {
    UIImage *launchImg = nil;
    NSString *orientation = @"";
    const CGSize screenSize = [UIScreen mainScreen].bounds.size;
    const UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (statusBarOrientation == UIInterfaceOrientationLandscapeLeft || statusBarOrientation == UIInterfaceOrientationLandscapeRight) {
        orientation = @"Landscape";
    } else {
        orientation = @"Portrait";
    }
    NSArray *imgsInfoArr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchImages"];
    for (NSDictionary *info in imgsInfoArr) {
        const CGSize imgSize = CGSizeFromString(info[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imgSize, screenSize) && [orientation isEqualToString:info[@"UILaunchImageOrientation"]] ) {
            launchImg = [UIImage imageNamed:info[@"UILaunchImageName"]];
        }
    }
    return launchImg;
}

+ (void)showWithSeconds:(NSInteger)seconds {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    FWADView *targetView = [[[NSBundle mainBundle] loadNibNamed:@"FWADView" owner:nil options:0] firstObject];
    targetView.frame = window.bounds;
    [window addSubview:targetView];
    targetView.seconds = seconds;
    NSLog(@"进来了");
    CGFloat statusBarHeight = 0.f;
    if (@available(iOS 13.0, *)) {
        statusBarHeight = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame.size.height;
    } else {
        statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
    }
    targetView.layout_btn_top.constant = statusBarHeight;
    [targetView.secondBtn setTitle:[NSString stringWithFormat:@"%lds | Close", (long)targetView.seconds] forState:UIControlStateNormal];
    __weak typeof(targetView) weakSelf = targetView;
    NSString *imageUrl = [[NSUserDefaults standardUserDefaults] valueForKey:@"lanchad"];
    UIImage *placeholder = [self getLaunchImage];
    
    if (imageUrl){
        NSLog(@"有图片：%@", imageUrl);
        [targetView.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:placeholder];
    } else {
        [targetView.imageView setImage:placeholder];
    }
    // 获取图片
    AFHTTPSessionManager *httpSessionManager = [[AFHTTPSessionManager alloc] init];
    httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [httpSessionManager POST:kRequestURL parameters:@{ @"app" : @"beacon" } headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        FWADRootClass *root = [[FWADRootClass alloc] initWithDictionary:responseObject];
        NSLog(@"image: %@", root.data.image);
        [weakSelf.imageView sd_setImageWithURL:[NSURL URLWithString:root.data.image] placeholderImage:placeholder];
        [[NSUserDefaults standardUserDefaults] setValue:root.data.image forKey:@"lanchad"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    // 有倒计时开启倒计时
    if (targetView.seconds > 0){
        [NSTimer scheduledTimerWithTimeInterval:1 target:targetView selector:@selector(secondTimerGo:) userInfo:nil repeats:YES];
    }
}

- (IBAction)clickClose:(id)sender {
    __weak typeof(self) weakSelf = self;
     [UIView animateWithDuration:0.2 animations:^{
         weakSelf.alpha = 0;
     } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
     }];
}

// 倒计时
- (void)secondTimerGo:(NSTimer *)timer {
    NSLog(@"倒计时：%ld", (long)self.seconds);
    self.seconds--;
    NSString *secondString = [NSString stringWithFormat:@"%lds | Close", (long)self.seconds];
    self.secondBtn.titleLabel.text = secondString;
    [self.secondBtn setTitle:secondString forState:UIControlStateNormal];
    
    if (self.seconds == 0){
        [self clickClose:nil];
        [timer invalidate];
    }
}


@end
