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

#import "BaseViewController.h"
#import "MBProgressHUD.h"

@interface BaseViewController ()

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

@end

@implementation BaseViewController

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

- (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)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.view.window 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
{
    self.hud.mode = MBProgressHUDModeAnnularDeterminate;
    self.hud.label.text = @"上传中...";
    self.hud.label.font = [UIFont systemFontOfSize:18];
    self.hud.contentColor = MainColor;
    self.hud.progress = progress;
    self.hud.removeFromSuperViewOnHide = YES;
}

#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.view 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.view.window 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:1.0];
}

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

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = Text;
    hud.contentColor = MainColor;
//    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    [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]) {
            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;
}


@end
