//
//  BaseViewController.m
//  Palmwms
//
//  Created by 曹云霄 on 16/8/24.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "BaseViewController.h"
#import "MBProgressHUD.h"
#import "OfflineMapsManager.h"
#import "AppDelegate.h"

/**
 *  永远不在提示
 */
NSString *const DOWNLOAD_MAP = @"NOPROMPT";

/**
 *  本次不再提示
 */
NSString *const ONCEDOWNLOAD_MAP = @"ONCENOPROMPT";

@interface BaseViewController ()<OfflineMapsManagerDelegate>

/**
 *  加载动画
 */
@property (nonatomic,strong) MBProgressHUD *hud;

/**
 *  离线地图管理
 */
@property (nonatomic,strong) OfflineMapsManager *offline;

@end

@implementation BaseViewController

#pragma mark - lazy
- (MBProgressHUD *)hud
{
    if (!_hud) {
        _hud = [MBProgressHUD showHUDAddedTo:[[self class] hudShowWindow] animated:YES];
    }
    return _hud;
}

#pragma mark - 获取显示window
+ (UIWindow *)hudShowWindow {
    UIWindow *showWindow = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    if ([windows count] >= 2) {
        showWindow = [windows objectAtIndex:1];
    }
    else {
        showWindow = [[UIApplication sharedApplication] keyWindow];
    }
    return showWindow;
}


- (OfflineMapsManager *)offline
{
    _offline = [OfflineMapsManager manager];
    _offline.delegate = self;
    return _offline;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self customAppStyle];
}

#pragma mark - 自定义风格
- (void)customAppStyle
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor =  MainColor;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self detectionUpdateVersion];
    //版本更新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectionUpdateVersion) name:UPLOADVERSION object:nil];
}


#pragma mark -下载定位城市离线地图
- (void)downLoadLocationCityMaps
{
    WS(weakSelf);
    if ([self.offline isDownloadMaps]) {
        if (SHARED_APPDELEGATE.isWIFI) {
            if (![[NSUserDefaults standardUserDefaults] boolForKey:DOWNLOAD_MAP]) {
                if (![[NSUserDefaults standardUserDefaults] boolForKey:ONCEDOWNLOAD_MAP]) {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:ONCEDOWNLOAD_MAP];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"是否下载当前城市离线地图以节省流量?" preferredStyle:UIAlertControllerStyleActionSheet];
                    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [weakSelf.offline startDownloadOfflineMaps:^(BOOL boolValue) {
                            if (!boolValue) {
                                [weakSelf SHOWPrompttext:@"启动下载失败"];
                            }
                        }];
                    }]];
                    [alertVC addAction:[UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:DOWNLOAD_MAP];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }]];
                    [self presentViewController:alertVC animated:YES completion:nil];
                }
            }
        }
    }
}


#pragma mark - 下载进度回调
- (void)offlineMapsDownloadProgress:(double)progress
{
    if (self.offline.downLoadState != 4) {
       [self ShowProgressView:progress withTitle:@"正在下载离线地图"];
    }
}

#pragma mark - 下载状态
- (void)offlineMapsDownloadSuccessOrFailure:(int)state
{
    switch (state) {
        case 1://正在下载
        {
            self.offline.downLoadState = 1;
        }
            break;
        case 2://等待下载
        {
            self.offline.downLoadState = 2;
        }
            break;
        case 3://已暂停
        {
            [self RemoveMBProgressHUDLoding];
        }
            break;
        case 4://完成
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"离线地图下载成功"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:DOWNLOAD_MAP];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
            break;
        case 5://校验失败
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"校验失败"];
        }
            break;
        case 6://网络异常
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"网络异常"];
        }
            break;
        case 7://读写异常
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"读写异常"];
        }
            break;
        case 8://wifi网络异常
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"wifi网络异常"];
        }
            break;
        case 9://离线包数据格式异常,需重新下载
        {
            [self RemoveMBProgressHUDLoding];
            [self SHOWPrompttext:@"离线包数据格式异常,需重新下载"];
        }
            break;
        case 10://离线包导入中
        {
            
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 自定义返回按钮
- (void)customBackButton:(SEL)backButtonClick
{
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithImage:LOADIMAGENAME(@"back") style:UIBarButtonItemStyleDone target:self action:backButtonClick];
    self.navigationItem.leftBarButtonItem = backButton;
}

#pragma mark -渐隐提示框回调
- (void)SHOWPrompttext:(NSString *)Text ComcpleteBlock:(void(^)())completed
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[self class] hudShowWindow] animated:YES];
    hud.label.text = Text;
    hud.contentColor = MainColor;
    hud.label.font = [UIFont systemFontOfSize:18];
    hud.animationType = MBProgressHUDAnimationZoom;
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud hideAnimated:YES afterDelay:2.0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (completed) {
            completed();
        }
    });
}

#pragma mark -显示MBProgressHUD等待视图
- (void)CreateMBProgressHUDLoding:(NSString *)text
{
    self.hud.animationType = MBProgressHUDAnimationFade;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.contentColor = MainColor;
    self.hud.label.text = text;
    self.hud.label.font = [UIFont systemFontOfSize:18];
    self.hud.removeFromSuperViewOnHide = YES;
}

#pragma mark -进度条
- (void)ShowProgressView:(double)progress withTitle:(NSString *)message
{
    self.hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    self.hud.label.text = [NSString stringWithFormat:@"%@(%.0lf/100)",message,progress*100];
    self.hud.label.font = [UIFont systemFontOfSize:18];
    self.hud.contentColor = MainColor;
    self.hud.progress = progress;
    [self.hud.button setTitle:@"取消" forState:UIControlStateNormal];
    [self.hud.button addTarget:self action:@selector(cancelDownloadMaps:) forControlEvents:UIControlEventTouchUpInside];
    self.hud.removeFromSuperViewOnHide = YES;
}

#pragma mark - 取消下载
- (void)cancelDownloadMaps:(UIButton *)sender
{
    NSLog(@"取消下载");
    [self.offline pauseDownloadOfflineMaps];
}

#pragma mark -移除MBProgressHUD等待视图
- (void)RemoveMBProgressHUDLoding
{
    [_hud hideAnimated:YES];
    _hud = nil;
}


#pragma mark -显示成功的提示框
- (void)SuccessMBProgressView:(NSString *)successString timeDelay:(NSTimeInterval)time finish:(void (^)())complete
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[self class] hudShowWindow] animated:YES];
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    hud.customView = imageView;
    hud.contentColor = MainColor;
    hud.label.font = [UIFont systemFontOfSize:18];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = successString;
    [hud hideAnimated:YES afterDelay:time];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (complete) {
            complete();
        }
    });
}

#pragma mark -显示信息的提示框
- (void)ErrorMBProgressView:(NSString *)errorString
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[self class] hudShowWindow] animated:YES];
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    hud.customView = imageView;
    hud.contentColor = MainColor;
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.font = [UIFont systemFontOfSize:18];
    hud.label.text = errorString;
    [hud hideAnimated:YES afterDelay:2.0];
}

#pragma mark -渐隐提示框
- (void)SHOWPrompttext:(NSString *)Text
{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[self class] hudShowWindow] animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = Text;
    hud.contentColor = MainColor;
    [hud hideAnimated:YES afterDelay:2.0f];
}

#pragma mark -结束MJRfresh刷新
- (void)endRefreshingForTableView:(UIScrollView *)TableView
{
    if (TableView.mj_header.isRefreshing) {
        
        [TableView.mj_header endRefreshing];
    }
    else if (TableView.mj_footer.isRefreshing)
    {
        [TableView.mj_footer endRefreshing];
    }
}

#pragma mark -获得我的storyboard对象
- (UIStoryboard *)getStoryboardWithName
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"PalmwmsMain" bundle:nil];
    return storyboard;
}

#pragma mark - 用户确认框
- (void)showSheetViewWithMessage:(NSString *)message complete:(void (^)())finish
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        finish();
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - 保存账号密码
+ (void)saveAccountAndPassWord:(NSString *)account AndPassword:(NSString *)passWord
{
    if ([SSKeychain setPassword:account forService:SERVICENAME account:SAVEACCOUNT]) {
        NSLog(@"保存账号成功");
    }
    if ([SSKeychain setPassword:passWord forService:SERVICENAME account:SAVEPASSWORD]) {
        NSLog(@"保存密码成功");
    }
}

#pragma mark - 删除账号密码
+ (void)deleteAccountAndPassWord
{
    if ([SSKeychain deletePasswordForService:SERVICENAME account:SAVEPASSWORD]) {
        NSLog(@"删除密码成功");
    }
    if ([SSKeychain deletePasswordForService:SERVICENAME account:SAVEACCOUNT]) {
        NSLog(@"删除账号成功");
    }
}

#pragma mark - 检测更新
- (void)detectionUpdateVersion
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary* content =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *version = [content valueForKey:@"CFBundleShortVersionString"];
    //获取服务端版本大小
    WS(weakSelf);
    NSString *string = [NSString stringWithFormat:@"driver/getUpgrade?apptype=ios&version=%@",version];
    NSLog(@"%@",SERVERREQUESTURL(string));
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:SERVERREQUESTURL(string) WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0] && ![returnValue[@"data"][@"version"] isEqualToString:version]) {
            NSDictionary *dict = returnValue[@"data"];
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"发现新版本%@,快去更新吧!",dict[@"version"]] preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dict[@"url"]]];
            }]];
            //是否强制更新
            if (![dict[@"forceupdate"] isEqualToString:@"1"]) {
                [alertVC addAction:[UIAlertAction actionWithTitle:@"以后再说" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [alertVC dismissViewControllerAnimated:YES completion:nil];
                }]];
            }
            [weakSelf presentViewController:alertVC animated:YES completion:nil];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf ErrorMBProgressView:@"网络不可用,请检查网络连接"];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}


#pragma mark - 获取当前时间之前或者之后的时间（之前传入负数）
- (NSString *)getTimeby:(NSInteger)day
{
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    if(day!=0){
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*day];
    }else{
        theDate = nowDate;
    }
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}


- (void)dealloc
{
    NSLog(@"释放:%@",self.title);
}

@end
