//
//  FecViewLayoutHelper.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2023/9/2.
//  Copyright © 2023 hikvision. All rights reserved.
//

#import "FecViewLayoutHelper.h"
#import "EZDeviceInfo.h"

#define ZOOM_ACCURACY 0.005f // 放缩精度

@interface FecViewLayoutHelper () {
    NSLayoutConstraint *newConstraint;

    UIView *previousPlayView;///< 记录全景五分屏下点击的分屏
    
    EZFecPlaceType fecPlaceType;
    EZFecCorrectType fecCorrectType;
}

@end

@implementation FecViewLayoutHelper

#pragma mark - public method

/** 打开鱼眼矫正 */
- (void)openFecCorrect:(EZFecCorrectType)fecCorrectType fecPlaceType:(EZFecPlaceType)fecPlaceType {
    // 1.缓存fecPlaceType & fecCorrectType
    self->fecPlaceType = fecPlaceType;
    self->fecCorrectType = fecCorrectType;
    // 2.UI布局调整
    [self layoutViewsForFec];
    // 3.设置对应的子视图
    [self.player setFecPlayViews:[self fecPlayViews]];
    // 4.重新设置矫正模式
    [self.player openFecCorrect:fecCorrectType fecPlaceType:fecPlaceType];
}

/** 画面比例调整为1:1 */
- (void)setPlayViewAspectRadioWith1V1 {
    NSLayoutConstraint *oldConstraint = self.playerViewAspectContraint;
    if (!newConstraint) {
        CGFloat newMultiplier = 1;
        newConstraint = [NSLayoutConstraint constraintWithItem:oldConstraint.firstItem attribute:oldConstraint.firstAttribute relatedBy:oldConstraint.relation toItem:oldConstraint.secondItem attribute:oldConstraint.secondAttribute multiplier:newMultiplier constant:oldConstraint.constant];
        newConstraint.priority = oldConstraint.priority;
    }
    [self.scrollView removeConstraint:oldConstraint];
    [self.scrollView addConstraint:newConstraint];
}

/** 画面比例调整为16:9 */
- (void)setPlayViewAspectRadioWith16V9 {
    [self.scrollView removeConstraint:newConstraint];
    [self.scrollView addConstraint:self.playerViewAspectContraint];
}

+ (BOOL)isFecDevice:(EZDeviceInfo *)deviceInfo {
    BOOL supportWallType = [FecViewLayoutHelper getSupportInt:EZFecPlaceTypeWall deviceInfo:deviceInfo] > 0;
    BOOL supportFloorType = [FecViewLayoutHelper getSupportInt:EZFecPlaceTypeFloor deviceInfo:deviceInfo] > 0;
    BOOL supportCeilingType = [FecViewLayoutHelper getSupportInt:EZFecPlaceTypeCeiling deviceInfo:deviceInfo] > 0;
    // 顶装、壁装、底装都不支持的话隐藏"查看模式"，只有鱼眼设备支持这几种安装方式
    BOOL isFecDevice = supportWallType || supportFloorType || supportCeilingType;
    
    return isFecDevice;
}

+ (int)getSupportInt:(EZFecPlaceType)fecPlaceType deviceInfo:(EZDeviceInfo *)deviceInfo {
    /**
     能力集312位 : 顶装矫正模式
     能力集313位 : 壁装矫正模式
     能力集666位 : 底装矫正模式
     */
    int supportValue = 0;
    if (fecPlaceType == EZFecPlaceTypeCeiling) {
        supportValue = [deviceInfo getSupportInt:312];
    } else if (fecPlaceType == EZFecPlaceTypeWall) {
        supportValue = [deviceInfo getSupportInt:313];
    } else if (fecPlaceType == EZFecPlaceTypeFloor) {
        supportValue = [deviceInfo getSupportInt:666];
    }
    
    return supportValue;
}

/** 根据能力值设置各种矫正模式按钮的状态 */
+ (void)setFecCorrectButtonsState:(NSArray<UIButton *> *)buttons supportValue:(int)supportValue {
    for (int i = 0; i < buttons.count; i ++) {
        UIButton *button = buttons[i];
        EZFecCorrectType correctType = (EZFecCorrectType)button.tag;
        BOOL enable = supportValue & correctType;// &运算判断是否支持该矫正模式，多种矫正模式已通过二进制的方式配置在平台配置好了
        
        button.enabled = enable;
        button.backgroundColor = enable ? HEXColor(0xC6C6C8) : HEXColor(0xE5E5EA);
        [button setTitleColor:enable ? [UIColor blackColor] : [UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}

#pragma mark - 不同矫正模式布局调整

/** 根据矫正模式返回对应需要的分屏 */
- (NSArray<UIView *> *)fecPlayViews {
    switch (fecCorrectType) {
        case EZFecCorrectType180:
        case EZFecCorrectType360:
        case EZFecCorrectTypeCYC:
        case EZFecCorrectTypeARC_Hor:
        case EZFecCorrectTypeLAT:
        case EZFecCorrectTypeWideAngle:
            return @[self.ptz1PlayView];
        case EZFecCorrectType4PTZ:
            return @[self.ptz1PlayView, self.ptz2PlayView, self.ptz3PlayView, self.ptz4PlayView];
        case EZFecCorrectType5PTZ:
            return @[self.ptz1PlayView, self.ptz2PlayView, self.ptz3PlayView, self.ptz4PlayView, self.ptz5PlayView];
        case EZFecCorrectTypeFull5PTZ:
            return @[self.ptz1PlayView, self.ptz2PlayView, self.ptz3PlayView, self.ptz4PlayView, self.ptz5PlayView, self.ptz6PlayView];
        default:
            return nil;
    }
}

/** 根据矫正模式调整分屏布局 */
- (void)layoutViewsForFec {
    self.playerView.hidden = fecCorrectType != EZFecCorrectTypeFish;// 不是默认的鱼眼模式，都要隐藏主视图
    if (previousPlayView) {// 清空全景五分屏下选中的视图的状态
        previousPlayView.layer.borderColor = [UIColor clearColor].CGColor;
        previousPlayView.layer.borderWidth = 1.f;
    }
    // 子视图布局调整
    if (fecCorrectType == EZFecCorrectTypeFish) {
        [self setPlayViewAspectRadioWith1V1];
        [self setAllFecPlayViewsHidden];
    } else if (fecCorrectType == EZFecCorrectType180 || fecCorrectType == EZFecCorrectTypeARC_Hor || fecCorrectType == EZFecCorrectTypeLAT) {
        [self layoutViewsFor1PTZ1V1];
    } else if (fecCorrectType == EZFecCorrectType360 || fecCorrectType == EZFecCorrectTypeWideAngle || fecCorrectType == EZFecCorrectTypeCYC) {
        [self layoutViewsFor1PTZ16V9];
    } else if (fecCorrectType == EZFecCorrectType4PTZ) {
        [self layoutViewsFor4PTZ];
    } else if (fecCorrectType == EZFecCorrectType5PTZ) {
        [self layoutViewsFor5PTZ];
    } else if (fecCorrectType == EZFecCorrectTypeFull5PTZ) {
        [self layoutViewsForFull5PTZ];
    }
}

- (void)layoutViewsFor4PTZ {
    [self setPlayViewAspectRadioWith1V1];
    [self setAllFecPlayViewsHidden];
    self.ptz1PlayView.hidden = NO;
    self.ptz2PlayView.hidden = NO;
    self.ptz3PlayView.hidden = NO;
    self.ptz4PlayView.hidden = NO;
    
    [self.ptz1PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.playerView);
        make.right.equalTo(self.playerView.mas_centerX);
        make.bottom.equalTo(self.playerView.mas_centerY);
    }];
    [self.ptz2PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.top.equalTo(self.playerView);
        make.left.equalTo(self.playerView.mas_centerX);
        make.bottom.equalTo(self.playerView.mas_centerY);
    }];
    [self.ptz3PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(self.playerView);
        make.top.equalTo(self.playerView.mas_centerY);
        make.right.equalTo(self.playerView.mas_centerX);
    }];
    [self.ptz4PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.playerView);
        make.top.equalTo(self.playerView.mas_centerY);
        make.left.equalTo(self.playerView.mas_centerX);
    }];
}

- (void)layoutViewsFor5PTZ {
    [self setPlayViewAspectRadioWith1V1];
    [self setAllFecPlayViewsHidden];
    self.ptz1PlayView.hidden = NO;
    self.ptz2PlayView.hidden = NO;
    self.ptz3PlayView.hidden = NO;
    self.ptz4PlayView.hidden = NO;
    self.ptz5PlayView.hidden = NO;
    
    float smallWidth = kScreenWidth/3;// 较小的视图宽度
    float margin = (kScreenWidth - smallWidth - smallWidth *1.5) * 0.5;
    [self.ptz1PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playerView);
        make.top.equalTo(self.playerView).offset(margin);
        make.right.equalTo(self.playerView.mas_centerX);
        make.height.equalTo(self.ptz1PlayView.mas_width);
    }];
    [self.ptz2PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.playerView);
        make.top.equalTo(self.ptz1PlayView);
        make.left.equalTo(self.playerView.mas_centerX);
        make.height.equalTo(self.ptz1PlayView.mas_width);
    }];
    [self.ptz3PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playerView);
        make.top.equalTo(self.ptz1PlayView.mas_bottom);
        make.width.height.mas_equalTo(smallWidth);
    }];
    [self.ptz4PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.ptz3PlayView.mas_right);
        make.top.equalTo(self.ptz3PlayView);
        make.width.height.mas_equalTo(smallWidth);
    }];
    [self.ptz5PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.ptz4PlayView.mas_right);
        make.top.equalTo(self.ptz3PlayView);
        make.width.height.mas_equalTo(smallWidth);
    }];
}

- (void)layoutViewsForFull5PTZ {
    [self setPlayViewAspectRadioWith1V1];
    self.ptz1PlayView.hidden = NO;
    self.ptz2PlayView.hidden = NO;
    self.ptz3PlayView.hidden = NO;
    self.ptz4PlayView.hidden = NO;
    self.ptz5PlayView.hidden = NO;
    self.ptz6PlayView.hidden = NO;
    float width = kScreenWidth/3;// 较小的视图宽度
    [self.ptz1PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playerView);
        make.top.equalTo(self.playerView);
        make.width.mas_equalTo(width*2);
        make.height.equalTo(self.ptz1PlayView.mas_width);
    }];
    [self.ptz2PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.playerView);
        make.top.equalTo(self.playerView);
        make.width.height.mas_equalTo(width);
    }];
    [self.ptz3PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.playerView);
        make.top.equalTo(self.ptz2PlayView.mas_bottom);
        make.width.height.mas_equalTo(width);
    }];
    [self.ptz4PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.playerView);
        make.top.equalTo(self.ptz3PlayView.mas_bottom);
        make.width.height.mas_equalTo(width);
    }];
    [self.ptz5PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.ptz4PlayView.mas_left);
        make.top.equalTo(self.ptz4PlayView);
        make.width.height.mas_equalTo(width);
    }];
    [self.ptz6PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.ptz5PlayView.mas_left);
        make.top.equalTo(self.ptz5PlayView);
        make.width.height.mas_equalTo(width);
    }];
}

/** 显示1个分屏 & 画面比例调整为1:1 */
- (void)layoutViewsFor1PTZ1V1 {
    [self setPlayViewAspectRadioWith1V1];
    [self setAllFecPlayViewsHidden];
    self.ptz1PlayView.hidden = NO;
    [self.ptz1PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.playerView);
    }];
}

/** 显示1个分屏 & 画面比例调整为16:9 */
- (void)layoutViewsFor1PTZ16V9 {
    [self setPlayViewAspectRadioWith16V9];
    [self setAllFecPlayViewsHidden];
    self.ptz1PlayView.hidden = NO;
    [self.ptz1PlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.playerView);
    }];
}

/** 所有的子视图都不显示 */
- (void)setAllFecPlayViewsHidden {
    self.ptz1PlayView.hidden = YES;
    self.ptz2PlayView.hidden = YES;
    self.ptz3PlayView.hidden = YES;
    self.ptz4PlayView.hidden = YES;
    self.ptz5PlayView.hidden = YES;
    self.ptz6PlayView.hidden = YES;
}

#pragma mark - Gestures

- (void)panGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint currentPoint = [gestureRecognizer locationInView:gestureRecognizer.view];
    CGPoint currentPosition = CGPointMake(currentPoint.x / CGRectGetWidth(gestureRecognizer.view.bounds),
                                          currentPoint.y / CGRectGetHeight(gestureRecognizer.view.bounds));
    CGPoint position = [gestureRecognizer translationInView:gestureRecognizer.view];
    CGPoint point = [self isARCCorrectMode:fecCorrectType] ? position : currentPosition;
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
        {
            [_player panGestureWith:UIGestureRecognizerStateBegan point:point gestureRecognizer:gestureRecognizer];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_player panGestureWith:UIGestureRecognizerStateChanged point:point gestureRecognizer:gestureRecognizer];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [_player panGestureWith:UIGestureRecognizerStateEnded point:point gestureRecognizer:gestureRecognizer];
        }
            break;
        default:
            break;
    }
    if ([self isARCCorrectMode:fecCorrectType]) {
        [gestureRecognizer setTranslation:CGPointMake(0, 0) inView:gestureRecognizer.view];
    }
}

- (void)pinchGestureRecognizer:(UIPinchGestureRecognizer *)gestureRecognizer {
    float zoomAccuracy = 0;
    if (gestureRecognizer.scale < 1) {
        zoomAccuracy = -ZOOM_ACCURACY;
    } else if (gestureRecognizer.scale > 1) {
        zoomAccuracy = ZOOM_ACCURACY;
    }
    float zoom = [self isARCCorrectMode:fecCorrectType] ? gestureRecognizer.scale : zoomAccuracy;
    
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
        {
            [_player pinGestureWith:gestureRecognizer.state zoom:zoom gestureRecognizer:gestureRecognizer];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_player pinGestureWith:gestureRecognizer.state zoom:zoom gestureRecognizer:gestureRecognizer];
        }
            break;
        default:
            break;
    }
    if ([self isARCCorrectMode:fecCorrectType]) {
        gestureRecognizer.scale = 1.0;
    }
}

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.view == self.ptz1PlayView) {// 全景五分屏第一个视图不能点击
        return;
    }
    // 上一个选中的视图选中状态清除
    if (previousPlayView) {
        previousPlayView.layer.borderColor = [UIColor clearColor].CGColor;
        previousPlayView.layer.borderWidth = 1.f;
    }
    BOOL isSupportTap = [_player tapGestureWith:gestureRecognizer];
    if (isSupportTap) {// 是全景五分屏支持点击，设置为选中状态
        gestureRecognizer.view.layer.borderColor = [UIColor whiteColor].CGColor;
        gestureRecognizer.view.layer.borderWidth = 1.f;
        previousPlayView = gestureRecognizer.view;
    } else if (!isSupportTap && gestureRecognizer.view == previousPlayView) {// 两次点击的是同一个视图，反选
        previousPlayView = nil;
    } else {

    }
    
}

#pragma mark - private method

- (BOOL)isARCCorrectMode:(EZFecCorrectType)fecCorrectType {
    if (fecCorrectType == EZFecCorrectTypeARC_Hor ||
        fecCorrectType == EZFecCorrectTypeARC_Ver ||
        fecCorrectType == EZFecCorrectTypeWideAngle ||
        fecCorrectType == EZFecCorrectTypeCYC) {
        return YES;
    }
    return NO;
}

#pragma mark - 懒加载

- (UIView *)ptz1PlayView {
    if (!_ptz1PlayView) {
        _ptz1PlayView = [self createPtzPlayView];
    }
    return _ptz1PlayView;
}
- (UIView *)ptz2PlayView {
    if (!_ptz2PlayView) {
        _ptz2PlayView = [self createPtzPlayView];
    }
    return _ptz2PlayView;
}
- (UIView *)ptz3PlayView {
    if (!_ptz3PlayView) {
        _ptz3PlayView = [self createPtzPlayView];
    }
    return _ptz3PlayView;
}
- (UIView *)ptz4PlayView {
    if (!_ptz4PlayView) {
        _ptz4PlayView = [self createPtzPlayView];
    }
    return _ptz4PlayView;
}
- (UIView *)ptz5PlayView {
    if (!_ptz5PlayView) {
        _ptz5PlayView = [self createPtzPlayView];
    }
    return _ptz5PlayView;
}

- (UIView *)ptz6PlayView {
    if (!_ptz6PlayView) {
        _ptz6PlayView = [self createPtzPlayView];
    }
    return _ptz6PlayView;
}

- (UIView *)createPtzPlayView {
    UIView *ptzPlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    [ptzPlayView addGestureRecognizer:({
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
        tapGesture;
    })];
    [ptzPlayView addGestureRecognizer:({
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
        panGesture;
    })];
    [ptzPlayView addGestureRecognizer:({
        UIPinchGestureRecognizer *gesure = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureRecognizer:)];
        gesure;
    })];
    
    return ptzPlayView;
}

@end
