//
//  ALFaceFittingView.m
//  GMAlpha
//
//  Created by Jing on 2018/11/26.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALFaceFittingView.h"
#import "UIColor+GMTheme.h"
#import <SceneKit/SceneKit.h>
#import "FileUtils.h"
#include "OBJView.h"
#import "ALMatchingModel.h"
#import "ALScanManager.h"

@interface ALFaceFittingView ()<SDKHelperDelegate>

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *view;
@property (nonatomic, strong) GMButton *rescanButton;
@property (nonatomic, strong) GMButton *fittingButton;
@property (nonatomic, strong) GMButton *gridButton;
@property (nonatomic, strong) GMButton *selectedButton;
@property (nonatomic, strong) OBJView  *objView;
//当前模型数据
@property (nonatomic, strong) ALMatchingModel *model;
@property (nonatomic, strong) NSString *goalObjPath;
@property (nonatomic, strong) NSString *goalStarUV;
@end

@implementation ALFaceFittingView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self p_setup];
        
        ALMatchingModel *myModle = [self getMy3DHeadSourceModel];
        [self.objView loadMyOBjModel:myModle];
    }
    return self;
}

//加载自己的模型
- (ALMatchingModel *)getMy3DHeadSourceModel {
    ALMatchingModel *model = [[ALMatchingModel alloc] init];
    if (ALScanManager.shareInstance.isScan3D) {
        //加载3d下文件
        model.sourceOBJFile = [ALScanManager.shareInstance.show3DInfo getOBJFile]; //存本地
        model.sourceMeshFile = [ALScanManager.shareInstance.show3DInfo getMeshFile]; //存本地
    } else {
        //加载2d下文件
        model.sourceOBJFile = [ALScanManager.shareInstance.show2DPathInfo getOBJFile];
        model.sourceMeshFile = [ALScanManager.shareInstance.show2DPathInfo getMeshFile]; //存本地
    }
    return model;
}

- (void)reloadData {
    [_objView reload];
}

- (void)refreshObj:(NSString *)goalObjPath startUv:(NSString *)goalStarUV {
    _model = [self getMy3DHeadSourceModel];
    if ([goalObjPath isNonEmpty] && [goalObjPath isNonEmpty]) {
        _goalObjPath = goalObjPath;
        _goalStarUV = goalStarUV;
        _model.goalOBJFile = [NSString stringWithFormat:@"%@/%@", [FileUtils getBasePath], goalObjPath];
        _model.goalMeshFile = [NSString stringWithFormat:@"%@/%@", [FileUtils getBasePath], goalStarUV];
        _sdkHelper = [[SDKHelper alloc] initWithOBJView:self.objView andModel:_model andSliderPanel:nil];
    } else {
        [AppDelegate.visibleController toast:@"获取目标模型失败"];
    }
}

//拟合数据
- (void)modifyDetails {    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.sdkHelper testEvlo];
    });
}

- (void)willModifyDetailsAtFilePath:(NSString *)filePath starUV:(NSString *)starUV {
    if (![filePath isNonEmpty] || ![starUV isNonEmpty]) {
        [AppDelegate.visibleController toast:@"正在下载..."];
        return;
    }
    
    [self refreshObj:filePath startUv:starUV];
}

- (BOOL)isGrid {
    return _selectedButton == _gridButton;
}

- (void)p_rescan {
    if ([_delegate respondsToSelector:@selector(rescanInFaceFittingView:)])
        [_delegate rescanInFaceFittingView:self];
}

- (void)p_fitting {
    if (_selectedButton == _fittingButton) return;
    self.selectedButton = _fittingButton;
    [self reloadData];
    if ([_delegate respondsToSelector:@selector(fittingInFaceFittingView:)])
        [_delegate fittingInFaceFittingView:self];
}

//需要知道网格脸以及目标模型
- (void)p_grid {
    if (_selectedButton == _gridButton) return;
    self.selectedButton = _gridButton;

    ALMatchingModel *model = [self getMy3DHeadSourceModel];
    if ([model.sourceOBJFile isNonEmpty] && [self.goalObjPath isNonEmpty]) {
        NSString *goalObj = [NSString stringWithFormat:@"%@/%@", [FileUtils getBasePath], self.goalObjPath];
        SCNNode *myNode;
        if (ALScanManager.shareInstance.isScan3D) {
            myNode = [_sdkHelper getMy3DNode];
            myNode.geometry.firstMaterial.lightingModelName = SCNLightingModelBlinn;
            myNode.geometry.firstMaterial.diffuse.contents = model.sourceMeshFile;
            myNode.geometry.firstMaterial.transparency = 0.5;
        }
        [self.objView reloadWithMyModel:model andStarObj:goalObj and3DNode:myNode];
    } else {
        [AppDelegate.visibleController toast:@"模型不存在"];
    }
    if ([_delegate respondsToSelector:@selector(gridInFaceFittingView:)])
        [_delegate gridInFaceFittingView:self];
}

- (void)setSelectedButton:(GMButton *)button {
    _selectedButton.selected = NO;
    button.selected = YES;
    _selectedButton = button;
}

- (void)p_setup {
    _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"faceFittingNormal"]];
    [self addSubview:_imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    _view = [UIView new];
    [self addSubview:_view];
    [_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    _objView = [[OBJView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_WIDTH)];
    [_view addSubview:_objView];
    
    _rescanButton = [GMButton buttonWithTitle:@"重新扫描" backgroundColor:UIColor.blackColor titleFontSize:14 titleColor:UIColor.whiteColor];
    [_rescanButton addTarget:self action:@selector(p_rescan) forControlEvents:UIControlEventTouchUpInside];
    [_view addSubview:_rescanButton];
    [_rescanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(68);
        make.height.mas_equalTo(26);
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(-15);
    }];
    
    _gridButton = [GMButton buttonWithType:UIButtonTypeCustom];
    _gridButton.hidden = YES;
    [_gridButton setBackgroundColor:UIColor.darkGrayColor forState:UIControlStateNormal];
    [_gridButton setBackgroundColor:UIColor.blackColor forState:UIControlStateSelected];
    [_gridButton setImage:[UIImage imageNamed:@"faceGrid"] forState:UIControlStateNormal];
    [_gridButton addTarget:self action:@selector(p_grid) forControlEvents:UIControlEventTouchUpInside];
    [_view addSubview:_gridButton];
    [_gridButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(37);
        make.height.mas_equalTo(33);
        make.right.bottom.mas_equalTo(-15);
    }];
    
    _fittingButton = [GMButton buttonWithType:UIButtonTypeCustom];
    _fittingButton.hidden = YES;
    [_fittingButton setBackgroundColor:UIColor.darkGrayColor forState:UIControlStateNormal];
    [_fittingButton setBackgroundColor:UIColor.blackColor forState:UIControlStateSelected];
    [_fittingButton setImage:[UIImage imageNamed:@"faceFitting"] forState:UIControlStateNormal];
    [_fittingButton addTarget:self action:@selector(p_fitting) forControlEvents:UIControlEventTouchUpInside];
    self.selectedButton = _fittingButton;
    [_view addSubview:_fittingButton];
    [_fittingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(37);
        make.height.mas_equalTo(33);
        make.right.mas_equalTo(self.gridButton.mas_left);
        make.bottom.mas_equalTo(self.gridButton);
    }];
}

#pragma mark - SDKHelperDelegate
-(void)analyzeObjFinish {
    //分析初始化 数据完毕
    [AppDelegate.visibleController hideLoading];
}
@end
