//
//  ALHomePortiraitCardCell.m
//  GMAlpha
//
//  Created by zhb on 2018/11/16.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALHomePortiraitCardCell.h"
#import <SceneKit/SceneKit.h>
#import "ALMatchingModel.h"
#import "FileUtils.h"

@interface ALHomePortiraitCardCell()
// 3D 提示模型
@property(nonatomic,strong) SCNView * headscnview;
@property(nonatomic,assign) BOOL customAnimation;
@property (nonatomic, strong) UIImage *defaultImage;
@property (nonatomic, assign) BOOL isShowDefaultImage;
@property (nonatomic, strong) ALMatchingModel *model;
@end
@implementation ALHomePortiraitCardCell
-(void)prepareForReuse {
    [super prepareForReuse];
    _customAnimation = NO;
    _isShowDefaultImage = YES;
}
- (void)setCardObj:(ALHomePortiraitObject *)cardObj {
    if (cardObj == nil) return;
    _cardObj = cardObj;
    [self.imageView setImageWithUrlString:cardObj.image.url placeHolder:@"banner_model"];
    [self setupCapturePromoteView];
    [self setCustomAnimation:YES];
}
//加载自己的模型
- (ALMatchingModel *)getMy3DHeadSourceModel {
    ALMatchingModel *model = [[ALMatchingModel alloc] init];
    if (ALScanManager.shareInstance.fitting3DInfo) {
        model.sourceOBJFile = [ALScanManager.shareInstance.fitting3DInfo getOBJFile]; //存本地
        model.sourceMeshFile = [ALScanManager.shareInstance.fitting3DInfo getMeshFile]; //存本地
        self.isShowDefaultImage = NO;
    } else if (ALScanManager.shareInstance.show3DInfo) {
        model.sourceOBJFile = [ALScanManager.shareInstance.show3DInfo getOBJFile]; //存本地
        model.sourceMeshFile = [ALScanManager.shareInstance.show3DInfo getMeshFile]; //存本地
        self.isShowDefaultImage = NO;
    } else {
        self.isShowDefaultImage = YES;
    }
    return model;
}
- (void)setIsShowDefaultImage:(BOOL)isShowDefaultImage {
    _isShowDefaultImage = isShowDefaultImage;
    if (isShowDefaultImage) {
        self.headscnview.hidden = YES;
    } else {
        self.headscnview.hidden = NO;
    }
}

- (void)setupCapturePromoteView {
    self.headscnview = [[SCNView alloc] init];
    self.headscnview.backgroundColor = UIColor.blackColor;
    _headscnview.frame = CGRectMake(0, 0, (MAINSCREEN_WIDTH-30)/2, (MAINSCREEN_WIDTH-30)/2);
    [self.contentView addSubview:_headscnview];
    _model = [self getMy3DHeadSourceModel];
    
    if (!_isShowDefaultImage) {
        self.headscnview.scene = [self loadSCNScene];
    }
}


- (void)setCustomAnimation:(BOOL)customAnimation
{
    @synchronized (self) {
        if(_customAnimation != customAnimation){
            _customAnimation = customAnimation;
            if(_customAnimation){
                SCNAction * action = [self createSCNAction:2.5];//2.5s
                [self.headscnview.scene.rootNode runAction:[SCNAction repeatActionForever:action]];
            } else {
                [self.headscnview.scene.rootNode removeAllActions];
            }
        }
    }
}

//////////////////////////////////////////////////////////////////
- (SCNAction *) createSCNAction:(float) duration
{
    SCNAction * middle_left = [self createSCNAction:-0.3 duration:duration];
    SCNAction * left_middle = [self createSCNAction:0.3 duration:duration];
    SCNAction * middle_right = [self createSCNAction:0.3 duration:duration];
    SCNAction * right_middle = [self createSCNAction:-0.3 duration:duration];
    return [SCNAction sequence:@[middle_left,left_middle,middle_right,right_middle]];
}

- (SCNAction *) createSCNAction:(float) y duration:(float)duration
{
    return [SCNAction rotateByX:0 y:y z:0 duration:duration];
}

- (SCNScene *) loadSCNScene
{
    ALMatchingModel *model = [self getMy3DHeadSourceModel];
    SCNScene *scene = [SCNScene sceneWithURL:[NSURL fileURLWithPath:model.sourceOBJFile]
                                     options:nil error:nil];//[SCNScene sceneNamed:@"art.scnassets/animationhead.obj"];
    SCNNode * head = scene.rootNode.childNodes[0];
    head.geometry.firstMaterial.lightingModelName = SCNLightingModelBlinn;
    head.geometry.firstMaterial.diffuse.contents  = model.sourceMeshFile;
    SCNVector3 position = head.position;
    head.position = SCNVector3Make(position.x , position.y + 20, position.z);
    [self scaleSCNNode:scene.rootNode byScale:0.8];
    return scene;
}
- (void) scaleSCNNode:(SCNNode *) node byScale:(float)scalevalue
{
    node.scale = SCNVector3Make(node.scale.x * scalevalue, node.scale.y * scalevalue, node.scale.z * scalevalue);
}
- (SCNNode *) createLightSCNNode
{
    SCNNode *lightNode = [SCNNode node];
    lightNode.light = [SCNLight light];
    lightNode.light.color = UIColor.whiteColor; // initially switched off
    lightNode.light.type = SCNLightTypeDirectional;
    return lightNode;
}
- (void)setup {
    [super setup];
    self.backgroundColor = UIColor.grayColor;
    self.layer.cornerRadius = 5;
    self.layer.masksToBounds = YES;
    [self.contentView addSubview:self.imageView];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.mas_equalTo(0);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedMe:)];
    [self addGestureRecognizer:tap];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMatchingObj) name:kcapture3DModelAndStartModelSuccess object:nil];
}

-(void)refreshMatchingObj {
    //先获取自己的模型
    _model = [self getMy3DHeadSourceModel];
    _isShowDefaultImage = YES;
    [self setCustomAnimation:NO];
    self.headscnview.scene = [self loadSCNScene];
    [self setCustomAnimation:YES];
    [ALScanManager.shareInstance.capture3Dvc.captureview viewDidDisappear:YES];
}
#pragma mark - 事件
- (void)clickedMe:(UITapGestureRecognizer *)tap {
    if ([self.delegate respondsToSelector:@selector(portiratieCardCellDidSelected:)]) {
        [self.delegate portiratieCardCellDidSelected:self];
    }
}

#pragma mark - getter
- (GMImageView *)imageView {
    if (!_imageView) {
        _imageView = [[GMImageView alloc] init];
        _imageView.userInteractionEnabled = YES;
    }
    return _imageView;
}

- (UIImage *)defaultImage {
    if (_defaultImage == nil) {
        _defaultImage = [UIImage imageWithColor:RGBCOLOR_HEX(0xF4F3F8)];
    }
    return _defaultImage;
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
