//
//  YOECGChartView.m
//  ECGChartView
//
//  Created by Mac on 2021/6/4.
//

#import "YOECGChartView.h"

@interface YOECGChartView()

/// 走纸速速 默认25mm/s (0.025s)
@property (nonatomic) int speed;

/// 纸张规格 10 mV/mm (一小格 10mV)
@property (nonatomic) int voltageSpecifications;

@property (nonatomic) YOECGChartViewType drawECGType;

@property (nonatomic) NSArray *voltageArr;

@property (nonatomic) UIView *pdfView;

@end


@implementation YOECGChartView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self configPar];
    }
    return self;
}


-(void)configPar{
    self.standard = [YOECGParamter new];
    self.negativeNum = 4;
    self.positiveNum = 4;
    self.statictiveNum = 10;
    self.gridView = [[YOECGBackGroundGridView alloc]initWithFrame:self.bounds];
    self.gridView.standard = self.standard;
    [self addSubview:self.gridView];
    self.ecgView = [[YOECGLineView alloc]initWithFrame:self.bounds];
    self.ecgView.standard = self.standard;
    [self addSubview:self.ecgView];
}


-(void)refreshSubViewFrame{
    /// 计算出总的列数
    int column = self.bounds.size.width / self.standard.oneGridSize;
    /// 网格的宽度
    float width = column * self.standard.oneGridSize;
    float ecgHeight = (self.negativeNum + self.positiveNum )  * self.standard.oneGridSize;
    if (self.drawECGType == YOECGChartViewStatic && self.voltageArr.count > 0) {
        width = self.voltageArr.count * self.standard.onePointWidth;
    }
    if (self.bounds.size.height > ecgHeight) {
        self.ecgView.frame = CGRectMake(0, 0, width, ecgHeight);
    }else{
        self.ecgView.frame = CGRectMake(0, 0, width, self.bounds.size.height);
    }
    self.gridView.frame = CGRectMake(0, 0, width, self.bounds.size.height);
}

/// 画静心电图【單軌】
-(void)drawStaticECGLine:(NSArray *)voltageArr{
    [self drawStaticECGLine:voltageArr oneLine:YES];
}

/// 画静心电图【YES 單軌 ,NO 雙軌】
-(void)drawStaticECGLine:(NSArray *)voltageArr oneLine:(BOOL)oneLine {
    if(![self.standard parameterIsRight]){
        NSAssert(NO, @"参数有问题");
    }
    self.voltageArr = voltageArr;
    self.drawECGType = YOECGChartViewStatic;
    if (oneLine) {
        self.gridView.hidden = self.ecgView.hidden = NO;
        [self.pdfView removeFromSuperview];
        [self refreshSubViewFrame];
        self.gridView.gridTotal = self.negativeNum + self.positiveNum;
        self.gridView.standard = self.standard;
        self.gridView.secodeLineHeight = self.standard.oneGridSize;
        self.gridView.isShowSecondText = YES;
        self.gridView.startSecond = 0;
        [self.gridView reloadGrid];
        self.ecgView.positiveNum = self.positiveNum;
        self.ecgView.negativeNum = self.negativeNum;
        self.ecgView.standard = self.standard;
        self.ecgView.clipsToBounds = YES;
        [self.ecgView drawStaticECGLine:voltageArr];
    } else {
        self.gridView.hidden = self.ecgView.hidden = YES;
        //計算＊秒的心電圖寬
        NSInteger indexX = (self.standard.oneGridSize * 2);
        NSInteger indexY = (self.standard.oneGridSize * 3);
        float allWidth = voltageArr.count * self.standard.onePointWidth;
        if (self.statictiveMaxNum > 0) {
            allWidth = 5 * self.statictiveMaxNum * self.standard.oneGridSize;
        }
        float ecgWidth = 5 * self.statictiveNum * self.standard.oneGridSize;
        float ecgHeight = (self.negativeNum + self.positiveNum )  * self.standard.oneGridSize;
        float indexW = ecgWidth;
        int indexS = 0;
        NSInteger row = 0;
        NSInteger MaxRow = 3;
        float pageHeight = (ecgHeight*MaxRow)+(indexY*MaxRow);
        NSInteger indexRow = ceil((allWidth/ecgWidth)/MaxRow)?:1;
        self.pdfView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ecgWidth+(indexX*2), pageHeight*indexRow)];
        [self addSubview:self.pdfView];
        UIView *pageView = [self pageViewInitWithFrame:CGRectMake(0, 0, self.pdfView.frame.size.width, pageHeight) X:indexX];
        [self.pdfView addSubview:pageView];
        YOECGBackGroundGridView *gridView = [self gridViewInitWithFrame:CGRectMake(indexX, indexY, ecgWidth, ecgHeight) StartSecond:indexS];
        [pageView addSubview:gridView];
        YOECGLineView *ecgView = [self ecgViewInitWithFrame:CGRectMake(indexX, indexY, ecgWidth, ecgHeight)];
        [pageView addSubview:ecgView];
        NSMutableArray *voltages = [NSMutableArray array];
        for (int i = 0; i < voltageArr.count; i++) {
            [voltages addObject:voltageArr[i]];
            if ((indexW - (i * self.standard.onePointWidth)) <= 0 || i == voltageArr.count-1) {
                //畫心電圖
                [ecgView drawStaticECGLine:voltages];
                //尚未完成，重新設定
                voltages = [NSMutableArray array];
                [voltages addObject:voltageArr[i]];
                indexS += self.statictiveNum;
                indexY += ecgHeight + (self.standard.oneGridSize * 2);
                indexW += ecgWidth;
                row += 1;
                self.statictiveMaxNum -= self.statictiveNum;
                if (indexW >= allWidth) {
                    indexW = allWidth;
                }
                if (i == voltageArr.count-1 || self.statictiveMaxNum == 0) {
                    return;
                }
                if (row%MaxRow == 0) {
                    indexY = (self.standard.oneGridSize * 3);
                    pageView = [self pageViewInitWithFrame:CGRectMake(0, pageHeight*(row/MaxRow), self.pdfView.frame.size.width, pageHeight) X:indexX];
                    [self.pdfView addSubview:pageView];
                }
                gridView = [self gridViewInitWithFrame:CGRectMake(indexX, indexY, ecgWidth, ecgHeight) StartSecond:indexS];
                [pageView addSubview:gridView];
                ecgView = [self ecgViewInitWithFrame:CGRectMake(indexX, indexY, ecgWidth, ecgHeight)];
                [pageView addSubview:ecgView];
            }
        }
    }
}

- (UIView *)pageViewInitWithFrame:(CGRect)frame X:(NSInteger)indexX {
    UIView *pageView = [[UIView alloc]initWithFrame:frame];
    pageView.backgroundColor = [UIColor whiteColor];
    UILabel *valueLabel = [UILabel new];
    valueLabel.text = [NSString stringWithFormat:@"%d mm/s, %d mm/mV, %d Hz",self.standard.speed,self.standard.voltageSpecifications,self.standard.sampleFrequency];
    [valueLabel sizeToFit];
    [valueLabel setFrame:CGRectMake(indexX, indexX, valueLabel.frame.size.width, valueLabel.frame.size.height)];
    [pageView addSubview:valueLabel];
    UILabel *dateLabel = [UILabel new];
    dateLabel.text = [NSString stringWithFormat:@"%@",self.ecgDate];
    [dateLabel sizeToFit];
    [dateLabel setFrame:CGRectMake(pageView.frame.size.width-dateLabel.frame.size.width-indexX, indexX, dateLabel.frame.size.width, dateLabel.frame.size.height)];
    [pageView addSubview:dateLabel];
    return pageView;
}

- (YOECGBackGroundGridView *)gridViewInitWithFrame:(CGRect)frame StartSecond:(int)startSecond {
    YOECGBackGroundGridView *gridView = [[YOECGBackGroundGridView alloc]initWithFrame:frame];
    gridView.gridTotal = self.negativeNum + self.positiveNum;
    gridView.standard = self.standard;
    gridView.bigGridColor = [UIColor darkGrayColor];
    gridView.smallGridColor = [UIColor lightGrayColor];
    gridView.secodeLineHeight = self.standard.oneGridSize;
    gridView.isShowSecondText = YES;
    gridView.startSecond = startSecond;
    [gridView reloadGrid];
    return gridView;
}

- (YOECGLineView *)ecgViewInitWithFrame:(CGRect)frame {
    YOECGLineView *ecgView = [[YOECGLineView alloc]initWithFrame:frame];
    ecgView.positiveNum = self.positiveNum;
    ecgView.negativeNum = self.negativeNum;
    ecgView.standard = self.standard;
    ecgView.clipsToBounds = YES;
    return ecgView;
}

- (UIImage *)pdfImageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.frame.size ,YES ,[UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (NSMutableArray *)pdfImages {
    if (self.pdfView) {
        NSMutableArray *pdfImages = [NSMutableArray array];
        for (UIView *view in self.pdfView.subviews) {
            UIImage *image = [self pdfImageWithView:view];
            [pdfImages addObject:image];
        }
        return pdfImages;
    } else {
        return nil;
    }
}

- (NSString *)pdfPath {
    if (self.pdfView) {
        NSArray *arry = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *fullFileName = [NSString stringWithFormat:@"%@[ECG].pdf",self.ecgDate];
        NSString *pdfPath = [[arry lastObject]stringByAppendingPathComponent:fullFileName];
        NSMutableData *pdfData = [NSMutableData data];
        UIView *indexView = [self.pdfView.subviews firstObject];
        UIGraphicsBeginPDFContextToData(pdfData, indexView.bounds, nil);
        for (UIView *view in self.pdfView.subviews) {
            UIGraphicsBeginPDFPage();
            CGContextRef pdfContext = UIGraphicsGetCurrentContext();
            [view.layer renderInContext:pdfContext];
        }
        UIGraphicsEndPDFContext();
        [pdfData writeToFile:pdfPath atomically:YES];
        return pdfPath;
    } else {
        return nil;
    }
}

- (NSString *)ecgDate {
    NSDateFormatter *dFormatter = [NSDateFormatter new];
    [dFormatter setLocale:[NSLocale currentLocale]];
    [dFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *date = [dFormatter stringFromDate:[NSDate date]];
    return date;
}

/// 实时心电图【双轨迹】
-(void)drawRealTimeECGLine:(NSArray *)voltageArr{
    [self drawRealTimeECGLine:voltageArr twoLine:YES];
}

/// 实时心电图【YES 双轨迹 ,NO 单轨迹】
-(void)drawRealTimeECGLine:(NSArray *)voltageArr twoLine:(BOOL)twoLine{
    if(![self.standard parameterIsRight]){
        NSAssert(NO, @"参数有问题");
    }
    [self refreshSubViewFrame];
    self.ecgView.positiveNum = self.positiveNum;
    self.ecgView.negativeNum = self.negativeNum;
    self.ecgView.standard = self.standard;
    self.ecgView.clipsToBounds = NO;
    if (twoLine) {
        self.drawECGType = YOECGChartViewRealTimeTwoLine;
        [self.ecgView drawRealTimeECGTwoLine:voltageArr];
    } else {
        self.drawECGType = YOECGChartViewRealTimeOneLine;
        [self.ecgView drawRealTimeECGOneLine:voltageArr];
    }
}


-(void)reloadGridView{
    self.gridView.gridTotal = self.negativeNum + self.positiveNum;
    self.gridView.standard = self.standard;
    self.gridView.secodeLineHeight = 0;
    self.gridView.isShowSecondText = NO;
    self.gridView.startSecond = 0;
    [self.gridView reloadGrid];
}


-(void)reload{
    self.voltageArr = [NSArray array];
    self.gridView.hidden = self.ecgView.hidden = NO;
    [self.gridView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.ecgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.ecgView clearData];
    [self.pdfView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.pdfView removeFromSuperview];
    [self refreshSubViewFrame];
    [self reloadGridView];
}

@end
