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

#import "ALFaceFittingModifyView.h"
#import "ALFaceStarCollectionViewCell.h"
#import "ALFaceModifyDetailsView.h"
#import <GMKit/UIColor+GMTheme.h>
#import "WYSegmentView+Factory.h"
#import "GMSegmentViewWithRedBadge.h"
#import "ALFaceFittingAPI.h"

@interface ALFaceFittingModifyView () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) GMView *editView;
@property (nonatomic, strong) GMCollectionView *starCollectionView;
@property (nonatomic, strong) ALFaceModifyDetailsView *modifyDetailsView;
@property (nonatomic, strong) ALFaceStarCollectionViewCell *modifyCell;

@property (nonatomic, strong) UIView *starView;
@property (nonatomic, strong) UIView *modifyView;

@property (nonatomic, strong) GMButton *maleStarButton;
@property (nonatomic, strong) GMButton *femaleStarButton;
@property (nonatomic, strong) UILabel *lineLabel;
@property (nonatomic, strong) GMButton *selectedStarButton;

@property (nonatomic, strong) GMButton *cancelButton;
@property (nonatomic, strong) GMButton *confirmButton;
@property (nonatomic, strong) WYSegmentView *detailSegmentView;
@property (nonatomic, strong) WYSegmentView *subDetailSegmentView;

@property (nonatomic, strong) NSDictionary *detailsDict;
@property (nonatomic, strong) NSMutableArray *valueArray;
@property (nonatomic, strong) NSString *currentStarFilePath;
@property (nonatomic, strong) NSString *currentStarUvPath;

@end

@implementation ALFaceFittingModifyView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self p_setup];
    }
    return self;
}

- (void)setStarArray:(NSArray<ALFaceStarModel *> *)starArray {
    _starArray = starArray;
    if (_modifyCell) [_modifyCell modifyDetails];
    _modifyCell = nil;
    [_starCollectionView reloadData];
}

- (BOOL)isFemale {
    return _selectedStarButton == _femaleStarButton;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _starArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ALFaceStarCollectionViewCell *cell = [collectionView dequeueCell:[ALFaceStarCollectionViewCell class] forIndexPath:indexPath];
    if (indexPath.row >= _starArray.count) {
        [cell addCell];
    } else {
        NSInteger item = indexPath.item;
        cell.model = _starArray[item];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ALFaceStarCollectionViewCell *cell = (ALFaceStarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSInteger index = indexPath.item;
    if (index == _starArray.count) {
        if (_modifyCell) {
            [_modifyCell modifyDetails];
            _modifyCell = nil;
        }
        if ([_delegate respondsToSelector:@selector(faceFittingModifyView:addStar:)])
            [_delegate faceFittingModifyView:self addStar:_maleStarButton.selected];
    } else if (cell.model.isLock) {
        if (_modifyCell) {
            [_modifyCell modifyDetails];
            _modifyCell = nil;
        }
        if ([_delegate respondsToSelector:@selector(faceFittingModifyView:unlockStar:)])
            [_delegate faceFittingModifyView:self unlockStar:_starArray[index]];
    } else if ([cell willModify]) {
        [self p_modifyDetails];
        [cell modifyDetails];
        if ([_delegate respondsToSelector:@selector(faceFittingModifyView:modifyStarDetails:)])
            [_delegate faceFittingModifyView:self modifyStarDetails:_starArray[index]];
        _currentStarFilePath = nil;
    } else if (cell != _modifyCell)  {
        __weak __typeof(self)weakSelf = self;
        __block BOOL isObjFinish;
        __block BOOL isUVFinish;
        _currentStarFilePath = [ALFaceFittingAPI fetchStarFittingObjPathWithUrl:cell.model.starModelUrl starId:cell.model.id completion:^(NSString * _Nullable filePath) {
            isObjFinish = YES;
            if (filePath) weakSelf.currentStarFilePath = filePath;
            else [AppDelegate.visibleController toast:@"obj文件加载失败"];
            if (isObjFinish && isUVFinish) [AppDelegate.visibleController hideLoading];
            if (weakSelf.currentStarFilePath && weakSelf.currentStarUvPath) {
                [weakSelf p_modifyWithCell:cell];
            }
        }];
        _currentStarUvPath = [ALFaceFittingAPI fetchStarFittingUvPathWithUrl:cell.model.starUv starId:cell.model.id completion:^(NSString * _Nullable filePath) {
            isUVFinish = YES;
            if (filePath) weakSelf.currentStarUvPath = filePath;
            else [AppDelegate.visibleController toast:@"UV文件加载失败"];
            if (isObjFinish && isUVFinish) [AppDelegate.visibleController hideLoading];
            if (weakSelf.currentStarFilePath && weakSelf.currentStarUvPath) {
                [weakSelf p_modifyWithCell:cell];
            }
        }];
        if (_currentStarFilePath && _currentStarUvPath) {
            [self p_modifyWithCell:cell];
        } else {
            [AppDelegate.visibleController showLoading:@"正在加载..."];
        }
    }
}

- (void)p_modifyWithCell:(ALFaceStarCollectionViewCell *)cell {
    [AppDelegate.visibleController hideLoading];
    if ([self.delegate respondsToSelector:@selector(faceFittingModifyView:willModeifyDetails:filePath:UVPath:)]) {
        [self.delegate faceFittingModifyView:self willModeifyDetails:cell.model filePath:_currentStarFilePath UVPath:_currentStarUvPath];
    }
    
    [_modifyCell modifyDetails];
    _modifyCell = cell;
    [cell modifyDetails];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSInteger value = [change[NSKeyValueChangeNewKey] integerValue];
    NSInteger section = _detailSegmentView.selectedSegmentIndex;
    NSInteger item = _subDetailSegmentView.selectedSegmentIndex;
    NSMutableArray *values = _valueArray[section];
    [values replaceObjectAtIndex:item withObject:@(value)];
    [_valueArray replaceObjectAtIndex:section withObject:values];
    if ([_delegate respondsToSelector:@selector(faceFittingModifyView:modifyDetailIndexPath:value:)])
        [_delegate faceFittingModifyView:self modifyDetailIndexPath:[NSIndexPath indexPathForRow:item inSection:section] value:value];
}

- (void)p_modifyDetails {
    [self p_resetValues];
    [_modifyDetailsView resetValue];
    _modifyDetailsView.hidden = _starCollectionView.hidden;
    _starCollectionView.hidden = !_starCollectionView.hidden;
    _modifyView.hidden = _starView.hidden;
    _starView.hidden = !_starView.hidden;
    _editView.backgroundColor = _starView.hidden ? RGBCOLOR_HEX(0xF6F5FA) : UIColor.whiteColor;

    _subDetailSegmentView.sectionTitles = _detailsDict[@"鼻子"];
    [_detailSegmentView setSelectedSegmentIndex:0 animated:NO];
    [_subDetailSegmentView setSelectedSegmentIndex:0 animated:NO];
    [_subDetailSegmentView layoutSegments];
}

- (void)p_selectButton:(GMButton *)button {
    if (button == _selectedStarButton) return;
    button.selected = YES;
    _selectedStarButton.titleLabel.font = [UIFont gmFont:14];
    _selectedStarButton.selected = NO;
    _selectedStarButton = button;
    _selectedStarButton.titleLabel.font = [UIFont gmBoldFont:14];
    if ([_delegate respondsToSelector:@selector(faceFittingModifyView:selettStarListIsFemale:)])
        [_delegate faceFittingModifyView:self selettStarListIsFemale:button == _femaleStarButton];
}

- (void)p_finish:(GMButton *)button {
    [self p_modifyDetails];
    [_detailSegmentView layoutSegments];
    _modifyCell = nil;
    if ([_delegate respondsToSelector:@selector(faceFittingModifyView:modifyDetialsFinish:values:)])
        [_delegate faceFittingModifyView:self modifyDetialsFinish:button == _confirmButton values:_valueArray];
}

- (void)p_resetValues {
    _valueArray = [NSMutableArray new];
    NSArray *titles = @[@"鼻子", @"眼部", @"嘴部", @"脸颊", @"美白"];
    for (NSString *title in titles) {
        NSArray *array = _detailsDict[title];
        NSMutableArray *values = [NSMutableArray new];
        for (NSString *string in array) {
            [values addObject:@(50)];
        }
        [_valueArray addObject:values];
    }
}

- (void)p_setup {
    self.backgroundColor = UIColor.whiteColor;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ALFaceModifyDetails" ofType:@"plist"];
    _detailsDict = [NSDictionary dictionaryWithContentsOfFile:path];
    [self p_resetValues];
    
    _editView = [GMView new];
    _editView.backgroundColor = UIColor.whiteColor;
    [self addSubview:_editView];
    [_editView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom - 50);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(90, 130);
    layout.minimumLineSpacing = 15;
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    _starCollectionView = [[GMCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _starCollectionView.showsHorizontalScrollIndicator = NO;
    [_starCollectionView registerCell:[ALFaceStarCollectionViewCell class]];
    _starCollectionView.delegate = self;
    _starCollectionView.dataSource = self;
    _starCollectionView.backgroundColor = UIColor.whiteColor;
    [_editView addSubview:_starCollectionView];
    [_starCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(130);
        make.centerY.equalTo(self.editView);
    }];
    
    _modifyDetailsView = [[ALFaceModifyDetailsView alloc] init];
    _modifyDetailsView.hidden = YES;
    [self addSubview:_modifyDetailsView];
    [_modifyDetailsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.starCollectionView);
    }];
    
    _starView = [UIView new];
    [self addSubview:_starView];
    [_starView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
    }];
    
    _modifyView = [UIView new];
    _modifyView.hidden = YES;
    [self addSubview:_modifyView];
    [_modifyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.starView);
    }];
    
    _femaleStarButton = [GMButton buttonWithTitle:@"女明星" backgroundColor:UIColor.whiteColor titleFontSize:16 titleColor:UIColor.auxiliaryTextDark];
    [_femaleStarButton setTitleColor:UIColor.headlineText forState:UIControlStateSelected];
    [_femaleStarButton addTarget:self action:@selector(p_selectButton:) forControlEvents:UIControlEventTouchUpInside];
    _femaleStarButton.selected = YES;
    _femaleStarButton.titleLabel.font = [UIFont gmBoldFont:16];
    _selectedStarButton = _femaleStarButton;
    [_starView addSubview:_femaleStarButton];
    [_femaleStarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.mas_width).multipliedBy(0.5);
        make.height.mas_equalTo(50);
        make.left.bottom.mas_equalTo(0);
    }];
    
    _maleStarButton = [GMButton buttonWithTitle:@"男明星" backgroundColor:UIColor.whiteColor titleFontSize:16 titleColor:UIColor.auxiliaryTextDark];
    [_maleStarButton setTitleColor:UIColor.headlineText forState:UIControlStateSelected];
    [_maleStarButton addTarget:self action:@selector(p_selectButton:) forControlEvents:UIControlEventTouchUpInside];
    [_starView addSubview:_maleStarButton];
    [_maleStarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.mas_width).multipliedBy(0.5);
        make.height.mas_equalTo(50);
        make.right.bottom.mas_equalTo(0);
    }];
    
    _lineLabel = [[UILabel alloc] init];
    _lineLabel.backgroundColor = UIColor.separatorLine;
    [_starView addSubview:_lineLabel];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(12);
        make.center.mas_equalTo(self.starView);
    }];
    
    NSArray *titles = @[@"鼻子", @"眼部", @"嘴部", @"脸颊"/*, @"美白"*/];
    _detailSegmentView = [WYSegmentView dynamicSegment];
    _detailSegmentView.sectionTitles = titles;
    _detailSegmentView.titleTextAttributes = @{NSFontAttributeName:[UIFont gmFont:16],
                                            NSForegroundColorAttributeName:UIColor.auxiliaryTextLight};
    _detailSegmentView.selectedTitleTextAttributes = @{NSFontAttributeName:[UIFont gmBoldFont:16],
                                                    NSForegroundColorAttributeName:UIColor.bodyText};
    _detailSegmentView.itemHorizonalPadding = 22.5;
    _detailSegmentView.scrollView.contentInset = UIEdgeInsetsMake(0, 43.5, 0, 43.5);
    _detailSegmentView.bothEndPadding = 43.5;
    _detailSegmentView.showIndicator = NO;
    _detailSegmentView.clipsToBounds = NO;
    _detailSegmentView.bottomLine.hidden = YES;
    [_detailSegmentView layoutSegments];
    [_modifyView addSubview:_detailSegmentView];
    [_detailSegmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.mas_equalTo(0);
    }];
    
    _subDetailSegmentView = [WYSegmentView dynamicSegment];
    _subDetailSegmentView.backgroundColor = RGBCOLOR_HEX(0xF6F5FA);
    _subDetailSegmentView.sectionTitles = _detailsDict[@"鼻子"];
    _subDetailSegmentView.titleTextAttributes = @{NSFontAttributeName:[UIFont gmFont:14],
                                               NSForegroundColorAttributeName:UIColor.auxiliaryTextLight};
    _subDetailSegmentView.selectedTitleTextAttributes = @{NSFontAttributeName:[UIFont gmBoldFont:14],
                                                       NSForegroundColorAttributeName:RGBCOLOR_HEX(0x0093FF)};
    _subDetailSegmentView.itemHorizonalPadding = 22.5;
    _subDetailSegmentView.scrollView.contentInset = UIEdgeInsetsMake(0, 9.5, 0, 9.5);
    _subDetailSegmentView.showIndicator = NO;
    _subDetailSegmentView.clipsToBounds = NO;
    _subDetailSegmentView.bottomLine.hidden = YES;
    [_subDetailSegmentView layoutSegments];
    [_modifyDetailsView addSubview:_subDetailSegmentView];
    [_subDetailSegmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(15);
    }];
    
    __weak typeof(self) weakSelf = self;
    _detailSegmentView.didSelectedBlock = ^(NSUInteger index) {
        NSString *key = titles[index];
        weakSelf.subDetailSegmentView.sectionTitles = weakSelf.detailsDict[key];
        [weakSelf.subDetailSegmentView setSelectedSegmentIndex:0 animated:YES];
        [weakSelf.subDetailSegmentView layoutSegments];
        [weakSelf.modifyDetailsView resetValue];
        if ([weakSelf.delegate respondsToSelector:@selector(faceFittingModifyView:modifyStarDetail:indexPath:)]) {
            [weakSelf.delegate faceFittingModifyView:weakSelf modifyStarDetail:weakSelf.modifyCell.model indexPath:[NSIndexPath indexPathForRow:weakSelf.subDetailSegmentView.selectedSegmentIndex inSection:weakSelf.detailSegmentView.selectedSegmentIndex]];
        }
    };
    
    _subDetailSegmentView.didSelectedBlock = ^(NSUInteger index) {
        [weakSelf.modifyDetailsView resetValue];
        if ([weakSelf.delegate respondsToSelector:@selector(faceFittingModifyView:modifyStarDetail:indexPath:)]) {
            [weakSelf.delegate faceFittingModifyView:weakSelf modifyStarDetail:weakSelf.modifyCell.model indexPath:[NSIndexPath indexPathForRow:weakSelf.subDetailSegmentView.selectedSegmentIndex inSection:weakSelf.detailSegmentView.selectedSegmentIndex]];
        }
    };
    
    _cancelButton = [GMButton buttonWithType:UIButtonTypeCustom];
    [_cancelButton setBackgroundImage:[UIImage imageNamed:@"faceCancel"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(p_finish:) forControlEvents:UIControlEventTouchUpInside];
    [_modifyView addSubview:_cancelButton];
    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(50);
        make.left.centerY.mas_equalTo(0);
    }];
    
    _confirmButton = [GMButton buttonWithType:UIButtonTypeCustom];
    [_confirmButton setBackgroundImage:[UIImage imageNamed:@"faceConfirm"] forState:UIControlStateNormal];
    [_confirmButton addTarget:self action:@selector(p_finish:) forControlEvents:UIControlEventTouchUpInside];
    [_modifyView addSubview:_confirmButton];
    [_confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(50);
        make.right.centerY.mas_equalTo(0);
    }];
    
    [_modifyDetailsView addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)dealloc {
    @try {
        [_modifyDetailsView removeObserver:self forKeyPath:@"value"];
    }
    @catch (NSException *exception) {
        NSLog(@"Exception: %@", exception);
    }
    @finally  {
        // Added to show finally works as well
    }
}

@end
