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

#import "ALFaceFittingViewController.h"
#import "ALCreateTopicController.h"
#import "ALScanFaceHomeViewController.h"
#import "ALFaceFittingView.h"
#import "ALFaceFittingModifyView.h"
#import "ALFaceStarCollectionViewCell.h"
#import "ALFaceAlertView.h"
#import "ALFaceFittingAPI.h"
#import "GMShareSDK.h"
#import "JSONModel.h"
#import "ALScanManager.h"
#import "UIViewController+GMExtension.h"
#import "FileUtils.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 "ALCaptureUtils.h"

@interface ALFaceFittingViewController () <ALFaceFittingModifyViewDelegate, ALFaceFittingViewDelegate, GMAlbumListViewControllerDelegate>
@property (nonatomic, strong) GMPhotoManager *manager;
@property (nonatomic, strong) ALFaceFittingView *faceFittingView;
@property (nonatomic, strong) ALFaceFittingModifyView *fittingModifyView;
@property (nonatomic, strong) NSArray <ALFaceStarModel *>*femaleStarArray;
@property (nonatomic, strong) NSArray <ALFaceStarModel *>*maleStarArray;
@property (nonatomic, assign) NSInteger unlockCnt;
@property (nonatomic, strong) ALCaptureUtils *captureUtils;
@property (nonatomic, assign) NSInteger lastSelectedTab;
@end

@implementation ALFaceFittingViewController

static NSString *reuseIdentifier = @"reuseIdentifier";

- (void)initController {
    [super initController];
    
    self.pageName = @"avatar_fitting";
    
    self.navigationBar.title = @"模拟";
    self.navigationBar.rightTitle = @"分享";
    self.navigationBar.nearRightIcon = @"faceDesc";
    self.navigationBar.isShowShadow = NO;
    _captureUtils = [[ALCaptureUtils alloc] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self p_prepareData];
    [self p_setup];
    [self p_requestStarList];
}

- (void)backAction:(OCNavigationBarButton *)button {
    [super backAction:button];
    [Phobos track:@"page_click_return_label" attributes:@{@"page_name":self.pageName}];
}

- (void)reloadFaceFitting {
    [_faceFittingView reloadData];
}

- (void)p_prepareData {
    self.femaleStarArray = [GMCache fetchObjectAtDocumentPathWithkey:ALFEMALE_STAR_FITTING_LIST];
    self.maleStarArray = [GMCache fetchObjectAtDocumentPathWithkey:ALMALE_STAR_FITTING_LIST];
}

- (void)p_requestStarList {
    [AppDelegate.visibleController showLoading:@"正在加载..."];
    NSMutableDictionary *parameters = [NSMutableDictionary new];
    [parameters setValue:ALScanManager.shareInstance.fittingId forKey:@"id"];
    [ALFaceFittingAPI fetchStarListWithParameters:parameters completion:^(GMResponseOC *responseObject) {
        [AppDelegate.visibleController hideLoading];
        if (responseObject.isSuccess) {
            NSDictionary *data = responseObject.data;
            NSDictionary *stars = data[@"stars"];
            self.unlockCnt = [data[@"unlock_cnt"] integerValue];
            self.maleStarArray = [ALFaceStarModel arrayOfModelsFromDictionaries:stars[@"male"] error:nil];
            self.femaleStarArray = [ALFaceStarModel arrayOfModelsFromDictionaries:stars[@"female"] error:nil];
            self.fittingModifyView.starArray = self.fittingModifyView.isFemale ? self.femaleStarArray : self.maleStarArray;
        }
    }];
}

- (void)rescanInFaceFittingView:(ALFaceFittingView *)view {
    [Phobos track:@"avatar_fitting_click_rescan" attributes:@{@"page_name":self.pageName}];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"重新扫描" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ALScanFaceHomeViewController *vc = [[ALScanFaceHomeViewController alloc] init];
        vc.isHiddenJump = YES;
        [self pushViewController:vc];
    }];
//    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"上传图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [AppDelegate.visibleController showLoading:nil];
//        [ALFaceFittingAPI fetchFaceFittingDataWithCompletion:^(GMResponseOC * _Nonnull responseObject) {
//            [AppDelegate.visibleController hideLoading];
//            if (responseObject.isSuccess) {
//                [self gm_presentAlbumListViewControllerWithManager:self.manager delegate:self];
//            } else [AppDelegate.visibleController toast:responseObject.message];
//        }];
//    }];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:action1];
    [alertController addAction:action2];
//    [alertController addAction:action3];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)fittingInFaceFittingView:(ALFaceFittingView *)view {
    [Phobos track:@"avatar_fitting_click_slider" attributes:[self p_getSliderAndTabPhobos]];
    NSLog(@"%s", __func__);
}

- (void)gridInFaceFittingView:(ALFaceFittingView *)view {
    [Phobos track:@"avatar_fitting_click_slider" attributes:[self p_getSliderAndTabPhobos]];
    NSLog(@"%s", __func__);
}

- (void)albumListViewController:(GMAlbumListViewController *)albumListViewController didDoneAllImage:(NSArray<UIImage *> *)imageList {
    
    U2DSessionData *sessionData = [[U2DSessionData alloc] initWithID:@"alphaUser2DCapture" error:nil];
    _captureUtils.u2dSession = sessionData;
    if (imageList.count > 0) {
        UIImage *image = imageList[0];
        NSString *suggestName = [NSString stringWithFormat:@"%@.png",[PhobosUtil currentTime]];
        NSString *filePath = [sessionData.rootSessionDirectory stringByAppendingPathComponent:suggestName];
        //1. 创建一个文件夹 把image 存到本地
        [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
    
        if (![FileUtils isFileExist:filePath]) {
            return;
        }
        U2DHeadNetModel *u2dModel  =  [[U2DHeadNetModel alloc]init];
        _captureUtils.u2dModel = u2dModel;
        NSString *netImgFile = [sessionData.rootSessionDirectory stringByAppendingString:@"/formatNet.jpg"];
        NSString *uvImgFile = [sessionData.rootSessionDirectory stringByAppendingString:@"/formatUV.jpg"];
        U2DModelTF tff;
        BOOL isSuccess =  [u2dModel formatNetImageWithInImgFile:filePath andnetImgFile:netImgFile uvImgFile:uvImgFile getModelTF:&tff];
        _captureUtils.tff_net = tff;
        ////相似度
        U2DHeadSimilarity *u2dSim = [[U2DHeadSimilarity alloc]init];
        //// 定义源图片路径
        NSString * inImg = filePath;
        // 定义个变量，用于承接生成的bmp的路径 --规则是在源图片目录下生成一张 同名capImg_similar.bmp 的图片
        NSString * simImg;
        [u2dSim headFaceSimilarityWithInImg:inImg andOutImg:&simImg];
        //2. 生成bmp 以及 formatUv
        if (isSuccess) {
            AL2DCaptureInfo *captureInfo = [[AL2DCaptureInfo alloc] initWithBasePath:sessionData.rootSessionDirectory];
    
            ALScanManager.shareInstance.show2DPathInfo = captureInfo;
            ALScanManager.shareInstance.isScan3D = NO;
            [ALScanManager.shareInstance savePathInfo];
           
            UIImage *netImage = [UIImage imageWithContentsOfFile:netImgFile];
            UIImage *bmpImage = [UIImage imageWithContentsOfFile:simImg];
            //        capImg.jpg
            _captureUtils.originCapImgFile = filePath;
            //异步处理 上传图片生成 obj
            [_captureUtils uploadNetImage:netImage BmpImage:bmpImage complete:^(BOOL isSuccess) {
                //是否上传成功
            }];
        } else {
            [self toast:@"上传失败，请上传正面人脸照片"];
        }
    }
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view selettStarListIsFemale:(BOOL)isFemale {
    [Phobos track:@"avatar_fitting_click_tab" attributes:[self p_getSliderAndTabPhobos]];
    if (isFemale && _femaleStarArray) {
        _fittingModifyView.starArray = _femaleStarArray;
    } else if (!isFemale && _maleStarArray) {
        _fittingModifyView.starArray = _maleStarArray;
    } else {
        [self p_requestStarList];
    }
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view unlockStar:(ALFaceStarModel *)star {
    NSMutableDictionary *paras = [[self p_getSliderAndTabPhobos] mutableCopy];
    [paras setValue:star.id forKey:@"star_avatar_id"];
    [Phobos track:@"avatar_fitting_click_star_card" attributes:paras];
    if (_unlockCnt > 0) {
        [self p_unlockStar:star];
    } else {
        [self p_share];
    }
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view addStar:(BOOL)isFemale {
    ALCreateTopicController *vc = [[ALCreateTopicController alloc] initWithComeInType:(FromWhereComeInFace) from:@"avatar_fitting_click_create_topic"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view willModeifyDetails:(ALFaceStarModel *)star filePath:(NSString *)filePath UVPath:(NSString *)uvPath {
    [_faceFittingView willModifyDetailsAtFilePath:filePath starUV:uvPath];
    NSMutableDictionary *paras = [[self p_getSliderAndTabPhobos] mutableCopy];
    [paras setValue:star.id forKey:@"star_avatar_id"];
    [Phobos track:@"avatar_fitting_click_star_card" attributes:paras];
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view modifyStarDetails:(ALFaceStarModel *)star {
    dispatch_async(dispatch_get_main_queue(), ^{
        [AppDelegate.visibleController showLoading:@"模型数据处理中"];
    });
    [_faceFittingView modifyDetails];
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view modifyStarDetail:(ALFaceStarModel *)star indexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSArray *titles = @[@"鼻子", @"眼部", @"嘴部", @"脸颊", @"美白"];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ALFaceModifyDetails" ofType:@"plist"];
    NSDictionary *tabs = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *tab = titles[section];
    NSArray *subTabs = tabs[tab];
    NSString *eventId = @"avatar_fitting_click_feature_tab";
    NSMutableDictionary *paras = [[self p_getSliderAndTabPhobos] mutableCopy];
    [paras setValue:star.id forKey:@"star_avatar_id"];
    [paras setValue:@"avatar_fitting" forKey:@"page_name"];
    [paras setValue:tab forKey:@"feature_tab"];
    if (_lastSelectedTab == section) {
        eventId = @"avatar_fitting_click_sub_feature_tab";
        [paras setValue:subTabs[row] forKey:@"sub_feature_tab"];
    }
    [Phobos track:eventId attributes:paras];
    _lastSelectedTab = section;
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view modifyDetailIndexPath:(NSIndexPath *)indexPath value:(NSInteger)value {
    [_faceFittingView.sdkHelper testtranform:(int)indexPath.section andRow:(int)indexPath.row andValue:value];
}

- (void)faceFittingModifyView:(ALFaceFittingModifyView *)view modifyDetialsFinish:(BOOL)isFinish values:(NSArray *)values {
    if (isFinish) {
//        NSLog(@"%s---%@", __func__, values);
    } else {
//        NSLog(@"%s---cancel", __func__);
    }
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    [Phobos track:@"avatar_fitting_click_share" attributes:@{@"page_name":self.pageName}];
    [self p_share];
}

- (void)nearRightButtonClicked:(OCNavigationBarButton *)button {
    [Phobos track:@"avatar_fitting_click_fit_intro" attributes:@{@"page_name":self.pageName}];
    ALFaceAlertView *alertView = [[ALFaceAlertView alloc] init];
    [self.view addSubview:alertView];
}

- (void)p_share {
    ALFaceAlertView *alertView = [[ALFaceAlertView alloc] init];
    alertView.isShare = YES;
    alertView.clickBlock = ^(ALFaceAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) [Phobos track:@"page_click_return_label" attributes:@{@"page_name":@"avatar_fitting_share"}];
        else [self p_shareWithIndex:buttonIndex];
    };
    [self.view addSubview:alertView];
}

- (void)p_unlockStar:(ALFaceStarModel *)model {
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定解锁次明星" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [AppDelegate.visibleController showLoading:@"正在加载..."];
        NSMutableDictionary *parameters = [NSMutableDictionary new];
        [parameters setValue:model.id forKey:@"star_id"];
        [parameters setValue:ALScanManager.shareInstance.fittingId forKey:@"recognition_id"];
        [ALFaceFittingAPI unlockStarWithParameters:parameters completion:^(GMResponseOC * _Nonnull responseObject) {
            [AppDelegate.visibleController hideLoading];
            if (responseObject.isSuccess) {
                NSDictionary *dataDict = responseObject.data;
                self.unlockCnt = [dataDict[@"unlock_cnt"] integerValue];
                [self p_requestStarList];
            } else {
                [AppDelegate.visibleController toast:responseObject.message];
            }
        }];
    }];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)p_shareWithIndex:(NSInteger)index {
    [Phobos track:@"avatar_fitting_share_click_share" attributes:@{@"type" : index == 1 ? @"微信" : @"朋友圈"}];
    if (![GMShareSDK isClientInstalled:GMSharePlatformWechatSession]) {
        [AppDelegate.visibleController toast:@"您未安装微信客户端"];
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary new];
    [parameters setValue:index == 1 ? @"3" : @"4" forKey:@"channel"];
    [parameters setValue:ALScanManager.shareInstance.fittingId forKey:@"unique_id"];
    [parameters setValue:@"1" forKey:@"content_type"];
    [AppDelegate.visibleController showLoading:@"正在加载..."];
    [ALFaceFittingAPI unlockStarNeedShareWithParameters:parameters completion:^(GMResponseOC * _Nonnull responseObject) {
        [AppDelegate.visibleController hideLoading];
        if (responseObject.isSuccess) {
            NSDictionary *data = responseObject.data[@"share_data"];
            NSString *title = data[index == 1 ? @"wechat" : @"wechatline"][@"title"];
            NSString *content = data[index == 1 ? @"wechat" : @"wechatline"][@"content"];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:data[@"image"]]]];
            NSMutableDictionary *parameters = [NSMutableDictionary new];
            
            NSString *shareUrl = data[@"url"];
            shareUrl = [shareUrl stringByAppendingFormat:@"&channel=%@",[GMShareSDK shareChannel:(index == 1 ? GMSharePlatformWechatSession : GMSharePlatformWechatTimeline)]];
            NSString *user_id = [NSString stringWithFormat:@"%zd",[GMLoginManager shareInstance].user.userId];
            if (![GMLoginManager shareInstance].isVisitor) {
                shareUrl = [shareUrl stringByAppendingFormat:@"&from_user_id=%@",user_id];
            }
            
            [parameters setValue:shareUrl forKey:@"url"];
            [parameters setValue:title forKey:@"title"];
            [parameters setValue:content forKey:@"text"];
            [parameters setValue:image forKey:@"images"];
            [[GMShareSDK shareInstance] share:index == 1 ? GMSharePlatformWechatSession : GMSharePlatformWechatTimeline parameters:parameters onStateChanged:^(GMShareResponseState state, NSError *error) {
                if (state == GMShareResponseStateSuccess) {
                    [GMHudModule toast:@"分享成功"];
                } else if(state == GMShareResponseStateCancel) {
                    [GMHudModule toast:@"取消分享"];
                } else if(state == GMShareResponseStateFail) {
                    [GMHudModule toast:@"分享失败"];
                }
            }];
        } else {
//            [self p_shareWithIndex:index];
        }
    }];
}

- (NSDictionary *)p_getSliderAndTabPhobos {
    return @{@"page_name":self.pageName,
             @"slider_name" : self.faceFittingView.isGrid ? @"差异" : @"融合",
             @"tab_name" : self.fittingModifyView.isFemale ? @"女" : @"男"};
}

- (void)p_setup {
    self.view.backgroundColor = UIColor.whiteColor;
    _faceFittingView = [[ALFaceFittingView alloc] init];
    _faceFittingView.delegate = self;
    [self.view addSubview:_faceFittingView];
    [_faceFittingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(OCNavigationBar.barHeight + 20);
        make.left.right.mas_equalTo(0);
        make.height.equalTo(self.faceFittingView.mas_width);
    }];
    
    _fittingModifyView = [[ALFaceFittingModifyView alloc] init];
    _fittingModifyView.delegate = self;
    _fittingModifyView.starArray = _femaleStarArray;
    [self.view addSubview:_fittingModifyView];
    [_fittingModifyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.faceFittingView.mas_bottom);
        make.bottom.left.right.mas_equalTo(0);
    }];
}

- (GMPhotoManager *)manager {
    if (!_manager) {
        _manager = [[GMPhotoManager alloc] initWithType:GMPhotoManagerSelectedTypePhoto];
        _manager.configuration.photoMaxNum = 1;
    }
    return _manager;
}

@end
