//
//  HYHAddImageView.m
//  HYHRotateScaleImageView
//
//  Created by huangyongheng on 2019/7/11.
//  Copyright © 2019 hyh. All rights reserved.
//

#import "HYHAddImageView.h"
#import <Masonry/Masonry.h>

@interface HYHAddImageView () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView *contentView;
/** 旋转缩放控制按钮 */
@property (nonatomic, strong) UIImageView *rotateCtrl;
/** 删除视图控制按钮 */
@property (nonatomic, strong) UIButton *removeButton;
/** 翻转视图控制按钮 */
@property (nonatomic, strong) UIButton *flipButton;

/** 旋转缩放参考点 */
@property (nonatomic, assign) CGPoint originalPoint;
/** 视图初始size */
@property (nonatomic, assign) CGSize originalSize;
/** 记录上一个控制点 */
@property (nonatomic, assign) CGPoint lastCtrlPoint;

@property (nonatomic, assign) EditElementAction supportActions;

// 点击手势 - 选中
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
// 捏合手势 - 缩放
@property (nonatomic, strong) UIPinchGestureRecognizer *pinchGesture;
// 旋转手势
@property (nonatomic, strong) UIRotationGestureRecognizer *rotateGesture;

@end

@implementation HYHAddImageView

- (instancetype)init{
    if (self = [super init]) {
        [self createSubview];
//        [self setupData];
    }
    return self;
}

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

- (void)createSubview {
    [self addSubview:self.contentView];
    
    if ([self supportEditActions] & EditElementActionNone) {
        self.userInteractionEnabled = false;
    }
    
    if ([self supportEditActions] & EditElementActionDelete) {
        self.userInteractionEnabled = true;
        [self addSubview:self.removeButton];
        [self.removeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(40);
            make.height.mas_equalTo(40);
            make.top.left.mas_equalTo(0);
        }];
    }
    
    if ([self supportEditActions] & EditElementActionFlip) {
        self.userInteractionEnabled = true;
        [self addSubview:self.flipButton];
        [self.flipButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(40);
            make.height.mas_equalTo(40);
            make.top.right.mas_equalTo(0);
        }];
    }
    
    if ([self supportEditActions] & EditElementActionScale) {
        self.userInteractionEnabled = true;
        [self addSubview:self.rotateCtrl];
        [self.rotateCtrl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(40);
            make.height.mas_equalTo(40);
            make.bottom.right.mas_equalTo(0);
        }];
    }
    
    CGFloat space = EditElement_Inset;
    if ([self supportEditActions] == EditElementActionNone) {
        space = 0;
    }
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(space);
        make.bottom.right.mas_equalTo(-space);
    }];
    
    if ([self supportEditActions] & EditElementActionClick) {
        self.userInteractionEnabled = true;
        [self addGestureRecognizer:self.tapGesture];
    }
}

- (void)setupData {
    if (self.originalSize.width != 0 && self.originalSize.height != 0) {
        return;
    }
    //参考点默认为视图中心，point值为中心点比例
    self.originalPoint = CGPointMake(0.5, 0.5);
    self.originalSize = self.frame.size;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self setupData];
}

- (EditElementAction)supportEditActions {
    return EditElementActionAll;
}

- (CGFloat)minimumScaleRatio {
    return 0.3;
}

#pragma mark - === 手势操作 ===
- (BOOL)shouldScaleToSize:(CGSize)targetSize {
    if (targetSize.width < self.originalSize.width*self.minimumScaleRatio || 
        targetSize.height < self.originalSize.height*self.minimumScaleRatio) {
        return NO;
    }
    return YES;
}

- (void)rotateAction:(UIRotationGestureRecognizer *)rotateGesture {
    NSUInteger touchCount = rotateGesture.numberOfTouches;
    if (touchCount <= 1) {
        return;
    }
    [self movingGestureChanged:rotateGesture.state];
    
    CGPoint p1 = [rotateGesture locationOfTouch: 0 inView:self];
    CGPoint p2 = [rotateGesture locationOfTouch: 1 inView:self];
    CGPoint newCenter = CGPointMake((p1.x+p2.x)/2,(p1.y+p2.y)/2);
    self.originalPoint = CGPointMake(newCenter.x/self.bounds.size.width, newCenter.y/self.bounds.size.height);
    
    CGPoint oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = oPoint;
    
    self.transform = CGAffineTransformRotate(self.transform, rotateGesture.rotation);
    rotateGesture.rotation = 0;
    
    oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = CGPointMake(self.center.x + (self.center.x - oPoint.x),
                              self.center.y + (self.center.y - oPoint.y));
}

- (void)pinchAction:(UIPinchGestureRecognizer *)pinchGesture {
    NSUInteger touchCount = pinchGesture.numberOfTouches;
    if (touchCount <= 1) {
        return;
    }
    [self movingGestureChanged:pinchGesture.state];
    
    CGPoint p1 = [pinchGesture locationOfTouch: 0 inView:self];
    CGPoint p2 = [pinchGesture locationOfTouch: 1 inView:self];
    CGPoint newCenter = CGPointMake((p1.x+p2.x)/2,(p1.y+p2.y)/2);
    self.originalPoint = CGPointMake(newCenter.x/self.bounds.size.width, newCenter.y/self.bounds.size.height);
    
    CGPoint oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = oPoint;
    
    CGFloat scale = pinchGesture.scale;
    
    if (scale < 1 && ![self shouldScaleToSize:self.frame.size]) {
        // 当缩小到最小值时，停止缩小
    }else{
        self.transform = CGAffineTransformScale(self.transform, scale, scale);
        [self fitCtrlScaleX:scale scaleY:scale];
    }
    
    oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = CGPointMake(self.center.x + (self.center.x - oPoint.x),
                              self.center.y + (self.center.y - oPoint.y));
    pinchGesture.scale = 1;
}

- (void)tapGestureAction:(UITapGestureRecognizer *)tapGesture {
    if (self.setEditBlock) {
        self.setEditBlock();
    }
    self.isEditing = YES;
}

- (void)movingGestureChanged:(UIGestureRecognizerState)state {
    switch (state) {
        case UIGestureRecognizerStateBegan:
            if (self.beginMovingBlock) {
                self.beginMovingBlock();
            }
            break;
        case UIGestureRecognizerStateEnded:
            if (self.endMovingBlock) {
                self.endMovingBlock();
            }
            break;
        default:
            break;
    }
}

#pragma mark - === 视图控制按钮 手势事件 ===

//缩放旋转
- (void)rotateCtrlPanGesture:(UIPanGestureRecognizer *)panGesture{
    if (panGesture.state == UIGestureRecognizerStateBegan) {
        self.lastCtrlPoint = [self convertPoint:self.rotateCtrl.center toView:self.superview];
        return;
    }
    
    if (panGesture.state == UIGestureRecognizerStateEnded) {
        return;
    }

    CGPoint ctrlPoint = [panGesture locationInView:self.superview];
    [self scaleViewWithCtrlPoint:ctrlPoint];
    [self rotateViewWithCtrlPoint:ctrlPoint];
    self.lastCtrlPoint = ctrlPoint;
    
    [self movingGestureChanged:panGesture.state];
}

//移除视图
- (void)removeButtonClick:(UIButton *)sender {
    if (self.removeViewBlock) {
        self.removeViewBlock();
    }
    [self removeFromSuperview];
}

//移除视图
- (void)flipButtonClick:(UIButton *)sender {
    self.contentView.transform3D = CATransform3DRotate(self.contentView.transform3D, M_PI, 0, 1, 0);
}

#pragma mark - === 旋转 ===

- (void)rotateViewWithCtrlPoint:(CGPoint)ctrlPoint {
    
    CGPoint oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = CGPointMake(self.center.x - (self.center.x - oPoint.x),
                              self.center.y - (self.center.y - oPoint.y));
    
    
    float angle = atan2(self.center.y - ctrlPoint.y, ctrlPoint.x - self.center.x);
    float lastAngle = atan2(self.center.y - self.lastCtrlPoint.y, self.lastCtrlPoint.x - self.center.x);
    angle = - angle + lastAngle;
    self.transform = CGAffineTransformRotate(self.transform, angle);
    
    
    oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = CGPointMake(self.center.x + (self.center.x - oPoint.x),
                              self.center.y + (self.center.y - oPoint.y));
}

#pragma mark - === 缩放 ===

/* 等比缩放 */
- (void)scaleViewWithCtrlPoint:(CGPoint)ctrlPoint {
    CGPoint oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = oPoint;
    
    //上一个控制点距离中心的距离
    CGFloat preDistance = [self distanceWithStartPoint:self.center endPoint:self.lastCtrlPoint];
    //当前控制点距离中心的距离
    CGFloat newDistance = [self distanceWithStartPoint:self.center endPoint:ctrlPoint];
    CGFloat scale = newDistance / preDistance;
    
    NSLog(@"%f - %f", scale, self.frame.size.width);
    if (scale < 1 && ![self shouldScaleToSize:self.frame.size]) {
        //当缩小到最小值时，停止缩小
    }else{
        self.transform = CGAffineTransformScale(self.transform, scale, scale);
        [self fitCtrlScaleX:scale scaleY:scale];
    }
    
    oPoint = [self convertPoint:[self getRealOriginalPoint] toView:self.superview];
    self.center = CGPointMake(self.center.x + (self.center.x - oPoint.x),
                              self.center.y + (self.center.y - oPoint.y));
}

#pragma mark - private

/* 控制按钮保持大小不变 */
- (void)fitCtrlScaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY {
    self.removeButton.transform = CGAffineTransformScale(self.removeButton.transform, 1/scaleX, 1/scaleY);
    self.rotateCtrl.transform = CGAffineTransformScale(self.rotateCtrl.transform, 1/scaleX, 1/scaleY);
    self.flipButton.transform = CGAffineTransformScale(self.flipButton.transform, 1/scaleX, 1/scaleY);
}

/* 计算两点间距 */
- (CGFloat)distanceWithStartPoint:(CGPoint)start endPoint:(CGPoint)end {
    CGFloat x = start.x - end.x;
    CGFloat y = start.y - end.y;
    return sqrt(x * x + y * y);
}

/** 获取参考点坐标 */
- (CGPoint)getRealOriginalPoint {
    return CGPointMake(self.bounds.size.width * self.originalPoint.x,
                       self.bounds.size.height * self.originalPoint.y);
}

#pragma mark - UIGestureRecognizerDelegate

/* 同时触发多个手势 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

/* 当点击旋转控制按钮时，禁止全图平移手势 */
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (gestureRecognizer.view == self) {
        CGPoint p = [touch locationInView:self];
        if (CGRectContainsPoint(self.rotateCtrl.frame, p)) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - setter

- (void)setIsEditing:(BOOL)isEditing {
    _isEditing = isEditing;
    if (isEditing) {
        self.removeButton.hidden = NO;
        self.rotateCtrl.hidden = NO;
        self.flipButton.hidden = NO;
        // 暂时取消双指操作
        if ([self supportEditActions] & EditElementActionScale) {
            if (![self.gestureRecognizers containsObject:self.pinchGesture]) {
                [self addGestureRecognizer:self.pinchGesture];
            }
            if (![self.gestureRecognizers containsObject:self.rotateGesture]) {
                [self addGestureRecognizer:self.rotateGesture];
            }
        }
    }else{
        self.removeButton.hidden = YES;
        self.rotateCtrl.hidden = YES;
        self.flipButton.hidden = YES;
        if ([self.gestureRecognizers containsObject:self.pinchGesture]) {
            [self removeGestureRecognizer:self.pinchGesture];
        }
        if ([self.gestureRecognizers containsObject:self.rotateGesture]) {
            [self removeGestureRecognizer:self.rotateGesture];
        }
    }
    [self setNeedsDisplay];
}

#pragma mark - getter

- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] initWithFrame: CGRectZero];
        _contentView.clipsToBounds = YES;
    }
    return _contentView;
}

- (UIButton *)removeButton {
    if (_removeButton == nil) {
        _removeButton = [[UIButton alloc] init];
        [_removeButton addTarget:self action:@selector(removeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
        iv.image = [UIImage imageNamed:@"ic-diy-op-delete"];
        [_removeButton addSubview:iv];
    }
    return  _removeButton;
}

- (UIButton *)flipButton {
    if (_flipButton == nil) {
        _flipButton = [[UIButton alloc] init];
        [_flipButton addTarget:self action:@selector(flipButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *iv = [[UIImageView alloc] init];
        iv.image = [UIImage imageNamed:@"ic-diy-op-flip"];
        [_flipButton addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(24);
            make.height.mas_equalTo(24);
            make.top.right.mas_equalTo(0);
        }];
    }
    return _flipButton;
}

- (UIImageView *)rotateCtrl{
    if (_rotateCtrl == nil) {
        _rotateCtrl = [[UIImageView alloc]init];
        _rotateCtrl.userInteractionEnabled = YES;
        _rotateCtrl.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(rotateCtrlPanGesture:)];
        [_rotateCtrl addGestureRecognizer:panGesture];
        
        UIImageView *iv = [[UIImageView alloc] init];
        iv.image = [UIImage imageNamed:@"ic-diy-op-scale"];
        [_rotateCtrl addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(24);
            make.height.mas_equalTo(24);
            make.bottom.right.mas_equalTo(0);
        }];
    }
    return _rotateCtrl;
}

- (UIRotationGestureRecognizer *)rotateGesture {
    if (_rotateGesture == nil) {
        _rotateGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotateAction:)];
        _rotateGesture.delegate = self;
    }
    return _rotateGesture;
}

- (UIPinchGestureRecognizer *)pinchGesture {
    if (_pinchGesture == nil) {
        _pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
        _pinchGesture.delegate = self;
    }
    return _pinchGesture;
}

- (UITapGestureRecognizer *)tapGesture {
    if (_tapGesture == nil) {
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
//        _tapGesture.delegate = self;
    }
    return _tapGesture;
}

@end
