//
//  NvRectView.m
//  aa
//
//  Created by 刘东旭 on 2017/8/11.
//  Copyright © 2017年 刘东旭. All rights reserved.
//

#import "NvRectView.h"


@interface NvRectView ()

@property (strong, nonatomic) UIButton *leftTop;
@property (strong, nonatomic) UIButton *rightTop;
@property (strong, nonatomic) UIButton *rightBottom;
@property (strong, nonatomic) UIButton *leftBottom;
@property (assign, nonatomic) CGPoint leftTopPoint;
@property (assign, nonatomic) CGPoint rightTopPoint;
@property (assign, nonatomic) CGPoint rightBottompPoint;
@property (assign, nonatomic) CGPoint leftBottomPoint;
@property (assign, nonatomic) BOOL isDown;
@property (assign, nonatomic) BOOL isInRect;
@property (assign, nonatomic) BOOL isTouchUpInsideStatus;//用于标识是否是点击

@property (assign, nonatomic) BOOL isHiddenRotation;//

@property (nonatomic, assign) NSTimeInterval begin; //开始按下的时间
@property (nonatomic, assign) NSTimeInterval end; //结束按下的时间
@property (nonatomic, assign) CGPoint beginPoint; //开始按下的点
@property (nonatomic, assign) CGPoint endPoint; //结束按下的点

@property (nonatomic, assign) BOOL rollout; //是否划出屏幕

@end

#define NvInterval 150

@implementation NvRectView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.type = NV_CAPTION;
        [self addSubview:self.leftTop];
        [self addSubview:self.rightTop];
        [self addSubview:self.rightBottom];
        [self addSubview:self.leftBottom];
        self.leftTop.hidden = YES;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame type:(NvType)type {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.type = type;
        [self addSubview:self.leftTop];
        [self addSubview:self.rightTop];
        [self addSubview:self.rightBottom];
        [self addSubview:self.leftBottom];
        self.leftTop.hidden = NO;
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    self.isTouchUpInsideStatus = YES;
    self.rollout = NO;
    self.begin = [NSDate date].timeIntervalSince1970*1000;
    NSUInteger toucheNum = [[event allTouches] count];//有几个手指触摸屏幕
    if ( toucheNum > 1 ) {
        return;//多个手指不执行旋转
    }
    
    //self.tranformView，你想旋转的视图
    if (![touch.view isEqual:self]) {
        return;
    }
    
    CGPoint currentPoint = [touch locationInView:touch.view];//当前手指的坐标
    self.beginPoint = currentPoint;
    if ([self.delegate respondsToSelector:@selector(rectView:touchBeganPoint:)]) {
        [self.delegate rectView:self touchBeganPoint:currentPoint];
    }
    
    if (self.rightBottom.frame.origin.x<currentPoint.x && currentPoint.x<(self.rightBottom.frame.origin.x+self.rightBottom.frame.size.width) && self.rightBottom.frame.origin.y<currentPoint.y && currentPoint.y<(self.rightBottom.frame.origin.y+self.rightBottom.frame.size.height)) {
        self.isDown = true;
    }
    
    if ([self isInRect:currentPoint]) {
        self.isInRect = true;
    } else {
        [super touchesBegan:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    self.isTouchUpInsideStatus = NO;
    UITouch *touch = [touches anyObject];
    
    if (self.rollout) {
        return;
    }
    
    NSUInteger toucheNum = [[event allTouches] count];//有几个手指触摸屏幕
    if ( toucheNum > 1 ) {
        return;//多个手指不执行旋转
    }
    
    //self.tranformView，你想旋转的视图
    if (![touch.view isEqual:self]) {
        return;
    }
        
    CGPoint center = [self getCenter];
    CGPoint currentPoint = [touch locationInView:touch.view];//当前手指的坐标
    CGPoint previousPoint = [touch previousLocationInView:touch.view];//上一个坐标
    
    if (!CGRectContainsPoint(self.bounds, currentPoint)) {
        self.rollout = YES;
        return;
    }
    
    float x = currentPoint.x-previousPoint.x;
    float y = currentPoint.y-previousPoint.y;
    NSInteger s = 10;//跟边界的距离

    float minx = currentPoint.x;
    float maxx = currentPoint.x;
    float miny = currentPoint.y;
    float maxy = currentPoint.y;
    //向左滑
    if (x<0) {
        if ((minx-s)<=0) {
            return;
        }
    } else {//向右滑
        if ((maxx+s)>=self.frame.size.width) {
            return;
        }
    }
    //向上滑
    if (y<0) {
        if ((miny-s)<=0) {
            return;
        }
    } else {//向下滑
        if ((maxy+s)>=self.frame.size.height) {
            return;
        }
    }
    
    if (self.isDown) {

        CGFloat angle = atan2f(currentPoint.y - center.y, currentPoint.x - center.x) - atan2f(previousPoint.y - center.y, previousPoint.x - center.x);
        
        CGFloat scale = sqrtf(powf(currentPoint.y - center.y, 2)+powf(currentPoint.x - center.x, 2))/sqrtf(powf(previousPoint.y - center.y, 2)+powf(previousPoint.x - center.x, 2));
        
        if ([self.delegate respondsToSelector:@selector(rectView:rotate:scale:)]) {
            [self.delegate rectView:self rotate:-angle*180/M_PI scale:scale];
        }
        
    } else if(self.isInRect) {
        if ([self.delegate respondsToSelector:@selector(rectView:currentPoint:previousPoint:)]) {
            [self.delegate rectView:self currentPoint:currentPoint previousPoint:previousPoint];
        }
    } else {
        [super touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesEnded");
    self.isDown = false;
    self.isInRect = false;
    
    UITouch *touch = [touches anyObject];
    NSUInteger toucheNum = [[event allTouches] count];//有几个手指触摸屏幕
    if ( toucheNum > 1 ) {
        return;//多个手指不执行旋转
    }
    //self.tranformView，你想旋转的视图
    if (![touch.view isEqual:self]) {
        return;
    }
    CGPoint currentPoint = [touch locationInView:touch.view];//当前手指的坐标
    if ([self.delegate respondsToSelector:@selector(rectView:touchesEnded:)]) {
        [self.delegate rectView:self touchesEnded:currentPoint];
    }
    self.end = [NSDate date].timeIntervalSince1970*1000;
    NSLog(@"按压时间：%f",self.end-self.begin);
    self.endPoint = currentPoint;
    float offset = [self offsetStartPoint:self.beginPoint endPoint:self.endPoint];
    /*
    单独isTouchUpInsideStatus来判断在iphone8上iOS12系统上，单击屏幕会出发touchmove，可能是硬件传感器过于灵敏导致的也可能是系统差异，所以改为通过移动偏移量和按压时间来判断
    */
    if (/*self.isTouchUpInsideStatus && */offset < 3 && (self.begin-self.end)<NvInterval) {
        //只是点击事件
        NSLog(@"只是点击事件:%d",self.isTouchUpInsideStatus);
        if ([self.delegate respondsToSelector:@selector(rectView:touchUpInside:)]) {
            [self.delegate rectView:self touchUpInside:currentPoint];
        }
    } else {
        [super touchesEnded:touches withEvent:event];
    }
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    NSLog(@"touchesCancelled");
    self.isDown = false;
    self.isInRect = false;
    
    UITouch *touch = [touches anyObject];
    NSUInteger toucheNum = [[event allTouches] count];//有几个手指触摸屏幕
    if ( toucheNum > 1 ) {
        return;//多个手指不执行旋转
    }
    //self.tranformView，你想旋转的视图
    if (![touch.view isEqual:self]) {
        return;
    }
    CGPoint currentPoint = [touch locationInView:touch.view];//当前手指的坐标
    if ([self.delegate respondsToSelector:@selector(rectView:touchesEnded:)]) {
        [self.delegate rectView:self touchesEnded:currentPoint];
    }
    
    self.end = [NSDate date].timeIntervalSince1970*1000;
    NSLog(@"按压时间：%f",self.end-self.begin);
    self.endPoint = currentPoint;
    float offset = [self offsetStartPoint:self.beginPoint endPoint:self.endPoint];
    if (/*self.isTouchUpInsideStatus && */offset < 3 && (self.begin-self.end)<NvInterval) {
        //只是点击事件
        NSLog(@"只是点击事件:%d",self.isTouchUpInsideStatus);
        if ([self.delegate respondsToSelector:@selector(rectView:touchUpInside:)]) {
            [self.delegate rectView:self touchUpInside:currentPoint];
        }
    } else {
        [super touchesCancelled:touches withEvent:event];
    }
}

- (float)offsetStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    CGFloat offset = sqrtf(powf(startPoint.y - endPoint.y, 2)+powf(startPoint.x - endPoint.x, 2));
    return offset;
}

- (void)setHidden:(BOOL)hidden {
    [super setHidden:hidden];
    if ([self.delegate respondsToSelector:@selector(rectView:isHidden:)]) {
        [self.delegate rectView:self isHidden:self.hidden];
    }
}

- (void)hidenAlignImage:(BOOL)hiden {
    self.leftBottom.hidden = hiden;
}

- (void)hideVoiceButton:(BOOL)hidden {
    self.leftBottom.hidden = hidden;
}

- (void)hiddenAllImage {
    self.leftBottom.hidden = YES;
    self.leftTop.hidden = YES;
    self.rightTop.hidden = YES;
    self.rightBottom.hidden = YES;
    self.isHiddenRotation = YES;
}

- (void)close {
    if ([self.delegate respondsToSelector:@selector(rectView:close:)]) {
        [self.delegate rectView:self close:self.rightTop];
    }
}

- (void)align {
    if ([self.delegate respondsToSelector:@selector(rectView:align:)]){
        [self.delegate rectView:self align:self.leftBottom];
    }
}

- (void)toggleVolume{
    if ([self.delegate respondsToSelector:@selector(rectView:toggleVolume:)]){
        [self.delegate rectView:self toggleVolume:self.leftBottom];
    }
}

- (void)horizontalFlip {
    if ([self.delegate respondsToSelector:@selector(rectView:horizontalFlip:)]) {
        [self.delegate rectView:self horizontalFlip:self.leftTop];
    }
}

- (void)setVolume:(BOOL)isVoice {
    if (isVoice) {
        [_leftBottom setImage:[UIImage imageNamed:@"NvVoice"] forState:UIControlStateNormal];
    } else {
        [_leftBottom setImage:[UIImage imageNamed:@"NvSilent"] forState:UIControlStateNormal];
    }
}

- (void)setTextAlign:(NvTextAlign)align {
    if (align == NvLeft) {
        [_leftBottom setImage:[UIImage imageNamed:@"NvTextAlignedLeft"] forState:UIControlStateNormal];
    } else if (align == NvCenter) {
        [_leftBottom setImage:[UIImage imageNamed:@"NvTextAlignedCenter"] forState:UIControlStateNormal];
    }else if (align == NvRight) {
        [_leftBottom setImage:[UIImage imageNamed:@"NvTextAlignedRight"] forState:UIControlStateNormal];
    } else {
        [_leftBottom setImage:[UIImage imageNamed:@"NvTextAlignedLeft"] forState:UIControlStateNormal];
    }
}

//MARK Getter
- (UIButton *)leftTop {
    if (!_leftTop) {
        _leftTop = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        [_leftTop setImage:[UIImage imageNamed:@"NvHorizontalFlip"] forState:UIControlStateNormal];
        [_leftTop addTarget:self action:@selector(horizontalFlip) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftTop;
}

- (UIButton *)rightTop {
    if (!_rightTop) {
        _rightTop = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width-20, 0, 20, 20)];
        [_rightTop setImage:[UIImage imageNamed:@"NvClose"] forState:UIControlStateNormal];
        [_rightTop addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightTop;
}

- (UIButton *)rightBottom {
    if (!_rightBottom) {
        _rightBottom = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width-20, self.frame.size.height-20, 20, 20)];
        _rightBottom.alpha = 0;
    }
    return _rightBottom;
}

- (UIButton *)leftBottom {
    if (!_leftBottom) {
        _leftBottom = [[UIButton alloc] initWithFrame:CGRectMake(0, self.frame.size.height-20, 20, 20)];
        if (self.type == NV_CAPTION) {
            [_leftBottom setImage:[UIImage imageNamed:@"NvTextAlignedLeft"] forState:UIControlStateNormal];
            [_leftBottom addTarget:self action:@selector(align) forControlEvents:
             UIControlEventTouchUpInside];
        } else {
            [_leftBottom setImage:[UIImage imageNamed:@"NvVoice"] forState:UIControlStateNormal];
            [_leftBottom addTarget:self action:@selector(toggleVolume) forControlEvents:
             UIControlEventTouchUpInside];
        }

        //_leftBottom.alpha = 0;
    }
    return _leftBottom;
}
//重新绘制
- (void)setPoints:(NSArray *)array {
    self.leftTopPoint = [array[0] CGPointValue];
    self.leftBottomPoint = [array[1] CGPointValue];
    self.rightBottompPoint = [array[2] CGPointValue];
    self.rightTopPoint = [array[3] CGPointValue];
    self.leftTop.center = self.leftTopPoint;
    self.rightTop.center = self.rightTopPoint;
    self.rightBottom.center = self.rightBottompPoint;
    self.leftBottom.center = self.leftBottomPoint;
    [self setNeedsDisplay];
}
//判断点是否在四点围城rect之内
- (BOOL)isInRect:(CGPoint)p {
    CGMutablePathRef pathRef=CGPathCreateMutable();
    CGPathMoveToPoint(pathRef, NULL, self.leftTopPoint.x, self.leftTopPoint.y);
    CGPathAddLineToPoint(pathRef, NULL, self.leftBottomPoint.x, self.leftBottomPoint.y);
    CGPathAddLineToPoint(pathRef, NULL, self.rightBottompPoint.x, self.rightBottompPoint.y);
    CGPathAddLineToPoint(pathRef, NULL, self.rightTopPoint.x, self.rightTopPoint.y);
    CGPathCloseSubpath(pathRef);
    BOOL isIn = CGPathContainsPoint(pathRef, nil, p, false);
    CGPathRelease(pathRef);
    return isIn;
}

- (CGPoint)getCenter {
    return CGPointMake((self.leftTop.center.x+self.rightBottom.center.x)/2, (self.leftTop.center.y+self.rightBottom.center.y)/2);
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineCap(contextRef, kCGLineCapRound);
    CGContextSetLineWidth(contextRef, 2);  //线宽
    CGContextSetAllowsAntialiasing(contextRef, true);
    CGContextSetRGBStrokeColor(contextRef, 74.0 / 255.0, 144.0 / 255.0, 226.0 / 255.0, 1.0);  //线的颜色
    CGContextBeginPath(contextRef);

    CGContextMoveToPoint(contextRef, self.leftTopPoint.x, self.leftTopPoint.y);
    CGContextAddLineToPoint(contextRef, self.leftBottomPoint.x, self.leftBottomPoint.y);
    CGContextAddLineToPoint(contextRef, self.rightBottompPoint.x, self.rightBottompPoint.y);
    CGContextAddLineToPoint(contextRef, self.rightTopPoint.x, self.rightTopPoint.y);
    CGContextAddLineToPoint(contextRef, self.leftTopPoint.x, self.leftTopPoint.y);
    
    CGContextStrokePath(contextRef);
    if (self.isHiddenRotation) {
        
    } else {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGRect rotateRect = CGRectMake(self.rightBottompPoint.x-10, self.rightBottompPoint.y-10, 20, 20);
        CGContextAddEllipseInRect(context, rotateRect);
        [[UIColor whiteColor] set];
        CGContextFillPath(context);
        [[UIColor blackColor] set];
        CGContextDrawImage(context, rotateRect, [UIImage imageNamed:@"NvRotate"].CGImage);
    }
}


@end
