//
//  KKChartView.m
//  Open
//
//  Created by 雷俊博 on 2020/7/17.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "KKChartView.h"
#import "UIView+frameAdjust.h"

@interface KKChartView ()
{
    NSInteger lastTag;
    UILabel*  currentLabel;
    UILabel*  titleLabel;
    NSInteger currentTag;
    
}


@property (nonatomic, strong)NSMutableArray* x_names;

@property (nonatomic, strong)NSMutableArray* targetValues;

@property (nonatomic, strong)NSMutableArray* sublayers;





@end

@implementation KKChartView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.x_names = [NSMutableArray array];
        self.targetValues = [NSMutableArray array];
        self.sublayers = [NSMutableArray array];
    }
    return self;
}

/**
 *  画柱状图
 */
-(void)drawBarChartViewWithX_Value_Names:(NSMutableArray *)x_names TargetValues:(NSMutableArray *)targetValues
{
    self.x_names = x_names;
    self.targetValues = targetValues;
    for (UIView* subView in self.subviews) {
        [subView removeFromSuperview];
    }
    for (CAShapeLayer*layer in self.sublayers) {
        [layer removeFromSuperlayer];
    }
    [self.sublayers removeAllObjects];
    
    //1.画坐标轴
    [self drawXYLine:x_names];
    CGFloat targetValueMax = 0.0;
    CGFloat ATargetValue = 0.0;
    for (int i = 0; i < targetValues.count; i++) {
        NSString* str = targetValues[i];
        if (i == 0) {
            targetValueMax = str.floatValue;
        }else{
            if (str.floatValue > targetValueMax) {
                targetValueMax = str.floatValue;
            }
        }
    }
    
    ATargetValue = targetValueMax * 1.1/5;
    
    CGFloat width = CGRectGetWidth(self.frame);
//    CGFloat height = CGRectGetHeight(self.frame);
    NSInteger count = x_names.count;
    CGFloat itemWidth = (width - 2*self.leftMargin - (count + 1)*self.horizontalMargin)/count;
    CGFloat subItemwidth = 10.0;
    self.columnWidth = itemWidth;
    
    //2.每一个目标值点坐标
    for (int i=0; i < targetValues.count; i++) {
        //10为坐标间距
        CGFloat doubleValue = 0.0;
        if (ATargetValue > 0) {
            doubleValue = [targetValues[i] floatValue]/ATargetValue * self.verticalMargin; //目标值放大
        }else{
            doubleValue = 0.0; //目标值放大
        }
        CGFloat X = self.leftMargin + self.horizontalMargin + (itemWidth - subItemwidth)/2 + (self.horizontalMargin+self.columnWidth )*i;
        //CGFloat X = self.leftMargin + self.horizontalMargin*(i+1)+5;
        CGFloat Y = CGRectGetHeight(self.frame)-self.bottomMargin-doubleValue;
        
//        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(X, Y, subItemwidth, doubleValue)];
        UIBezierPath *path = [UIBezierPath bezierPath];
        // 首先设置一个起始点
        CGPoint startPoint = CGPointMake(X, Y + subItemwidth/2);
        [path moveToPoint:startPoint];
        [path addArcWithCenter:CGPointMake(X + subItemwidth/2, Y + subItemwidth/2) radius:subItemwidth/2 startAngle:-M_PI endAngle:0 clockwise:YES];
        [path addLineToPoint:CGPointMake(X + subItemwidth, CGRectGetHeight(self.frame)-self.bottomMargin)];
        [path addLineToPoint:CGPointMake(X, CGRectGetHeight(self.frame)-self.bottomMargin)];
        [path addLineToPoint:startPoint];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = path.CGPath;
        shapeLayer.strokeColor = [UIColor clearColor].CGColor;
        if (currentTag >= 1000) {
            if (i == (currentTag -1000)) {
                shapeLayer.fillColor = K_MainColor.CGColor;
            }else{
                shapeLayer.fillColor = [UIColor colorWithHex:0x5ab9ff].CGColor;
            }
        }else{
            if (i == (targetValues.count - 1)) {
                shapeLayer.fillColor = K_MainColor.CGColor;
            }else{
                shapeLayer.fillColor = [UIColor colorWithHex:0x5ab9ff].CGColor;
            }
        }
        shapeLayer.borderWidth = 2.0;
        if (doubleValue >= 10) {
            [self.layer addSublayer:shapeLayer];
            [self.sublayers addObject:shapeLayer];
        }
        
        
        //新建一个按钮，透明 覆盖shapeLayer
        UIButton * btn = [[UIButton alloc]init];
        btn.frame = CGRectMake(X, 0, self.columnWidth, CGRectGetHeight(self.frame)-self.bottomMargin);
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 1000 + i;
        [btn addTarget:self action:@selector(targetButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        
        
        CGFloat subX = self.leftMargin + self.horizontalMargin + (self.horizontalMargin+self.columnWidth )*i;
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(subX, Y-15,self.columnWidth, 15)];
        NSString* str = targetValues[i];
        textLabel.text = [NSString stringWithFormat:@"%@",str];
        textLabel.font = [UIFont systemFontOfSize:13.0];
        textLabel.textAlignment = NSTextAlignmentCenter;
        
        if (currentTag >= 1000) {
            if (i == (currentTag -1000)) {
                textLabel.textColor = K_MainColor;
                lastTag =  currentTag;
                NSString* str = [NSString stringWithFormat:@"%@步",targetValues[i]];
                 NSMutableAttributedString*attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                 [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:40],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(0, str.length - 1)];
                 [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(str.length - 1, 1)];
                
                titleLabel.attributedText = attributedStr;
                currentLabel.text = [self getDateStrWithStr:x_names[i]];
             }else{
                textLabel.textColor = [UIColor colorWithHex:0x5ab9ff];
            }
        }else{
            if (i == (targetValues.count - 1)) {
                textLabel.textColor = K_MainColor;
                lastTag =  i + 1000;
                NSString* str = [NSString stringWithFormat:@"%@步",targetValues[i]];
                 NSMutableAttributedString*attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                 [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:40],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(0, str.length - 1)];
                 [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(str.length - 1, 1)];
                
                titleLabel.attributedText = attributedStr;
                currentLabel.text = [self getDateStrWithStr:x_names[i]];
            }else{
                textLabel.textColor = [UIColor colorWithHex:0x5ab9ff];
            }
        }
        
        if (doubleValue > 0) {
            [self addSubview:textLabel];
        }
        
        
        
    }
     
}

/**
 *  画坐标轴
 */
-(void)drawXYLine:(NSMutableArray *)x_names{
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    
//    UILabel * priceLabel = [[UILabel alloc]init];
//    priceLabel.frame = CGRectMake(self.leftMargin, 5, 35, 15);
//    priceLabel.text = @"价格：¥";
//    priceLabel.textColor = [UIColor whiteColor];
//    priceLabel.font = [UIFont systemFontOfSize:8.0];
//    [self addSubview:priceLabel];


//    UILabel * firstLabel = [[UILabel alloc]init];
//    firstLabel.frame = CGRectMake(self.leftMargin,CGRectGetHeight(self.frame)-self.bottomMargin, self.priceLabelWidth, 20);
//    firstLabel.text = @"最近一周";
//    firstLabel.textColor = [UIColor whiteColor];
//    firstLabel.font = [UIFont systemFontOfSize:8.0];
//    firstLabel.adjustsFontSizeToFitWidth = YES;
//    [self addSubview:firstLabel];
    
    
    //1.Y轴、X轴的直线
    [path moveToPoint:CGPointMake(self.leftMargin, CGRectGetHeight(self.frame)-self.bottomMargin)];
    [path addLineToPoint:CGPointMake(self.leftMargin+CGRectGetWidth(self.frame)-2*self.leftMargin, CGRectGetHeight(self.frame)-self.bottomMargin)];
    
    //2.添加箭头
//    [path moveToPoint:CGPointMake(MARGIN, MARGIN)];
//    [path addLineToPoint:CGPointMake(MARGIN-5, MARGIN+5)];
//    [path moveToPoint:CGPointMake(MARGIN, MARGIN)];
//    [path addLineToPoint:CGPointMake(MARGIN+5, MARGIN+5)];
//
//    [path moveToPoint:CGPointMake(MARGIN+CGRectGetWidth(myFrame)-2*MARGIN, CGRectGetHeight(myFrame)-MARGIN)];
//    [path addLineToPoint:CGPointMake(MARGIN+CGRectGetWidth(myFrame)-2*MARGIN-5, CGRectGetHeight(myFrame)-MARGIN-5)];
//    [path moveToPoint:CGPointMake(MARGIN+CGRectGetWidth(myFrame)-2*MARGIN, CGRectGetHeight(myFrame)-MARGIN)];
//    [path addLineToPoint:CGPointMake(MARGIN+CGRectGetWidth(myFrame)-2*MARGIN-5, CGRectGetHeight(myFrame)-MARGIN+5)];
    
    
    CGFloat width = CGRectGetWidth(self.frame);
//    CGFloat height = CGRectGetHeight(self.frame);
    NSInteger count = x_names.count;
    CGFloat itemWidth = (width - 2*self.leftMargin - (count + 1)*self.horizontalMargin)/count;
    self.columnWidth = itemWidth;

    //3.添加索引格
    //X轴
    for (int i=0; i<x_names.count; i++) {
        CGFloat X = self.leftMargin + self.horizontalMargin +self.columnWidth/2+ (self.horizontalMargin+self.columnWidth)*i;
        CGPoint point = CGPointMake(X,CGRectGetHeight(self.frame)-self.bottomMargin);
        [path moveToPoint:point];
        [path addLineToPoint:CGPointMake(point.x, point.y-3)];
    }
    //Y轴（实际长度为200,此处比例缩小一倍使用）
    for (int i=0; i < self.verticalArray.count; i++) {
        CGFloat Y = CGRectGetHeight(self.frame)-self.bottomMargin-self.verticalMargin*i;
        CGPoint point = CGPointMake(self.leftMargin,Y);
        [path moveToPoint:point];
        [path addLineToPoint:CGPointMake(point.x+CGRectGetWidth(self.frame)-2*self.leftMargin, point.y)];
    }
    
    
    //4.添加索引格文字
    //X轴
    for (int i=0; i<x_names.count; i++) {
        CGFloat X = self.leftMargin + self.horizontalMargin + (self.horizontalMargin+self.columnWidth)*i;
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(X, CGRectGetHeight(self.frame)-self.bottomMargin + 10, self.columnWidth, 20)];
        textLabel.text = x_names[i];
        textLabel.font = [UIFont systemFontOfSize:8];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.textColor = [UIColor colorWithHex:0x4d4d4d];
        textLabel.numberOfLines = 2;
        [self addSubview:textLabel];
    }
    //Y轴
//    for (int i=0; i < self.verticalArray.count; i++) {
//        CGFloat Y = CGRectGetHeight(self.frame)-self.bottomMargin-self.verticalMargin*i;
//        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.leftMargin, Y-10,self.priceLabelWidth, 10)];
//        textLabel.text = [NSString stringWithFormat:@"%@",self.verticalArray[i]];
//        textLabel.font = [UIFont systemFontOfSize:8.0];
//        textLabel.textAlignment = NSTextAlignmentLeft;
//        textLabel.textColor = RGBCOLOR(204, 204, 204);
//        [self addSubview:textLabel];
//    }
    
    //5.渲染路径
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    shapeLayer.lineWidth = 0.2;
    shapeLayer.strokeColor = [UIColor colorWithHex:0x808080].CGColor;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.borderWidth = 0.5;
    [self.sublayers addObject:shapeLayer];
    [self.layer addSublayer:shapeLayer];
    
    NSInteger stepCount = 0;
    NSString* str = [NSString stringWithFormat:@"%ld步",stepCount];
     NSMutableAttributedString*attributedStr = [[NSMutableAttributedString alloc]initWithString:str];
     [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:40],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(0, str.length - 1)];
     [attributedStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:K_MainColor} range:NSMakeRange(str.length - 1, 1)];
    
    currentLabel = [[UILabel alloc]init];
    currentLabel.frame = CGRectMake(self.leftMargin,0, self.width - self.leftMargin * 2, 20);
    currentLabel.font = [UIFont systemFontOfSize:15.0];
    currentLabel.textColor = [UIColor colorWithHex:0x4d4d4d];
    currentLabel.textAlignment = NSTextAlignmentCenter;
    currentLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:currentLabel];
     
    titleLabel = [[UILabel alloc]init];
    titleLabel.frame = CGRectMake(self.leftMargin,CGRectGetMaxY(currentLabel.frame) + 20, self.width - self.leftMargin * 2, 30);
    titleLabel.font = [UIFont systemFontOfSize:18.0];
    titleLabel.textColor = K_MainColor;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:titleLabel];
    titleLabel.attributedText = attributedStr;
}


#pragma mark - event response
- (void)targetButtonClick:(UIButton *)sender
{
    currentTag = sender.tag;
    
    
    
    [self drawBarChartViewWithX_Value_Names:self.x_names TargetValues:self.targetValues];
}

#pragma mark - getDate
- (NSString *)getDateStrWithStr:(NSString *)dateStr
{
    NSString*dateString =  [dateStr substringToIndex:5];
    
    NSArray*dateArray = [dateString componentsSeparatedByString:@"/"];
    
    NSString*month = dateArray[0];
    NSString*day = dateArray[1];
  
    
    NSString* currentDateStr = [NSString stringWithFormat:@"%d月%d日",month.intValue,day.intValue];
    return currentDateStr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
