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

#import "BaseViewController.h"

@interface BaseViewController ()<UIPrintInteractionControllerDelegate,UIWebViewDelegate>


@property (nonatomic,strong) UIWebView *webView;

/**
 *  提示框
 */
@property (nonatomic,strong) PromptinformationView *promptView;

@end

@implementation BaseViewController


/**
 *  创建MBProgressHUD对象
 *
 *  @return MBProgressHUD
 */
- (MBProgressHUD *)TCHud
{
    if (_TCHud == nil) {
        
        _TCHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    return _TCHud;
}


/**
 *  初始化提示框
 *
 *  @return PromptinformationView
 */
- (PromptinformationView *)promptView
{
    if (_promptView == nil) {
        
        _promptView = [[[NSBundle mainBundle] loadNibNamed:@"PromptinformationView" owner:self options:nil] firstObject];
    }
    return _promptView;
}




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


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -渐隐提示框回调
- (void)SHOWPrompttext:(NSString *)Text ComcpleteBlock:(void(^)())completed
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    hud.labelText = Text;
    hud.animationType = MBProgressHUDAnimationZoom;
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2.0f];
    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
{
    self.TCHud.animationType = MBProgressHUDAnimationZoom;
    self.TCHud.mode = MBProgressHUDModeIndeterminate;
    self.TCHud.color = [UIColor clearColor];
    self.TCHud.activityIndicatorColor = kMainBlueColor;
    self.TCHud.removeFromSuperViewOnHide = YES;
}



#pragma mark -进度条
- (void)ShowProgressView:(double)progress
{
    self.TCHud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    self.TCHud.labelText = @"上传中....";
    self.TCHud.labelFont = [UIFont systemFontOfSize:12];
    self.TCHud.progress = progress;
    self.TCHud.removeFromSuperViewOnHide = YES;
}




#pragma mark -移除MBProgressHUD等待视图
- (void)RemoveMBProgressHUDLoding;
{
//    [self.TCHud hide:YES afterDelay:0.5];
    [_TCHud hide:YES];
    _TCHud = nil;
}


#pragma mark -显示成功的提示框
- (void)SuccessMBProgressView:(NSString *)successString
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    // Set the custom view mode to show any view.
    hud.mode = MBProgressHUDModeCustomView;
    // Set an image view with a checkmark.
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    // Looks a bit nicer if we make it square.
//    hud.square = YES;
    // Optional label text.
    hud.color = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    hud.labelFont = [UIFont systemFontOfSize:12];
    hud.labelText = successString;
    [hud hide:YES afterDelay:1];
}

#pragma mark -显示错误的提示框
- (void)ErrorMBProgressView:(NSString *)errorString
{
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
//    // Set the custom view mode to show any view.
//    hud.mode = MBProgressHUDModeText;
//    // Set an image view with a checkmark.
////    UIImage *image = [[UIImage imageNamed:@"Error"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
////    hud.customView = [[UIImageView alloc] initWithImage:image];
//    // Looks a bit nicer if we make it square.
////    hud.square = YES;
//    // Optional label text.
////    hud.activityIndicatorColor = kMainBlueColor;
//    hud.labelFont = [UIFont systemFontOfSize:12];
//    hud.labelText = errorString;
//    [hud hide:YES afterDelay:1];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = errorString;
    hud.margin = 10.f;
    hud.color = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    hud.minSize = CGSizeMake(250, 70);
    hud.animationType = MBProgressHUDAnimationZoom;
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1.0f];
}



#pragma mark -渐隐提示框
- (void)SHOWPrompttext:(NSString *)Text
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = Text;
    hud.margin = 10.f;
    hud.color = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    hud.minSize = CGSizeMake(200, 50);
    hud.animationType = MBProgressHUDAnimationZoom;
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1.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:@"StoryboardwithCYX" bundle:nil];
    return storyboard;
}

#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 调用airPrint无线打印机
- (void)callAirprintWithURL:(NSURL *)datasurl SuccessBlock:(void (^)())success ErrorBlock:(void (^)())failed
{
//    NSData *mypdfdata = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"The Swift Programming Language 中文版 - v1.2" ofType:@"pdf"]];
    
    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    
        pic.delegate = self;
        [self.webView loadRequest:[NSURLRequest requestWithURL:datasurl]];//网页
         self.webView.delegate = self;
        pic.printFormatter = [self.webView viewPrintFormatter];//布局打印视图绘制的内容。
        UIPrintInfo *printInfo = [UIPrintInfo printInfo];
        printInfo.outputType = UIPrintInfoOutputGeneral;
        printInfo.jobName = @"订单明细";
        printInfo.duplex = UIPrintInfoDuplexShortEdge;
        pic.printInfo = printInfo;
        pic.showsPageRange = YES;
    
    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];
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self CreateMBProgressHUDLoding];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self RemoveMBProgressHUDLoding];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    [self ErrorMBProgressView:@"打印失败"];
}


#pragma mark -提示文本,图片
- (void)PromptinformationViewWithimage:(UIImage *)image withTitle:(NSString *)title withpoint:(CGPoint)point
{
    self.promptView.tipsImage.image = image;
    self.promptView.tipsTitle.text = title;
    self.promptView.frame = CGRectMake(point.x, point.y, 250, 170);
    [self.view addSubview:self.promptView];
}





#pragma mark -删除提示文本、图片
- (void)RemovePromptinformationView
{
    [self.promptView removeFromSuperview];
    self.promptView = nil;
}




#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 kTCColor(241, 81, 83);
            }
            return @"未付款";
        }
            break;
        case 002://已付款
        {

            if (code) {
                return kTCColor(126, 191, 53);
            }
            return @"已付款";
        }
            break;
        case 003://已发货
        {

            if (code) {
                return kTCColor(240, 180, 51);
            }
            return @"已发货";
        }
            break;
        case 004://已退货
        {

            if (code) {
                return kTCColor(153, 153, 153);
            }
            return @"已退货";
        }
            break;
        case 005://已作废
        {

            if (code) {
                return kTCColor(153, 153, 153);
            }
            return @"已撤销";
        }
            break;
        case 006://已完成
        {

            if (code) {
                return kTCColor(89, 172, 220);
            }
            return @"已完成";
        }
            break;
            
        default:
            break;
    }
    return nil;
}

#pragma mark -查询购物车数量
- (void)QueryShoppingCarNumber
{
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@%@",ServerAddress,@"/shopcart/get/",[Customermanager manager].customerID] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            NSLog(@"更新购物车数量成功");
            [[NSNotificationCenter defaultCenter]postNotificationName:REFRESHSHOPPINGCAR object:returnValue[@"data"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        NSLog(@"更新购物车数量失败");
    }];
}



#pragma mark -系统提示框
- (void)promptCustomerWithString:(NSString *)message
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}








@end
