//
//  RDCheckAppVersion.m
//  SmartHome
//
//  Created by Rayson on 2018/3/17.
//  Copyright © 2018年 Realde. All rights reserved.
//

#import "RDCheckAppVersion.h"
#import "NSDate+currentDate.h"
#import <UIKit/UIKit.h>

@interface RDCheckAppVersion ()
@property (nonatomic,copy) NSString *appId;  // ** appStore的appid */
@end

@implementation RDCheckAppVersion

+(RDCheckAppVersion *)sharedInstance{
    static RDCheckAppVersion *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[RDCheckAppVersion alloc] init];
    });
    return instance;
}

- (NSString *)curVersion{
    if (_curVersion == nil) {
        _curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    }
    return _curVersion;
}

- (NSString *)curVersionDetail{
    if (_curVersionDetail == nil) {
        NSString *version = self.curVersion;
        NSString *bundle = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        _curVersionDetail = [NSString stringWithFormat:@"%@(%@)",version, bundle];
    }
    return _curVersionDetail;
}

- (void)checkUpdateAlert{
    
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_appVersionCheckSuccess:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 0) {
           
            NSDictionary *data = responseObject[@"data"];
            BOOL needUpdate = [data[@"need_update"] boolValue];
            if (!needUpdate) {
                [weakSelf noUpdate];
                return;
            }
            
            NSDictionary *info = data[@"update_info"];
            NSString *content = info[@"content"];
            BOOL forceUpdate = info[@"force_update"];// 是否强制更新
            [weakSelf p_checkUpdateOnAppStoreContent:content canCancel:forceUpdate];
        } else{
        }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)noUpdate{
    [TheAlertCtrl rds_alertWithTitle:@"提示" message:@"当前是最新版本，无需更新。"];
}

-(void)checkUpdate{
    
    [self p_checkUpdateOnServer];
}

// 请求服务器上的检查更新接口
- (void)p_checkUpdateOnServer{
    
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_appVersionCheckSuccess:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 0) {
           
            NSDictionary *data = responseObject[@"data"];
            BOOL needUpdate = [data[@"need_update"] boolValue];
            if (!needUpdate) return;
            
            NSDictionary *info = data[@"update_info"];
            NSString *content = info[@"content"];
            BOOL forceUpdate = info[@"force_update"];// 是否强制更新
            [weakSelf p_checkUpdateOnAppStoreContent:content canCancel:forceUpdate];
        } else{
        }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)p_checkUpdateOnAppStoreContent:(NSString *)content canCancel:(BOOL)canCancel{
    
    if(canCancel){
        // 用户选了暂不更新的话，当天不再提示更新
        NSDate *noUpdate = [kUserDefaults objectForKey:@"noUpdate"];
        BOOL isToday = [NSDate isDateInToday:noUpdate];
        if(isToday) return;
    }
    
    NSURL *appUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",kAppIdOnAppStore]];
    NSString *appMsg = [NSString stringWithContentsOfURL:appUrl encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *appMsgDict = [RDCheckAppVersion jsonStringToDictionary:appMsg];
    NSDictionary *appResultsDict = [appMsgDict[@"results"] lastObject];
    NSString *appStoreVersion = appResultsDict[@"version"];
//    float newVersionFloat = [appStoreVersion floatValue];//新发布的版本号
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//    float currentVersionFloat = [currentVersion floatValue];//使用中的版本号
    
    
    NSString *cacheAlertVersion = [kUserDefaults stringForKey:@"appStoreVersion"];
    if ([appStoreVersion isEqualToString:cacheAlertVersion] || kNULLString(appStoreVersion)) {
        // 商店上相同版本号不再提示
        // return ;
    }
    
    [kUserDefaults setObject:appStoreVersion forKey:@"appStoreVersion"];
    
    // AppStore 版本号大于当前版本号 （降序）
    if ([appStoreVersion compare:currentVersion options:NSNumericSearch] == NSOrderedDescending)
    {
        
        
        self.appId = kAppIdOnAppStore;
        self.isShowing = YES;
        
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"发现新版本\n"
                                                                        message:content
                                                                 preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *done = [UIAlertAction actionWithTitle:@"马上更新"
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/app/id%@",self.appId]];
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            
            self.isShowing = NO;
        }];
        
        [alert addAction:done];
        
        if(canCancel){
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"暂不更新"
                                                             style:UIAlertActionStyleCancel
                                                           handler:^(UIAlertAction * action) {
                self.isShowing = NO;
                [kUserDefaults setObject:[NSDate currentDate] forKey:@"noUpdate"];
            }];
            [alert addAction:cancel];
        }
        
        
        UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
        // 更新UI要在主线程执行
        dispatch_async(dispatch_get_main_queue(), ^{
            [window.rootViewController presentViewController:alert animated:YES completion:nil];
        });
    }
}


+ (BOOL)isChecking{
    NSURL *appUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",kAppIdOnAppStore]];
    NSString *appMsg = [NSString stringWithContentsOfURL:appUrl encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *appMsgDict = [RDCheckAppVersion jsonStringToDictionary:appMsg];
    NSDictionary *appResultsDict = [appMsgDict[@"results"] lastObject];
    NSString *appStoreVersion = appResultsDict[@"version"];
    //    float newVersionFloat = [appStoreVersion floatValue];//新发布的版本号
    
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if (kNULLString(appStoreVersion) || kNULLString(currentVersion)) {
        return YES;
    }
    
    // 当前 版本号大于AppStore版本号 （降序）
    if ([currentVersion compare:appStoreVersion options:NSNumericSearch] == NSOrderedDescending)
    {
        return YES;
    }
    else{
        return NO;
    }
    
    
    
}

+ (NSDictionary *)jsonStringToDictionary:(NSString *)jsonStr
{
    if (jsonStr == nil)
    {
        return nil;
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
    if (error)
    {
        //NSLog(@"json格式string解析失败:%@",error);
        return nil;
    }
    
    return dict;
}


- (BOOL)isAlertUpdataAgain
{
    BOOL res = [[NSUserDefaults standardUserDefaults] objectForKey:@"IS_ALERT_AGAIN"];
    return res;
}

@end
