//
//  SearchViewController.m
//  Demo
//
//  Created by ls on 2019/7/25.
//  Copyright © 2019 super. All rights reserved.
//

#import "SearchViewController.h"
//#import <CYBaseKit/CYBaseKit.h>
@interface SearchViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray* deviceList;
@property (nonatomic, strong) UIActivityIndicatorView* activityIndicator;
/**
 管理类
 */
#ifdef THREESDK
@property (nonatomic,strong) CYEcgKit * manager;
#else
@property (nonatomic, strong) CYBaseKit* manager;
#endif

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 20, 20);
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.deviceList = [[NSMutableArray alloc] init];
    
    self.title = @"搜索设备";
    

    self.activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
     self.activityIndicator.hidesWhenStopped = YES;
    [self.view addSubview: self.activityIndicator];
    
    [ self.activityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self.view);
        make.center.equalTo(self.view);
        make.height.mas_equalTo(200);
        make.width.mas_equalTo(200);
    }];
    //设置小菊花颜色
     self.activityIndicator.color = [UIColor blackColor];
    [ self.activityIndicator startAnimating];
    
    
    //初始化管理类，并设置代理
    #ifdef THREESDK
    self.manager = [CYEcgKit sharedInstance];
#else
    self.manager = [CYBaseKit sharedInstance];
#endif
//    self.manager.delegate = self;
    
    __weak typeof(self) weakSelf = self;
    //开始搜索设备
    [self.manager scanForPeripherals:^(CyEcgDeviceModel * _Nonnull cyPeripheral, NSError * _Nonnull error) {
        if(error == nil)
        {
            [weakSelf.deviceList addObject:cyPeripheral];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if(weakSelf.tableView.hidden)
                {
                    weakSelf.tableView.hidden = NO;
                    [weakSelf.activityIndicator stopAnimating];
                }
                
                [weakSelf.tableView reloadData];
            });
        }
    }];
    
    self.tableView.hidden = YES;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark tableView deldegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.deviceList.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellId = @"cellId";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        
        UIView* view = [[UIView alloc] init];
        [cell addSubview:view];
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).offset(5);
            make.bottom.equalTo(cell).offset(-5);
            make.left.equalTo(cell).offset(5);
            make.right.equalTo(cell).offset(-5);
        }];
        
        view.backgroundColor = [UIColor colorWithRed:0 green:145.0/255.0f blue:234.0/255.0f alpha:1];
        view.layer.cornerRadius = 15;
        view.layer.masksToBounds = YES;
        
        
        UILabel* titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
        [titleLab setTag:10086];
        titleLab.textColor = [UIColor whiteColor];
        titleLab.textAlignment = NSTextAlignmentLeft;
        [view addSubview:titleLab];
        
        UILabel* detailLab = [[UILabel alloc] initWithFrame:CGRectZero];
        [detailLab setTag:10087];
        detailLab.textColor = [UIColor whiteColor];
        detailLab.textAlignment = NSTextAlignmentLeft;
        [view addSubview:detailLab];
        
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).offset(15);
            make.left.equalTo(detailLab);

        }];
        
        [detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLab.mas_bottom).offset(5);
            make.centerX.equalTo(cell);
        }];
    }
    
    UILabel* titleLab = [cell viewWithTag:10086];
    UILabel* detailLab = [cell viewWithTag:10087];
    
    CyEcgDeviceModel* model =self.deviceList[indexPath.row];
    
    titleLab.text = [NSString stringWithFormat:@"设备名：%@",model.peripheral.name];
    detailLab.text = [NSString stringWithFormat:@"设备号：%@",model.currentDeviceNo];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CyEcgDeviceModel* model = self.deviceList[indexPath.row];
//    [self.manager connectPeripheral:model.peripheral success:nil disConnect:nil failConnect:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"DEVICENUM" object:model];
}

/*
#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
