//
//  EcgViewController.m
//  Demo
//
//  Created by super on 2019/6/5.
//  Copyright © 2019 super. All rights reserved.
//

#import "EcgViewController.h"
#import "OtherViewController.h"
#import "CustomCell.h"
#import "SearchViewController.h"
#import "CYPlayBackViewController.h"
@interface EcgViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CYEcgDelegate>
@property (weak, nonatomic) IBOutlet UIView *ecgView;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
@property (weak, nonatomic) IBOutlet UIButton *connectBtn;
@property (weak, nonatomic) IBOutlet UIButton *otherBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
/**
 管理类
 */
#ifdef THREESDK
@property (nonatomic,strong) CYEcgKit * manager;
#else
@property (nonatomic,strong) CYBaseKit * manager;
#endif
/**
 心电数据绘制视图
 */
@property (nonatomic, strong) CYHeartLive *refreshMoniterView;

@property (nonatomic, assign) BOOL isRecording;//记录中
@property (nonatomic, assign) BOOL isConnected;//设备连接
@property (nonatomic, strong) NSString* deviceStatus;//设备连接状态
@property (nonatomic, strong) NSString* deviceNum;//设备号
@property(nonatomic,strong) NSArray * arrCal;

/**
 心电运算结果
 */
@property (nonatomic,strong) CYResult * result;

@end

@implementation EcgViewController

- (void)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];

    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    [super viewDidLoad];
    self.title = @"主页";
    
    //设备信息
    self.deviceStatus = @"未连接";
    self.deviceNum = @"";
    
    self.recordBtn.layer.cornerRadius = 15;
    self.connectBtn.layer.cornerRadius = 15;
    self.otherBtn.layer.cornerRadius = 15;
    
    self.isRecording = NO;
    self.isConnected = NO;
    self.view.backgroundColor =[UIColor whiteColor];
    
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    
    //初始化管理类，并设置代理
    
#ifdef THREESDK
    self.manager = [CYEcgKit sharedInstance];
#else
    self.manager = [CYBaseKit sharedInstance];
#endif
    self.manager.delegate = self;
    
    self.ecgView.layer.borderWidth = 1;
    self.ecgView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.ecgView.layer.cornerRadius = 10;
    self.ecgView.layer.masksToBounds = YES;
    
    //使用心电图实时显示ui框架
    [self.ecgView addSubview:self.refreshMoniterView];
    [self.refreshMoniterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.ecgView).offset(10);
        make.bottom.equalTo(self.ecgView).offset(-10);
        make.left.equalTo(self.ecgView).offset(10);
        make.right.equalTo(self.ecgView).offset(-10);
    }];
    
    //需要时刷新计算结果
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(Timered:) userInfo:nil repeats:YES];
    [timer fire];
     
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fiterDeviceNum:) name:@"DEVICENUM" object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
   if(![[[NSUserDefaults standardUserDefaults] objectForKey:@"IDLETIMER"] isEqualToString:@"off"])
    {
        [UIApplication sharedApplication].idleTimerDisabled = YES;
    }
    else
    {
        [UIApplication sharedApplication].idleTimerDisabled = NO;
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
}

-(void)fiterDeviceNum:(NSNotification*)notification
{
    __weak typeof(self) weakself = self;
    CyEcgDeviceModel * model  = notification.object;

    
    [self.manager connectPeripheral:model.peripheral success:^{
        NSLog(@"连接成功");
        weakself.deviceNum = model.currentDeviceNo;

        weakself.isConnected = YES;
        [weakself.connectBtn setTitle:@"断开设备" forState:UIControlStateNormal];
        weakself.deviceStatus = @"连接成功";
    } disConnect:^{
        weakself.isConnected = NO;
        [weakself.connectBtn setTitle:@"连接设备" forState:UIControlStateNormal];
        weakself.deviceStatus = @"连接断开";
        NSLog(@"断开连接");
    } failConnect:^{
        weakself.isConnected = NO;
        [weakself.connectBtn setTitle:@"连接设备" forState:UIControlStateNormal];
        weakself.deviceStatus = @"连接失败";
        NSLog(@"连接失败");
    }];
}

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

//实时心电图控件
- (CYHeartLive *)refreshMoniterView{
    if (!_refreshMoniterView) {
        _refreshMoniterView = [[CYHeartLive alloc]initWithFrame:CGRectMake(0, 0, self.ecgView.frame.size.width, self.ecgView.frame.size.height)];
    }
    return _refreshMoniterView;
}

//点击开始记录按钮
- (IBAction)recordAction:(id)sender {
    
    if(!self.isConnected)
    {
        [XDTopHud showWarning:@"请先连接设备"];
        return;
    }
    
    self.isRecording = !self.isRecording;
    //记录数据
    if (self.isRecording) {
        //开始记录 -- 指定文件名 如果不指定 则使用默认文件名
        [self.manager startRecordWithFileName:nil];
        [self.recordBtn setTitle:@"结束记录" forState:UIControlStateNormal];
    }
    else{
        //结束记录
        [self.manager endRedcord];
        [self.recordBtn setTitle:@"开始记录" forState:UIControlStateNormal];
        CYPlayBackViewController* controller = [[CYPlayBackViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
}
- (IBAction)connectAction:(id)sender {
    
    if(!self.isConnected)
    {
        SearchViewController* controller = [[SearchViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else
    {
        //没开始记录，点击断开连接
        if(self.isRecording == NO)
        {
            [self.manager cancelPeripheral];
            return;
        }
        //已经开始记录 断开连接并且跳转界面
        self.isRecording = NO;
        [self.recordBtn setTitle:@"开始记录" forState:UIControlStateNormal];
        
        [self.manager endRedcord];
        [self.manager cancelPeripheral];

        CYPlayBackViewController* controller = [[CYPlayBackViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

//点击其他按钮
- (IBAction)otherAction:(id)sender {
    OtherViewController * vc = [[OtherViewController alloc]init];
    vc.isRecording = self.isRecording;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSArray *)arrCal{
    if (!_arrCal) {
        _arrCal = @[
                    @"设备状态",
                    @"设备号",
                    @"当前状态",
                    @"记录时间",
                    @"设备电量",
                    @"即时心率",
                    @"节律比例",
                    @"RR间期",
                    @"步数",
                    @"代谢当量值",
                    @"步频"];
    }
    return _arrCal;
}

- (CYResult *)result{
    if (!_result) {
        _result = [[CYResult alloc]init];
    }
    return _result;
}



//每秒刷新一次数据
- (void)Timered:(NSTimer*)timer {
    [self.collectionView reloadData];
}


- (NSData *)getDataWithLength:(int)length andData:(NSMutableData *)ecgData {
    NSMutableData *lengthData = [NSMutableData data];
    for (int i = 0; i < length; i++) {
        [lengthData appendBytes:&((Byte*)([ecgData bytes]))[0] length:sizeof(Byte)];
        //移除第一个元素
        if(ecgData.length > 0) {
            [ecgData replaceBytesInRange:NSMakeRange(0, 1) withBytes:NULL length:0];
        }
    }
    return [lengthData copy];
}

#pragma mark CyBleDelegate

#pragma mark 获取硬件信息
- (void)fetchCyEcgDeviceInfo:(CyEcgDeviceModel *)info
{
    self.deviceNum = info.currentDeviceNo;
}

#pragma mark 获取心电设备原始数据
-(void)fetchCyOriginalData:(NSData *)data
{
    //如果使用实时心电ui控件 传入原始数据就可以开始绘制
    [self.refreshMoniterView drawLineWithOriginData:data];
}


#pragma mark 获取实时监测结果
- (void)fetchCyCalResult:(CYResult *)result{
    self.result = result;
}

#pragma mark tableview delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrCal.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //cell的重用，在设置UICollectionView 中注册了cell
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.cellTitleLab.text = self.arrCal[indexPath.row];//设置cell的title

    //设置数据
    switch (indexPath.row) {
        case 0:
            cell.detailLab.text = self.deviceStatus;
            break;
        case 1:
            cell.detailLab.text = self.deviceNum.length <= 0 ? @"--" : self.deviceNum;
            break;
        case 2:
            cell.detailLab.text =self.result.motionState == -1 ? @"--" : [self motionStatus: self.result.motionState];
            break;
        case 3:
            cell.detailLab.text = (self.result.recordTime == -1 || self.result.recordTime == 0) ? @"--" : [NSString stringWithFormat:@"%lld秒",self.result.recordTime];
            break;
        case 4:
            cell.detailLab.text = self.result.battery == -1 ? @"--" : [NSString stringWithFormat:@"%d%%",self.result.battery];
            break;
        case 5:
            cell.detailLab.text = self.result.heartRate == -1 ? @"--" : [NSString stringWithFormat:@"%d",self.result.heartRate];
            break;
        case 6:
            cell.detailLab.text = self.result.rhythm == -1 ? @"--" : [NSString stringWithFormat:@"%.0f%%",self.result.rhythm];
            break;
        case 7:
            cell.detailLab.text = self.result.rrInterval == -1 ? @"--" : [NSString stringWithFormat:@"%d",self.result.rrInterval];
            break;
        case 8:
            cell.detailLab.text = self.result.totalStep == -1 ? @"--" : [NSString stringWithFormat:@"%d",self.result.totalStep];
            break;
        case 9:
            cell.detailLab.text = self.result.mets == -1 ? @"--" : [NSString stringWithFormat:@"%.2f",self.result.mets];
            break;
        case 10:
            cell.detailLab.text = self.result.stepFrequence == -1 ? @"--" : [NSString stringWithFormat:@"%.1d步/分",self.result.stepFrequence];
            break;
        default:
            break;
    }
   
    return cell;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.width/2 - 10 , 40);
}

-(NSString*)motionStatus:(int)status
{
    NSString* motionStr = @"--";
    switch (status) {
        case -1:
            motionStr = @"无";
            break;
        case 1:
            motionStr = @"步行";
            break;
        case 2:
            motionStr = @"站/坐";
            break;
        case 3:
            motionStr = @"跑";
            break;
        case 4:
            motionStr = @"躺";
            break;
        case 5:
            motionStr = @"摔";
            break;
        default:
            break;
    }
    
    return motionStr;
}

//时间戳转时间
- (NSString *)getTimeFromTimestamp:(long long)interval{
    
    if(interval == 0)
    {
        return @"--";
    }
    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:interval/1000];
    //设置时间格式
    
    NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"YYYY.MM.dd HH:mm:ss"];
    
    //将时间转换为字符串
    
    NSString *timeStr=[formatter stringFromDate:myDate];
    
    return timeStr;
}

-(NSString*)ShowValue:(NSString*)value
{
    if([value isEqualToString:@"-1"])
    {
        return @"--";
    }
    
    return value;
}
@end
