//
//  CYPlayBackViewController.m
//  Demo
//
//  Created by super on 2019/7/1.
//  Copyright © 2019 super. All rights reserved.
//

#import "CYPlayBackViewController.h"
#define IPHONE_X \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})
//屏幕宽高
#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height
#define WEAKSELF __weak typeof(self) weakSelf = self;

@interface CYPlayBackViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView* tableView;
/**
 心电回放视图
 */

/**
 蓝牙数据
 */
@property (nonatomic,strong) NSData * ecgData;

@property (nonatomic, strong) CYEcgPlayBackView *ecgView;
@property (nonatomic, strong) UIView *container;
/**
 开始时间
 */
@property (nonatomic, assign) NSTimeInterval startTime;

@end

@implementation CYPlayBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    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 setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 20, 20);
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    self.title = @"报告结果";
    //初始化心电视图
    [self setupEcgView];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
    
    [self.ecgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.container).offset(10);
        make.bottom.equalTo(self.container).offset(-10);
        make.left.equalTo(self.container).offset(10);
        make.right.equalTo(self.container).offset(-10);
    }];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.container.mas_bottom);
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
    }];
    
    [self getEcgDataWithCount:0 andRefreshData:YES];

}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 设置心电视图
 */
- (void)setupEcgView {

   self.ecgView = [[CYEcgPlayBackView alloc]initWithFrame:CGRectMake(20, 64, ScreenW - 40, 250)];

   self.container = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 20, 250)];
    [self.view addSubview:self.container];
    self.container.layer.borderWidth = 1;
    self.container.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.container.layer.cornerRadius = 10;
    self.container.layer.masksToBounds = YES;
    [self.container addSubview:self.ecgView];
    
}




#pragma mark 数据处理
/**
 从oss下载文件
 
 @param count 当前下载的文件个数（判断需要下载的文件是否足够）
 @param refresh 是否刷新数据
 */
- (void)getEcgDataWithCount:(int)count andRefreshData:(BOOL)refresh{
    WEAKSELF
//    NSString *keyName;
//    if (self.viewType == TrainViewTypeSelfMonitor) {
//        keyName = self.fileKeyArr[count];
//    } else {
//        keyName = self.fileKeyArr.firstObject;
//    }
//
#ifdef THREESDK
    CYLastFileInfo* lastInfo = [CYEcgKit sharedInstance].lastFileInfo;
#else
    CYLastFileInfo* lastInfo = [CYBaseKit sharedInstance].lastFileInfo;
#endif
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:lastInfo.filePath]) {
        //文件存在
        dispatch_async(dispatch_get_main_queue(), ^{
                if (refresh) {
                    NSData *originData = [NSData dataWithContentsOfFile:lastInfo.filePath];

                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //刷新数据

                        [weakSelf.ecgView mappingData:originData];
                    });
                }
//
//            }
//            NSData *ecgData = [NSData dataWithContentsOfFile:[filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.ed",weakSelf.fileNameArr[count]]]];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //刷新数据
//                [weakSelf mappingData:ecgData];
//            });

        });
    }
    
    [self.tableView reloadData];
}



#pragma mark tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}

-(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];
        cell.backgroundColor = [UIColor whiteColor];
        UILabel* titleLab = [[UILabel alloc] initWithFrame:CGRectMake(17, 0, 100, cell.frame.size.height)];
        titleLab.font = [UIFont systemFontOfSize:15];
        titleLab.numberOfLines = 0;
        [titleLab setTag:10086];
        titleLab.textAlignment = NSTextAlignmentLeft;
        [cell addSubview:titleLab];
        
        UILabel* detailLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(titleLab.frame), 0, cell.frame.size.width - CGRectGetMaxX(titleLab.frame) - 17, cell.frame.size.height)];
        [detailLab setTag:10087];
        detailLab.font = [UIFont systemFontOfSize:15];
        detailLab.numberOfLines = 0;
        detailLab.textAlignment = NSTextAlignmentCenter;
        detailLab.backgroundColor = [UIColor lightTextColor];
        [cell addSubview:detailLab];
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell);
            make.left.mas_equalTo(30);
            make.bottom.equalTo(cell);
            make.width.mas_equalTo(100);
        }];
        
        [detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).offset(1);
            make.left.equalTo(titleLab.mas_right).offset(20);
            make.right.equalTo(cell).offset(-20);
            make.bottom.equalTo(cell).offset(-1);
        }];
    }
    #ifdef THREESDK
    CYLastFileInfo* lastInfo = [CYEcgKit sharedInstance].lastFileInfo;
#else
    CYLastFileInfo* lastInfo = [CYBaseKit sharedInstance].lastFileInfo;
#endif
    if(lastInfo != nil)
    {
        UILabel* titleLab = [cell viewWithTag:10086];
        UILabel* detailLab = [cell viewWithTag:10087];
        
        detailLab.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        if(indexPath.row == 0)
        {
            titleLab.text = @"文件路径";
            detailLab.text = lastInfo.filePath;
        }
        else if (indexPath.row == 1)
        {
            detailLab.backgroundColor = [UIColor whiteColor];
        }
        else if (indexPath.row == 2)
        {
            titleLab.text = @"记录信息";
            detailLab.text = [NSString stringWithFormat:@"记录开始时间：%@",[self getTimeFromTimestamp:lastInfo.recordStartTime]];
        }
        else if (indexPath.row == 3)
        {
            detailLab.text = [NSString stringWithFormat:@"记录时长(秒)：%lld",lastInfo.recordDuration];
        }
        else if (indexPath.row == 4)
        {
            detailLab.text = [NSString stringWithFormat:@"最小心率：%dbpm",lastInfo.minHR];
        }
        else if (indexPath.row == 5)
        {
            detailLab.text = [NSString stringWithFormat:@"平均心率：%dbpm",lastInfo.avgHR];
        }
        else if (indexPath.row == 6)
        {
            detailLab.text =  [NSString stringWithFormat:@"最大心率：%dbpm",lastInfo.maxHR];
        }
        else if (indexPath.row == 7)
        {
            detailLab.text = [NSString stringWithFormat:@"步数：%d",lastInfo.totalStepNum];
        }
    }
    
    return cell;
}

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

//时间戳转时间
- (NSString *)getTimeFromTimestamp:(long long)interval{
    
    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;
    
}

@end
