//
//  ALUnre2DViewController.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/28.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALUnre2DViewController.h"
#import <Unre2DScanLib/U2DHeadScanner.h>
#import <Unre2DScanLib/U2DHeadNetModel.h>
#import <Unre2DScanLib/U2DHeadSimilarity.h>
#import <SceneKit/SceneKit.h>
#import "AL3DCaptureReminderView.h"
#import "Unre3DAR3DCaptureImpl.h"
#import "AudioPlayUtils.h"
#import "AppDelegate+ViewControl.h"
#import "ALScanFaceCompleteViewController.h"

#import "ALScanManager.h"
#import "ALUpLoadManager.h"
#import "ALFaceSDK.H"
#import "ALCaptureUtils.h"
#import "AL2DCaptureInfo.h"
#import "ALScanPlayerView.h"
#import "ALFaceFittingManager.h"

static int const TAG_CAPTURE_IMAGE_VIEW_OK = 2;
static int const TAG_CAPTURE_IMAGE_VIEW_FAIL = 3;
//const int SELECT_CONFIG_SUM = 7;
//int selectconfig[SELECT_CONFIG_SUM] = {0,0,0,0,0,0,0};

@interface ALUnre2DViewController ()

@property(nonatomic,strong) GMImageView *previewUIView;
@property(nonatomic,strong) GMImageView *captureFaceView;
@property(nonatomic,strong) UIButton *captureButton;

@property (nonatomic, strong) AL3DCaptureReminderView *bottomView;

@property (nonatomic, strong) U2DCamera *u2dCam;
//@property (nonatomic, strong) U3DHeadSimilarity *u3dSimilar;
@property (nonatomic, strong) U2DHeadScanner *u2dHeadScan;
@property (nonatomic, strong) U2DSessionData * u2dSession;

@property (nonatomic, strong) U2DHeadNetModel *u2dModel;
@property(nonatomic,assign) Unre2DHeadScannerScanHint lastUnre2DScanHint;
//@property(nonatomic,assign) Unre3DAR3DFAILHint lastUnre3DAR3DFAILHint;

// 3D 提示模型
@property(nonatomic,strong) SCNView * headscnview;

@property (nonatomic, assign) BOOL isPlayVideo;
@property (nonatomic, strong) ALFaceSDK *faceSDK;
/** 获取UV图的接口传回的数据 */
@property (nonatomic, copy) NSString *uvUrl;
/** netPath对应raw_similar_data */
@property (nonatomic, copy) NSString *netPath;
/** bmpPath对应pre_uv_url */
@property (nonatomic, copy) NSString *bmpPath;
/** 数据请求成功后获得的id */
@property (nonatomic, copy) NSString *resultId;
/** token */
@property (nonatomic, copy) NSString *token;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) ALCaptureUtils *captureUtils;
@end

@implementation ALUnre2DViewController

- (void)initController {
    [super initController];
    _isPlayVideo = YES;
    _captureUtils = [[ALCaptureUtils alloc] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"模拟";
    self.navigationBar.rightIcon = @"scan_3d_right";
    self.index = 0;
    //请求上传的token
    [self setup2DCameraView];
    [self setupUnre2DAR3DCapture];
    [self setupRemindBottomView];
    
    [self setupCapturePromoteView];
    [self setupStartButton];
    [self setupAudioButton];
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    ALScanPlayerView *playView = [[ALScanPlayerView alloc] init];
    [self.view addSubview:playView];
}

- (void)setupRemindBottomView {
    _bottomView = [[AL3DCaptureReminderView alloc] init];
    _bottomView.hidden = YES;
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(MAINSCREEN_WIDTH + OCNavigationBar.barHeight);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

//创建相机
- (void)setup2DCameraView {
    _previewUIView =[[GMImageView alloc] init];
    _previewUIView.contentMode = UIViewContentModeScaleAspectFill;
    _previewUIView.frame = CGRectMake(0, OCNavigationBar.barHeight, MAINSCREEN_WIDTH, MAINSCREEN_WIDTH);
    [self.view addSubview:_previewUIView];
    
    _captureFaceView = [[GMImageView alloc] init];
    _captureFaceView.image = [UIImage imageNamed:@"scan_ok"];
    _captureFaceView.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_WIDTH);
    [_previewUIView addSubview:_captureFaceView];
    [_previewUIView bringSubviewToFront:_captureFaceView];
}


- (void)setupUnre2DAR3DCapture {
    self.u2dCam = [[U2DCamera alloc] initWithVideoOrientation:Unre2DCameraVideoOrientationPortraitUp];
    if(!self.u2dCam.supportsCameraCapturing){
        return;
    }
    NSString *fittingId = ALScanManager.shareInstance.fittingId;
    if ([fittingId isNonEmpty]) {
        self.u2dSession = [[U2DSessionData alloc] initWithID:@"alphaCapture2D" error:nil];
    }  else {
        self.u2dSession = [[U2DSessionData alloc] initWithID:@"alphaCapture2D" error:nil];
    }
    self.captureUtils.u2dSession = self.u2dSession;
    self.u2dHeadScan = [[U2DHeadScanner alloc] initWithCamera:self.u2dCam sessionData:self.u2dSession];
    [self.u2dHeadScan addObserver:self];
    [self.u2dHeadScan startTracking];

}

//语音提示View
- (void)setupCapturePromoteView {
    self.headscnview = [[SCNView alloc] init];
    self.headscnview.hidden = YES;
    self.headscnview.backgroundColor = RGBCOLOR_HEX(0x262F3D);
    _headscnview.frame = CGRectMake(0, OCNavigationBar.barHeight, MAINSCREEN_WIDTH, MAINSCREEN_WIDTH);
    [self.view addSubview:_headscnview];
}

- (void)setupStartButton {
    _captureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _captureButton.frame = CGRectMake(MAINSCREEN_WIDTH/2-35, MAINSCREEN_WIDTH + 64 + OCNavigationBar.barHeight, 70, 70);
    [_captureButton setBackgroundImage:[UIImage imageNamed:@"unre_scan_start"] forState:UIControlStateNormal];
    [_captureButton addTarget:self action:@selector(onCapturePress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_captureButton];
}

- (void)onCapturePress {
    self.headscnview.hidden = NO;
    self.bottomView.hidden = NO;
    self.captureButton.hidden = YES;
    [self.view bringSubviewToFront:self.headscnview];
    [self loadAdminHead:YES];
    
    [self.u2dHeadScan startScanning];
}

- (void)setupAudioButton {
    UIButton *audioButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [audioButton addTarget:self action:@selector(closeAudio:) forControlEvents:UIControlEventTouchUpInside];
    [audioButton setBackgroundImage:[UIImage imageNamed:@"3d_audio_button"] forState:UIControlStateNormal];
    [audioButton setBackgroundImage:[UIImage imageNamed:@"3d_audio_butto_cl"] forState:UIControlStateSelected];
    [self.view addSubview:audioButton];
    [audioButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(OCNavigationBar.barHeight+20);
        make.right.mas_equalTo(-20);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(27);
    }];
    
    GMLabel *label = [GMLabel labelWithTextColor:UIColor.whiteColor fontSize:12];
    label.text = @"人声引导开关";
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(audioButton.mas_right);
        make.top.equalTo(audioButton.mas_bottom).offset(10);
    }];
}

- (void)closeAudio:(UIButton *)button {
    button.selected = !button.selected;
    _isPlayVideo = !button.selected;
}


- (void) viewDidAppear:(BOOL)animated
{
    //phone
    [super viewDidAppear:animated];
    //NSLog(@"[viewDidAppear]");
    if(self.u2dCam.supportsCameraCapturing){
        [self.u2dCam startStreaming:self.previewUIView];
    }
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    //NSLog(@"[viewDidDisappear]");
    if(self.u2dCam.supportsCameraCapturing){
        [self.u2dHeadScan cancelScaning];
        [self.u2dCam stopStreaming];
    }
}

//head Scanner
- (void)didProvideHint:(Unre2DHeadScannerScanHint)hint{
    
    if (hint == Unre2DHeadScannerScanHintCaptureCompleted) {
    } else {
        if(self.lastUnre2DScanHint != hint){
            [self notifyTurnHead:hint];
            if (_isPlayVideo) {
                [self playAudio:hint];
            }
            [self animationHead:hint];
            self.lastUnre2DScanHint = hint;//update lastUnre3DAR3DScanHint.
        }
    }
}
- (void) playAudio:(Unre2DHeadScannerScanHint) hint
{
    NSString * audiofile = nil;
    switch(hint){
        case Unre2DHeadScannerScanHintTurnHeadLeft:{
            audiofile = @"turnleft.mp3";
        }break;
        case Unre2DHeadScannerScanHintTurnHeadRight:{
            audiofile = @"turnright.mp3";
        }break;
        case Unre2DHeadScannerScanHintTurnHeadToTheMiddle:{
            audiofile = @"turnmiddle.mp3";
        }break;
        default: break;
    }
    if(audiofile){
        [AudioPlayUtils playSoundEffect:audiofile];
    }
}

- (void) notifyTurnHead:(Unre2DHeadScannerScanHint) hint
{
    NSString * facehint = @"";
    switch(hint){
        case Unre2DHeadScannerScanHintTurnHeadLeft:{
            facehint = @"请向左慢慢转头";
            self.index = -2;
        }break;
        case Unre2DHeadScannerScanHintTurnHeadRight:{
            facehint = @"请向右慢慢转头";
            self.index = 2;
        }break;
        case Unre2DHeadScannerScanHintTurnHeadToTheMiddle:{
            facehint = @"请转回中间";
            self.index = 0;
        }break;
        case Unre2DHeadScannerScanHintKeepHeadTurning:{
            facehint = @"请保持";
        }break;
        default:{
            //facehint = NSLocalizedString(@"FaceNotFound", nil);
            return;//否则导致闪现提示
        }break;
    }
    //TODO 扫描提示
    self.bottomView.reminderLabel.text = facehint;
}
- (void) updateUnre2DFaceTypeHint:(Unre2DHeadScannerFacePosition) type
{
    NSString * facehint = @"";
    switch(type){
        case Unre2DHeadScannerFacePositionFaceTooFar:{
            facehint = NSLocalizedString(@"FaceTooFar", nil);
        }break;
        case Unre2DHeadScannerFacePositionFaceTooClose:{
            facehint = NSLocalizedString(@"FaceTooClose", nil);
        }break;
        case Unre2DHeadScannerFacePositionFaceNotFrontal:{
            facehint = NSLocalizedString(@"FaceNotFrontal", nil);
        }break;
        case Unre2DHeadScannerFacePositionFaceNotCentered:
        case Unre2DHeadScannerFacePositionNotAvailable:
        case Unre2DHeadScannerFacePositionFaceNotFound:{
            facehint = NSLocalizedString(@"FaceNotCentered", nil);
        }break;
        case Unre3DAR3DFacePositionReadyToScan:{
            facehint = @"";
        }break;
        default:{
            //facehint = NSLocalizedString(@"FaceNotFound", nil);
            return;//否则导致闪现提示
        }break;
    }
    self.bottomView.reminderLabel.text = facehint;
}

- (void)didTrackFacePosition:(Unre2DHeadScannerFacePosition)facePosition
{
    if (facePosition == Unre2DHeadScannerFacePositionReadyToScan) {
        [self updateCaptureImageView: TAG_CAPTURE_IMAGE_VIEW_OK];
        [self updateCaptureButton:TAG_CAPTURE_IMAGE_VIEW_OK];
    }else{
        [self updateCaptureImageView: TAG_CAPTURE_IMAGE_VIEW_FAIL];
        [self updateCaptureButton:TAG_CAPTURE_IMAGE_VIEW_FAIL];
    }
}

- (void)didReportProgressInfo:(Unre2DHeadScannerProgressInfo *)progressInfo {
    if (progressInfo.currentHeadPosition < 0 && self.index == -2) {
        self.bottomView.stepView.index = -2;
    } else if (progressInfo.currentHeadPosition > 0 && self.index == 2) {
        self.bottomView.stepView.index = 2;
    } else {
        self.bottomView.stepView.index = 0;
    }
}

- (void)didReportCountdown:(float)countdown
{
    
    
}

- (void) updateCaptureImageView:(NSInteger) tagflag
{
    if(!self.captureFaceView.hidden && self.captureFaceView.tag != tagflag){
        dispatch_async(dispatch_get_main_queue(), ^{
            switch(tagflag){
                case TAG_CAPTURE_IMAGE_VIEW_OK:
                    self.captureFaceView.userInteractionEnabled = YES;
                    self.captureFaceView.tag = TAG_CAPTURE_IMAGE_VIEW_OK;
                    self.captureFaceView.image = [UIImage imageNamed:@"scan_ok"];
                    break;
                case TAG_CAPTURE_IMAGE_VIEW_FAIL:
                    self.captureFaceView.userInteractionEnabled = NO;
                    self.captureFaceView.tag = TAG_CAPTURE_IMAGE_VIEW_FAIL;
                    self.captureFaceView.image = [UIImage imageNamed:@"scan_fail"];
                    //[layer setArcColor:UIColor.redColor];
                    break;
            }
        });
    }
}
- (void) updateCaptureButton:(NSInteger) tagflag
{
    if(tagflag == TAG_CAPTURE_IMAGE_VIEW_OK){
        self.captureButton.userInteractionEnabled = YES;
        [self.captureButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        self.captureButton.imageView.tintColor = UIColor.whiteColor;
    } else {
        self.captureButton.userInteractionEnabled = NO;
        [self.captureButton setTitleColor:UIColor.darkGrayColor forState:UIControlStateNormal];
        self.captureButton.imageView.tintColor = UIColor.darkGrayColor;
    }
}
- (void)didCompleteScanningSuccessfully:(BOOL)completedSuccessfully
{
    if(completedSuccessfully){
        //[self.u2dHeadProc processWithSessionData:self.u3dSession];
    }else{
        [self updateCaptureImageView:TAG_CAPTURE_IMAGE_VIEW_OK];
        [self updateCaptureButton:TAG_CAPTURE_IMAGE_VIEW_OK];
        
    }
    [self.u2dHeadScan startTracking];
}

-(void) didReportNetImagePath:(NSString *)imgPath
{
    NSLog(@"huan net img path  %@",imgPath);
    //切割图片测试demo
    _u2dModel  =  [[U2DHeadNetModel alloc]init];
    self.captureUtils.u2dModel = _u2dModel;

    NSString *netImgFile = [self.u2dSession.rootSessionDirectory stringByAppendingString:@"/formatNet.jpg"];
    NSString *uvImgFile = [self.u2dSession.rootSessionDirectory stringByAppendingString:@"/formatUV.jpg"];
    U2DModelTF tff;
    BOOL isSuccess =  [_u2dModel formatNetImageWithInImgFile:imgPath andnetImgFile:netImgFile uvImgFile:uvImgFile getModelTF:&tff];
    _captureUtils.tff_net = tff;
    //相似度
    U2DHeadSimilarity *u2dSim = [[U2DHeadSimilarity alloc]init];
    // 定义源图片路径
    NSString * inImg = imgPath;
    // 定义个变量，用于承接生成的bmp的路径 --规则是在源图片目录下生成一张 同名capImg_similar.bmp 的图片
    NSString * simImg;
    [u2dSim headFaceSimilarityWithInImg:inImg andOutImg:&simImg];
    
    if (isSuccess) {
        AL2DCaptureInfo *captureInfo = [[AL2DCaptureInfo alloc] initWithBasePath:self.u2dSession.rootSessionDirectory];
        ALScanManager.shareInstance.show2DPathInfo = captureInfo;
        [ALScanManager.shareInstance savePathInfo];
        //1.取出 capImg_similar.bmp
        UIImage *netImage = [UIImage imageWithContentsOfFile:netImgFile];
        UIImage *bmpImage = [UIImage imageWithContentsOfFile:simImg];
        _captureUtils.originCapImgFile = imgPath;
        //异步处理 上传图片生成 obj
        [_captureUtils uploadNetImage:netImage BmpImage:bmpImage complete:^(BOOL isSuccess) {
            
        }];
       
    }
    
    BOOL isNeedRequest = [GMLoginManager shareInstance].user.has_scanFace;
    
    [[AppDelegate navigation] pushViewController:[ALScanFaceCompleteViewController new] animated:YES];
    
    if (isNeedRequest) [ALFaceFittingManager shareInstance].isNeedRequest = YES;
    
}



#pragma mark - 人体模拟声音
- (void) loadAdminHead:(BOOL) show
{
    if(self.headscnview){
        if(show){
            self.headscnview.scene = [self loadSCNScene];
            //[self AnimationFadeIn: self.headscnview.scene];
        } else {
            [self.headscnview.scene.rootNode removeAllActions];
            [self removeAllChildNodes:self.headscnview.scene.rootNode];
        }
    }
}

- (void) animationHead:(Unre2DHeadScannerScanHint) hint
{
    switch(hint){
        case Unre2DHeadScannerScanHintTurnHeadLeft:{
            [self.headscnview.scene.rootNode removeAllActions];
            [self.headscnview.scene.rootNode runAction:[SCNAction repeatAction:[SCNAction rotateByX:0 y:-0.8 z:0 duration:1] count:1]];
        }break;
        case Unre2DHeadScannerScanHintTurnHeadRight:{
            [self.headscnview.scene.rootNode removeAllActions];
            [self.headscnview.scene.rootNode runAction:[SCNAction repeatAction:[SCNAction rotateByX:0 y:0.8 z:0 duration:1] count:1]];
        }break;
        case Unre2DHeadScannerScanHintTurnHeadToTheMiddle:{
            if(self.lastUnre2DScanHint == Unre2DHeadScannerScanHintTurnHeadLeft){
                [self.headscnview.scene.rootNode removeAllActions];
                [self.headscnview.scene.rootNode runAction:[SCNAction repeatAction:[SCNAction rotateByX:0 y:0.8 z:0 duration:1] count:1]];
            } else if(self.lastUnre2DScanHint == Unre2DHeadScannerScanHintTurnHeadRight) {
                [self.headscnview.scene.rootNode removeAllActions];
                [self.headscnview.scene.rootNode runAction:[SCNAction repeatAction:[SCNAction rotateByX:0 y:-0.8 z:0 duration:1] count:1]];
            }
        }break;
        case Unre2DHeadScannerScanHintCaptureCompleted:{

        }break;
        default: break;
    }
}



- (void) AnimationFadeIn:(SCNScene *) scene
{
    // Fade in the objects
    CABasicAnimation *startAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    startAnim.duration = 0.3;
    startAnim.fromValue = @0.0;
    startAnim.toValue = @1.0;
    [scene.rootNode addAnimation:startAnim forKey:@"fadeIn"];
}

- (SCNScene *) loadSCNScene
{
    //SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/anim.scn"];
    SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/animationhead.obj"];
    SCNNode * head = scene.rootNode.childNodes[0];
    SCNVector3 position = head.position;
    head.position = SCNVector3Make(position.x , position.y + 20, position.z);
    [scene.rootNode addChildNode:[self createLightSCNNode]];
    [self scaleSCNNode:scene.rootNode byScale:0.6];
    return scene;
}

- (void) scaleSCNNode:(SCNNode *) node byScale:(float)scalevalue
{
    node.scale = SCNVector3Make(node.scale.x * scalevalue, node.scale.y * scalevalue, node.scale.z * scalevalue);
}

- (void) removeAllChildNodes:(SCNNode*)scnnode
{
    NSEnumerator * enumerateor =  [scnnode.childNodes objectEnumerator];
    SCNNode * child;
    while (child = [enumerateor nextObject]) {
        [child removeFromParentNode];
    }
}

- (SCNNode *) createLightSCNNode
{
    SCNNode *lightNode = [SCNNode node];
    //lightNode.name = SCNNODE_NAME_LIGHT;
    lightNode.light = [SCNLight light];
    lightNode.light.color = UIColor.whiteColor; // initially switched off
    lightNode.light.type = SCNLightTypeDirectional;
    return lightNode;
}

@end
