//
//  UpdateAlertView.m
//  RealEstateManagement
//
//  Created by Javen on 2017/3/24.
//  Copyright © 2017年 上海勾芒信息科技. All rights reserved.
//

#import "UpdateAlertView.h"
#import "UpdateResponse.h"
#import "PgyUpdateManager.h"
@interface UpdateAlertView ()
@property (weak, nonatomic) IBOutlet UITextView *textViewContent;
@property (weak, nonatomic) IBOutlet UIButton *btnCancel;
@property (weak, nonatomic) IBOutlet UIButton *btnUpdate;
@property (weak, nonatomic) IBOutlet UILabel *labelNewVersion;
@property (strong, nonatomic) UIView *shadow;
@property (copy, nonatomic) void (^blockUpdate)(void);
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintCancelWidth;
@property (strong, nonatomic) NSString *updateUrl;
@end
@implementation UpdateAlertView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.shadow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.shadow.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.0];

    self.cornerRadius = 7;
    self.clipsToBounds = YES;
}

+ (UpdateAlertView *)alertWithNew:(NSString *)newVersion Content:(NSString *)content isForce:(BOOL)isForce url:(NSString *)url {
    UpdateAlertView *alertView = [UpdateAlertView viewFromNib];
    alertView.frame = CGRectMake(0, 0, 280, 220);
    alertView.center = kWindow.center;
    alertView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    alertView.labelNewVersion.text = [NSString stringWithFormat:@"(%@)",newVersion];
    //如果没有更新内容就使用默认的内容
    if (content != nil) {
        alertView.textViewContent.text = content;
    }
    
    if (isForce) {
        alertView.btnCancel.hidden = YES;
        alertView.constraintCancelWidth.constant = 280 - 32;
    }
    alertView.updateUrl = url;
    [alertView alert];
    
    return alertView;
}


+ (instancetype)updateWithVersion:(NSString *)newVersion
                           webUrl:(NSString *)webUrl
                          itemUrl:(NSString *)itemUrl
                          content:(NSString *)content
                          isForce:(BOOL)isForce
                         complete:(void (^)(BOOL isLatest))complete {
    
    if ([APP_VERSION compare:newVersion options:NSNumericSearch] != NSOrderedAscending) {
        CLog(@"已经是最新版本");
        complete(YES);
        return nil;
    }
    complete(NO);
    
    UpdateAlertView *alertView = [UpdateAlertView viewFromNib];
    alertView.frame = CGRectMake(0, 0, 280, 220);
    alertView.center = kWindow.center;
    alertView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    alertView.labelNewVersion.text = [NSString stringWithFormat:@"(%@)",newVersion];
    //如果没有更新内容就使用默认的内容
    if (content != nil) {
        alertView.textViewContent.text = content;
    }
    
    if (isForce) {
        alertView.btnCancel.hidden = YES;
        alertView.constraintCancelWidth.constant = 280 - 32;
    }
    
    alertView.updateUrl = itemUrl ? itemUrl : webUrl;
    [alertView alert];
    
    return alertView;
}

- (void)alert {
    [kWindow addSubview:self.shadow];
    [kWindow addSubview:self];
    [UIView animateWithDuration:0.5
                          delay:0
         usingSpringWithDamping:0.7
          initialSpringVelocity:1.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         self.shadow.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
                         self.transform = CGAffineTransformMakeScale(1, 1);
                     }
                     completion:nil];
}

- (void)cancel {
    [UIView animateWithDuration:0.5
        delay:0
        usingSpringWithDamping:0.9
        initialSpringVelocity:1.0
        options:UIViewAnimationOptionCurveEaseOut
        animations:^{
            self.transform = CGAffineTransformMakeScale(0.01, 0.01);
            self.shadow.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.0];
        }
        completion:^(BOOL finished) {
            [self.shadow removeFromSuperview];
            [self removeFromSuperview];
        }];
}

#pragma mark - 点击事件

- (IBAction)actionCancel:(id)sender {
    [self cancel];
}
- (IBAction)actionUpdate:(id)sender {
    [MBProgressHUD j_loading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD j_hideLoadingView];
    });
    
    [[UIApplication sharedApplication]
     openURL:[NSURL URLWithString:self.updateUrl]];
}

@end

@interface ZJUpdateManager ()
@property (nonatomic, strong) UpdateResponse *updateInfo;
@property (assign, nonatomic) UIViewController *superVC;
//@property (strong, nonatomic) MBProgressHUD *hud;
@property (copy, nonatomic) void (^blockComplete)(BOOL);
@end
@implementation ZJUpdateManager

- (void)checkOnVC:(UIViewController *)vc complete:(void (^)(BOOL isLatest))complete {
    self.superVC = vc;
    self.blockComplete = complete;
    WS(weakSelf);
//    self.hud = [MBProgressHUD j_loadingOnView:vc.view text:@"检查版本更新中…"];
    [ZJHttpManager GET:@"ipapk?type=ipa" parameters:nil complete:^(id responseObject, NSError *error) {
        if (kIsResponse) {
            weakSelf.updateInfo = [UpdateResponse modelWithDic:responseObject[@"data"]];
            [weakSelf pgyerUpdate];
        }else{
//            [weakSelf.hud hideAnimated:YES];
            kFalseHttpTips;
        }
    }];
}

- (void)pgyerUpdate {
    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:PGYER_APPID];
    [[PgyUpdateManager sharedPgyManager] checkUpdateWithDelegete:self selector:@selector(updateMethod:)];
}

- (void)updateMethod:(NSDictionary *)response {
//    [self.hud hideAnimated:YES];
    NSString *url = response[@"downloadURL"];
    [UpdateAlertView updateWithVersion:self.updateInfo.version webUrl:self.updateInfo.url itemUrl:url content:nil isForce:self.updateInfo.forceUpdate complete:self.blockComplete];
    
}

@end