//
//  CultureGameViewController.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/5/6.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "CultureGameViewController.h"
#import "UIViewController+MMDrawerController.h"


@interface CultureGameViewController () <UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation CultureGameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"文创游";
    
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
     [Manager setNavi:self.navigationController.navigationBar];
    
    
#pragma - 设置导航栏左边的按钮
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(cultureGameLeftBtnIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothStopScan) name:@"downloadPause" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothStartScan) name:@"downloadResume" object:nil];
       
   //蓝牙扫描放进队列里面
    _queue = dispatch_queue_create("scanBluetooth", DISPATCH_QUEUE_CONCURRENT);
    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:_queue];
    
    _areaGameArr = [[NSMutableArray alloc]initWithCapacity:1000];
    //加载webView
    [self LoadWebView];
    
    
}

-(void)bluetoothStopScan
{
    [self.manager stopScan];
    _isScanning = NO;
}

-(void)bluetoothStartScan
{
    [_manager scanForPeripheralsWithServices:nil  options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
    _isScanning = YES;
}


- (void)LoadWebView {
    Singleton *singleton = [Singleton defaultSingleton];
    //以下是对webView的一些处理。
//    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64)];
//    [_webView setUserInteractionEnabled:YES];
//    [_webView setOpaque:NO]; //设置是否透明。
//    [_webView setScalesPageToFit:YES]; //自动缩放以适应屏幕。
    
    _webView = [Manager screenFrameWebview];
    _webView.delegate = self;
     [self.view addSubview:_webView];
    
    NSString *name = [singleton.nickName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"name = %@",name);
    NSString *str = [NSString stringWithFormat:@"%@/terminal/game?userId=%@&userName=%@&sex=%@",localRequestUrl,singleton.userid,name,singleton.sex];
    NSLog(@"str = %@",str);
    self.originStr = str;
    //加载网页
    NSURL *url = [NSURL URLWithString:str];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
   
    
//    JSContext *context = [_webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    context[@"jsopenoc"] = ^() {
//        NSLog(@"+++++++Begin Log+++++++");
//        NSArray *args = [JSContext currentArguments];
//        for (JSValue *jsVal in args) {
//            NSLog(@"%@", jsVal);
//            JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//            NSString *textJS = @"test()";//调用js的时候，如果是传字符串，要加''，
//            JSValue *str =[context evaluateScript:textJS];
//            NSString *jstr = [str toString];
//            NSLog(@"jstr = %@",jstr);
//        }
//        JSValue *this = [JSContext currentThis];
//        NSLog(@"this: %@",this);
//        NSLog(@"-------End Log-------");
//        
//    };
}


//导航栏左边按钮被点击
- (void)cultureGameLeftBtnIsClicked {
    if (![self.url isEqualToString:self.originStr]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出" message:@"确定要退出游戏么？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_areaGameArr removeAllObjects];//退出游戏后，之前存储的所有code清除
            NSURL *url = [NSURL URLWithString:self.originStr];
            [_webView loadRequest:[NSURLRequest requestWithURL:url]];
            [self.view addSubview:_webView];
            
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:ensure];
        [alert addAction:cancel];
        [self presentViewController:alert animated:NO completion:nil];
           }
    else
    {
        
        [self dismissViewControllerAnimated:NO completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToLastIndex" object:nil];
    }
    
        [self bluetoothStopScan];
        self.manager = nil;


}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"wenchuangyou url = %@",request.URL.absoluteString);
    if (![request.URL.absoluteString isEqualToString:self.originStr] ) {
        if (self.manager.state != CBCentralManagerStatePoweredOn) {
            //蓝牙没开启，不能跳转
            [FileDownloadTool alert:@"请手动开启蓝牙" view:self.view];
            return NO;
        }
    }
    
    if ([request.URL.absoluteString containsString:@"areaCode"] && [request.URL.absoluteString containsString:@"game_accept"]) {
        
          return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"game_continue"]) {
        //表示完成一个任务，继续等待下一个任务
        _canStartScan = YES;
        return NO;
    }
    if ([request.URL.absoluteString containsString:@"/terminal/game/branch/continue"]) {
        //表示赞助商支线完成，可以继续玩主线任务。
        [self bluetoothStartScan];
        _canStartScan = YES;
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"xiaodaoguan?branch_delete"]) {
        //表示跳过支线任务，直接执行主线任务
        _delBranch =  YES;
        _canStartScan = YES;
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"climbing/secondPass?"]) {
        //
        WS(ws);
        NSArray *arr = [request.URL.absoluteString componentsSeparatedByString:@"climbing/secondPass?"];
        NSString *frag = [arr objectAtIndex:1];
        NSArray *arr1 = [frag componentsSeparatedByString:@"&areaCode="];
        NSDictionary *dic = @{@"areaCode":[arr1 objectAtIndex:1],@"publicFrag":frag,@"type":@"1"};
        [_areaGameArr addObject:dic];
        NSString *postStr = [NSString stringWithFormat:@"%@/terminal/game/climbing/game_plot?%@",localRequestUrl,frag];
        [ws.webView stopLoading];
        NSURL *url = [NSURL URLWithString:postStr];
        [ws.webView loadRequest:[NSURLRequest requestWithURL:url]];
     //   [ws.view addSubview:ws.webView];
         _canStartScan = YES;
    }
    
    //赞助商支线。点击二维码扫描后，页面不跳转
    if ([request.URL.absoluteString containsString:@"scanBarcode?scanningId="] && [request.URL.absoluteString containsString:@"scanningAlt="]) {
        NSArray *rootArr = [request.URL.absoluteString componentsSeparatedByString:@"scanningId="];
        
        NSArray *secondArr = [[rootArr objectAtIndex:1] componentsSeparatedByString:@"scanningAlt="];
        self.scanningId = [secondArr objectAtIndex:0];
        self.scanningAlt = [secondArr objectAtIndex:1];
        NSLog(@"id = %@, alt = %@",self.scanningId,self.scanningAlt);
        //跳到扫描二维码页面
        QRCodeScanVC *codeVC = [[QRCodeScanVC alloc] init];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:codeVC];
        codeVC.delegate = self;
        codeVC.fromWhat = @"game";
        [self presentViewController:navc animated:YES completion:nil];
        
        return NO;
    }
    if ([request.URL.absoluteString containsString:@"game_start?"] && [request.URL.absoluteString containsString:@"&areaCode="]) {
       //搜索到蓝牙，加载的小游戏页面
        return YES;
    }
    
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
   
    //登高线和亲子线的，接受任务的逻辑一样，都要调用js获取code，并且，路径都包含game_accept
    if ([webView.request.URL.absoluteString containsString:@"game_accept"]) {
         NSLog(@"url = %@",webView.request.URL.absoluteString);
        JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        NSString *textJS = @"getTask('ios')";//调用js的时候，如果是传字符串，要加''，
        JSValue *str =[context evaluateScript:textJS];
        //2016-10-25，js返回的字符串，直接拼接在游戏开始加载的url后面
        NSString *jstr = [str toString];
        NSLog(@"jstr = %@",jstr);
        
        //1.先拿到code，存在数组里面，用字典存储一组信息，游戏code，2.在蓝牙搜索的事件里一直比对存的数组里面是否有有效code
      //  NSArray *accetArr = [jstr componentsSeparatedByString:@"game_start?"];
   //     NSString *acceptFragment = [accetArr objectAtIndex:1];//用于开始游戏的主参数，回传给服务器的，
        
        //先拿到主线code
        NSArray *firstA = [jstr componentsSeparatedByString:@"&areaCode="];
        NSArray *secondA = [[firstA objectAtIndex:1] componentsSeparatedByString:@"&areaBranchCodes="];
        //主线code
        NSString *mainCode = [secondA objectAtIndex:0];
        
        NSDictionary *codeGame = [[NSDictionary alloc]initWithObjectsAndKeys:mainCode,@"areaCode",jstr,@"publicFrag",@"1",@"type", nil];//存储主线的code和game的url
        [_areaGameArr addObject:codeGame];//拿到的主线景点code，暂时存储起来
        
        //找支线
        if (![[secondA objectAtIndex:1] isEqualToString:@""]) {
            NSArray *branchA = [[secondA objectAtIndex:1] componentsSeparatedByString:@","];
            //支线任务全部添加进去
            for (NSString *codeStr in branchA) {
                NSString *branchStr = [jstr stringByReplacingOccurrencesOfString:@"?" withString:@"/branch?"];
                NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:codeStr,@"areaCode",branchStr,@"publicFrag",@"2",@"type", nil];
                [_areaGameArr addObject:dic];
            }

        }
        NSLog(@"areaGameArr = %@",self.areaGameArr);
        //接受任务了才开始扫描
        _canStartScan = YES;
        [self bluetoothStartScan];
        
    }else
    {
        [self bluetoothStopScan];
        _canStartScan = NO;
    }
    
    //赞助商的时候，把参数截取出来，调用js
    if ([webView.request.URL.absoluteString containsString:@"scanBarcode?scanningId="] && [webView.request.URL.absoluteString containsString:@"scanningAlt="]) {
        
    }
    
    
    self.url = webView.request.URL.absoluteString;

}


#pragma mark --QRCodeDelegate
-(void)passValueToCultureGame:(NSString *)gameCode{
    
    JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *parameterStr = [NSString stringWithFormat:@"appBackBarcode('%@','%@','%@');",gameCode,self.scanningId,self.scanningAlt];
    JSValue *str =[context evaluateScript:parameterStr];
    NSLog(@"js = %@",str);
}



#pragma mark - CBCentralManager Delegate
//发现蓝牙设备，这个函数是不是原子型的，搜索到一个蓝牙的处理未完成的时候，其他蓝牙被搜索到后是不是会进入
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"perial.name = %@",peripheral.name);
    
    WS(ws);
    if (_canStartScan) {
        NSString *postStr;
        //这里面做比对动作
        for (NSDictionary *dic in ws.areaGameArr) {
            BOOL can =[self checkTheBluetoothValid:peripheral withAttCode:dic];
            if (can == YES) {
                _canStartScan = NO;
                if ([[dic objectForKey:@"type"] isEqualToString:@"1"]) {
                    //主线任务加载路径
                    postStr = [NSString stringWithFormat:@"%@%@",localRequestUrl,[dic objectForKey:@"publicFrag"]];
                        NSArray *arr = [postStr componentsSeparatedByString:@"&userName="];
                        postStr = [arr objectAtIndex:0];
                    
                    
                }else{
                    //支线任务，孝道馆的地方，需要特别处理
                    postStr = [NSString stringWithFormat:@"%@%@",localRequestUrl,[dic objectForKey:@"publicFrag"]];
                    NSArray *arr = [postStr componentsSeparatedByString:@"&userName="];
                    postStr = [arr objectAtIndex:0];
                }
                //移除code
                [self.areaGameArr removeObject:dic];
                 NSLog(@"areaGameArrRemove = %@",self.areaGameArr);
                //蓝牙暂时停止搜索
                [self bluetoothStopScan];
                NSURL *url = [NSURL URLWithString:postStr];
                [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
               // [self.view addSubview:self.webView];
                
                break;
            }
            
        }
        
    }
    
}


//检索json文件,看是否有 有效蓝牙
-(BOOL)checkTheBluetoothValid:(CBPeripheral *)peripheral withAttCode:(NSDictionary *)area
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"bluetooth1" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    NSError *error;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    NSArray *allObjectArr = [jsonDic objectForKey:@"bluetoothAddress"];
    for (NSDictionary *dic in allObjectArr) {
        if ([[dic objectForKey:@"ATTCODE"] isEqualToString:[area objectForKey:@"areaCode"]]) {//搜索到code，再比对code景点里面对应的蓝牙组，看是否和当前搜索到的蓝牙匹配
            NSArray *toothArr = [dic objectForKey:@"id"];//查询到蓝牙数组
            for (NSDictionary *toothDic in toothArr) {
                if ([[toothDic objectForKey:@"NAME"] isEqualToString:peripheral.name]) {
                    //在当前搜索的code里面，找到对应的蓝牙,证明找到对应蓝牙code、上传信息
                    NSLog(@"heiheiheiheie = %@",[dic objectForKey:@"ATTCODE"]);
                    NSLog(@"perial.name = %@",peripheral.name);
                    return YES;
                }
            }
            
        }
    }
    
    return NO;
}



-(void)centralManagerDidUpdateState:(CBCentralManager
                                     *)central
{
    
    switch(central.state) {
            
        case CBCentralManagerStatePoweredOff:
            _isScanning = NO;
            NSLog(@"CBCentralManagerStatePoweredOff");
            
            break;
            
        case CBCentralManagerStatePoweredOn:
            
            NSLog(@"CBCentralManagerStatePoweredOn");
            if (_isScanning == NO) {
                 [_manager scanForPeripheralsWithServices:nil  options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
            }
            
            break;
            
        case CBCentralManagerStateResetting:
            
            NSLog(@"CBCentralManagerStateResetting");
            
            break;
            
        case CBCentralManagerStateUnauthorized:
            
            NSLog(@"CBCentralManagerStateUnauthorized");
            
            break;
            
        case CBCentralManagerStateUnknown:
            
            NSLog(@"CBCentralManagerStateUnknown");
            _isScanning = NO;
            break;
            
        case CBCentralManagerStateUnsupported:
            _isScanning = NO;
            NSLog(@"CBCentralManagerStateUnsupported");
            
            break;
            
        default:
            
            break;
    }
    
}

#pragma mark - KVC
//使用KVC赋值, 没有找到对应的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    //字典中是id，属性中是ID
    //    if ([key isEqualToString:@"id"]) {
    //        self.ID = value;
    //    }
}

//使用KVC取值, 没有找到对应的key
- (id)valueForUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    return nil;
}


-(void)dealloc
{
    [_manager stopScan];
    _queue = nil;
    _manager = nil;
    _areaGameArr = nil;
    _url =nil;
    _webView = nil;
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"downloadPause" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"downloadResume" object:nil];
    
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
