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

#import "BaseViewController.h"
#import "LoginViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "PerfectInformationViewController.h"
#import "ResellerViewController.h"
#import "LocationViewController.h"

@interface BaseViewController ()<UIPrintInteractionControllerDelegate,UIWebViewDelegate,WKNavigationDelegate>


@property (nonatomic,strong) WKWebView *webView;

/**
 *  提示框
 */

@property (nonatomic,strong) UIPrintInteractionController *printControl;


@end

@implementation BaseViewController



- (WKWebView *)webView
{
    if (_webView == nil) {
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
    }
    //检测登陆超时通知
    [Notification addObserver:self selector:@selector(logintimeoutNotification:) name:LOGINTIMEOUT object:nil];
}

#pragma mark - 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark -完善导购个人信息
- (void)perfectGuideInformation
{
    PerfectInformationViewController *perfectInformation = [PerfectInformationViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:perfectInformation];
    nav.preferredContentSize = CGSizeMake(ScreenHeight-300, ScreenHeight-300);
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = nav.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = nav.view;
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark -完善导购经销商信息
- (void)perfectResellerInformation:(void(^)(ResellerViewController *resellerVc))completed
{
    ResellerViewController *resellerVc = [ResellerViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    resellerVc.preferredContentSize = CGSizeMake(400, 400);
    resellerVc.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = resellerVc.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = resellerVc.view;
    if (completed) {
        completed(resellerVc);
    }
    [self presentViewController:resellerVc animated:YES completion:nil];
}

#pragma mark -完善门店位置信息
- (void)perfectStoreLocationInformation
{
    LocationViewController *resellerVc = [LocationViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    resellerVc.modalPresentationStyle = UIModalPresentationFormSheet;
    resellerVc.preferredContentSize = CGSizeMake(400, 400);
    UIPopoverPresentationController *pop = resellerVc.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = resellerVc.view;
    [self presentViewController:resellerVc animated:YES completion:nil];
}


#pragma mark -登陆超时回调
- (void)logintimeoutNotification:(NSNotification *)not
{
    WS(weakSelf);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"登陆超时，请重新登陆" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        [Shoppersmanager manager].currentCustomer = NO;
        [Customermanager manager].model = nil;
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"OppleMain" bundle:nil];
        LoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"Login"];
        [UserDefault removeObjectForKey:USERNAME];
        [UserDefault removeObjectForKey:PASSWORD];
        [weakSelf restoreRootViewController:loginVC];
    }]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf presentViewController:alert animated:YES completion:nil];
    });
}

#pragma mark -切换rootViewcontroller
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = SHARED_APPDELEGATE.window;
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionFlipFromBottom
                    animations:animation
                    completion:nil];
}

#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 - 判断相机权限
+ (BOOL)determineCameraPermissions
{
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        ShowAlertView(@"提示", @"请在iPad的“设置-隐私-相机”选项中，允许欧立方访问你的相机", @[@"我知道了"], UIAlertControllerStyleAlert, nil);
        return NO;

    }else {
        return YES;
    }
}

#pragma mark - 判断相册的权限
+ (BOOL)determinePhotosPermissions
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        ShowAlertView(@"提示", @"请在iPad的“设置-隐私-相册”选项中，允许欧立方访问你的相册", @[@"我知道了"], UIAlertControllerStyleAlert, nil);
        return NO;
    }
    return YES;
}

#pragma mark -  考核题型转义
+ (NSString *)returnTopicTypeTitle:(NSString *)typeCode
{
    if ([typeCode isEqualToString:STUDYTOPICTYPE_SINGLE]) {
        return @"单选";
    }
    if ([typeCode isEqualToString:STUDYTOPICTYPE_MULTIPLE]) {
        return @"多选";
    }
    if ([typeCode isEqualToString:STUDYTOPICTYPE_TRUEORFALSE]) {
        return @"判断";
    }
    if ([typeCode isEqualToString:PASSLEVELTOPICTYPE_GAPFILLING]) {
        return @"填空";
    }
    if ([typeCode isEqualToString:PASSLEVELTOPICTYPE_SHORTANSWER]) {
        return @"简答";
    }
    return nil;
}

#pragma mark -查询兑奖单state对应文字
+ (id)returnPrizeBillStateTitleColor:(NSString *)stateCode
{
    NSDictionary *dict;
    if ([stateCode isEqualToString:@"requested"]) {
        dict = @{@"title":@"已申请",@"color":RGB(127, 192, 62, 1)};
    }else if ([stateCode isEqualToString:@"shipped"]) {
        dict = @{@"title":@"已发货",@"color":RGB(245, 185, 74, 1)};
    }else if ([stateCode isEqualToString:@"done"]) {
        dict = @{@"title":@"已完成",@"color":kMainBlueColor};
    }
    return dict;
}

#pragma mark - 设置提现状态
+ (NSDictionary *)setupLabelColor:(NSString *)text
{
    UIColor *color = kMainBlueColor;
    NSString *string;
    if ([text isEqualToString:@"submit"]) {
        color = RGB(128, 189, 51, 1);
        string = @"已提交";
    }else if ([text isEqualToString:@"paying"]) {
        color = kMainBlueColor;
        string = @"支付中";
    }else if ([text isEqualToString:@"accomplished"]) {
        color = kMainBlueColor;
        string = @"已完成";
    }else if ([text isEqualToString:@"failure"]) {
        color = [UIColor redColor];
        string = @"提现失败";
    }else if ([text isEqualToString:@"reject"]) {
        color = [UIColor redColor];
        string = @"驳回";
    }else if ([text isEqualToString:@"commission"]) {
        color = [UIColor blackColor];
        string = @"【产品返利】";
    }else if ([text isEqualToString:@"redPackage"]) {
        color = [UIColor blackColor];
        string = @"【欧普奖励】";
    }
    text = [[self class] isBlankString:text]?@"未知状态":text;
    return @{@"text":[[self class] isBlankString:string]?text:string,@"color":color};
}

#pragma mark - 区分提现还是返佣
+ (NSString *)separatePaymentsAndWithfrawal:(NSNumber *)number withType:(NSString *)type
{
    CGFloat money = [number floatValue];
    NSString *moneyType = [[self class] setupLabelColor:type][@"text"];
    return [NSString stringWithFormat:@"%@%@",moneyType,(money>0)?@"返佣":@"提现"];
}

#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 HH:mm:ss"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}

#pragma mark 调用airPrint无线打印机
- (void)callAirprintWithdata:(NSString *)PDFpath successBlock:(void(^)())success errorBlock:(void(^)())failed
{
    NSData *mypdfdata = [NSData dataWithContentsOfFile:PDFpath];
    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    if  (pic && [UIPrintInteractionController canPrintData: mypdfdata] ) {
        pic.delegate = self;
        UIPrintInfo *printInfo = [UIPrintInfo printInfo];
        printInfo.outputType = UIPrintInfoOutputGeneral;
        printInfo.jobName = @"订单明细";
        printInfo.duplex = UIPrintInfoDuplexLongEdge;
        pic.printInfo = printInfo;
        pic.showsPageRange = YES;
        pic.printingItem = mypdfdata;
        void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
            if (completed)
            {
                // 执行成功后的处理
                success();
            }
            else if (!completed && error)
            {
                // 执行失败后的处理
                failed();
            }
        };
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            [pic presentAnimated:YES completionHandler:completionHandler];
        }
    }
}



#pragma mark -传入订单状态，返回当前状态图片
+ (UIImage *)returnOrderStateImageWithStateCode:(NSInteger)ordercode
{
    const NSArray *imageArray = [NSArray arrayWithObjects:@"已撤销",@"已完成",@"已退货", nil];
    switch (ordercode) {
        case 4://退货
        {
            return TCImage([imageArray objectAtIndex_opple:2]);
        }
            break;
        case 5://作废
        {
            return TCImage([imageArray objectAtIndex_opple:0]);
        }
            break;
        case 6://完成
        {
            return TCImage([imageArray objectAtIndex_opple:1]);
        }
            break;
            
        default:
            break;
    }
    return nil;
}


#pragma mark -传入订单状态，返回订单文本信息,字体颜色
+ (id)returnOrderStateTitleWithStateCode:(NSInteger)ordercode withPoint:(CGPoint)point withCode:(NSInteger)code
{
    
    switch (ordercode) {
        case 001://未付款
        {
            if (code) {
                return RGB(241, 81, 83,1);
            }
            return @"待支付";
        }
            break;
        case 002://已付款
        {
            
            if (code) {
                return RGB(126, 191, 53,1);
            }
            return @"已支付";
        }
            break;
        case 003://已发货
        {
            
            if (code) {
                return RGB(240, 180, 51,1);
            }
            return @"已发货";
        }
            break;
        case 004://已退货
        {
            
            if (code) {
                return RGB(153, 153, 153,1);
            }
            return @"已退货";
        }
            break;
        case 005://已作废
        {
            
            if (code) {
                return RGB(153, 153, 153,1);
            }
            return @"已撤销";
        }
            break;
        case 006://已完成
        {
            
            if (code) {
                return RGB(89, 172, 220,1);
            }
            return @"已完成";
        }
            break;
            
        default:
            break;
    }
    return nil;
}


#pragma mark -查询购物车数量
- (void)queryShoppingCarNumber
{
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(QUERYSHOPPINGBAGNUMBER),[Customermanager manager].model.consumer.fid];
    [HTTP networkWithDictionaryRequestWithURL:urlString  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            [Notification postNotificationName:REFRESHSHOPPINGCAR object:RESPONSE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -通过经销商ID获取省市区
- (void)getStoreAddress:(void(^)())completed
{
    [HTTP networkRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(STOREADDRESS),[Shoppersmanager manager].shoppers.employee.currentDepart.fid] withRequestType:POST withParameter:nil withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            ToStoreAddress *address = [[ToStoreAddress alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            [Shoppersmanager manager].storeAddress = address;
            if (completed) {
                completed();
            }
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -直辖市处理
+ (NSString *)isMunicipality:(NSString *)province withCity:(NSString *)city withCountry:(NSString *)country withDetailAddress:(NSString *)address
{
    NSString *string = nil;
    if (![BaseViewController isBlankString:province] && ![BaseViewController isBlankString:city] && ![BaseViewController isBlankString:country]) {
        if (![province isEqualToString:city]) {
            if (![BaseViewController isBlankString:address]) {
                string = [NSString stringWithFormat:@"%@%@%@%@",province,city,country,address];
            }else {
                string = [NSString stringWithFormat:@"%@%@%@",province,city,country];
            }
        }else
        {
            if (![BaseViewController isBlankString:address]) {
                string = [NSString stringWithFormat:@"%@%@%@",city,country,address];
            }else {
                string = [NSString stringWithFormat:@"%@%@",city,country];
            }
        }
    }else
    {
        string = [NSString stringWithFormat:@"%@",address];
    }
    return string;
}

#pragma mark - 查询购物车商品
- (void)queryShoppingCarGoods
{
    [Notification postNotificationName:SHOPPINGCARGOODS object:nil];
}

#pragma mark - 获取版本号
- (NSString*)getAppVersion
{
    NSString *ver = [[[NSBundle mainBundle] infoDictionary]
                     objectForKey:@"CFBundleShortVersionString"];
    return [NSString stringWithFormat:@"Version %@",ver];
}

#pragma mark - 通过面额获取相应的图片
+ (UIImage *)getCorrespondingPictures:(NSInteger)total
{
    UIImage *image = nil;
    switch (total) {
        case 50:
        {
            image = TCImage(@"fifty");
        }
            break;
        case 100:
        {
            image = TCImage(@"onehundred");
        }
            break;
        case 200:
        {
            image = TCImage(@"twohundred");
        }
            break;
            
        default:
            break;
    }
    return image;
}

+ (BOOL)isBlankString:(NSString *)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}


/**
 闯关结果状态
 
 @param passResult 闯关结果
 
 @return 状态图片
 */
+ (UIImage *)emigratedState:(NSString *)passResult
{
    if ([passResult isEqualToString:@"0"]) {
        return TCImage(@"failure");
    }else if ([passResult isEqualToString:@"1"]) {
        return TCImage(@"success");
    }else if ([passResult isEqualToString:@"2"]) {
        return TCImage(@"submited");
    }
    return nil;
}


#pragma mark - 保存账号密码
+ (void)saveAccountAndPassWord:(NSString *)account AndPassword:(NSString *)passWord
{
    [UserDefault setValue:account forKey:SAVEACCOUNT];
    [UserDefault setValue:passWord forKey:SAVEPASSWORD];
    [UserDefault synchronize];
}

#pragma mark - 删除账号密码
+ (void)deleteAccountAndPassWord
{
    [UserDefault removeObjectForKey:SAVEACCOUNT];
    [UserDefault removeObjectForKey:SAVEPASSWORD];
}


#pragma mark -比较两个NSDate的大小
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        return 1;
    }
    else if (result == NSOrderedAscending){
        return -1;
    }
    return 0;
}

/**
 转换秒钟

 @param totalSeconds 秒数

 */
- (NSString *)timeFormatted:(NSInteger)totalSeconds
{
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;
    if (!hours && !minutes && seconds) {
        return [NSString stringWithFormat:@"%02ld秒", seconds];
    }else if (!hours && minutes){
        return [NSString stringWithFormat:@"%02ld分:%02ld秒",minutes,seconds];
    }else if (hours && minutes) {
        return [NSString stringWithFormat:@"%02ld时:%02ld分:%02ld秒",hours, minutes, seconds];
    }
    return nil;
}


/**
 格式化时间字符串

 @param dateString 时间字符串
 @return 中文标示
 */
+ (NSString *)formateDate:(NSString *)dateString
{
    @try {
        // ------实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//这里的格式必须和DateString格式一致
        NSDate * nowDate = [NSDate date];
        // ------将需要转换的时间转换成 NSDate 对象
        NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
        // ------取当前时间和转换时间两个日期对象的时间间隔
        NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
        // ------再然后，把间隔的秒数折算成天数和小时数：
        
        NSString *dateStr = [[NSString alloc] init];
        
        if (time<=60) {  //1分钟以内的
            
            dateStr = @"刚刚";
            
        }else if(time<=60*60){  //一个小时以内的
            
            int mins = time/60;
            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
            
        }else if(time<=60*60*24){  //在两天内的
            
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
            NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([need_yMd isEqualToString:now_yMd]) {
                //在同一天
                dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                //昨天
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        }else {
            
            [dateFormatter setDateFormat:@"yyyy"];
            NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
            NSString *nowYear = [dateFormatter stringFromDate:nowDate];
            
            if ([yearStr isEqualToString:nowYear]) {
                //在同一年
                [dateFormatter setDateFormat:@"MM-dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }else{
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }
        }
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
}


#pragma mark -汉字转码
- (NSString *)returnUrlString:(NSString *)ChineseString
{
    NSString* encodedString = [ChineseString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return encodedString;
}

/**
 UIPopoverPresentationController弹出框
 
 @param viewController 需要弹出的控制器
 @param size size
 @param barbuttonitem 箭头按钮
 */
- (void)popoverPresentationController:(UIViewController *)viewController withPreferredContentSize:(CGSize)size  withBarButtonItem:(UIBarButtonItem *)barbuttonitem
{
    viewController.preferredContentSize = size;
    viewController.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = viewController.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = viewController.view;
    pop.barButtonItem = barbuttonitem;
    [self presentViewController:viewController animated:YES completion:nil];
}




- (void)dealloc
{
    NSLog(@"释放%@控制器",self);
}





@end
