//
//  MoreAppVC.m
//  smartRhino
//
//  Created by armin on 2019/11/5.
//  Copyright © 2019 tederen. All rights reserved.
//

#import "MoreAppVC.h"
#import "MoreAppCell.h"

@interface MoreAppVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong,nonatomic) UICollectionView *collectionView;

@property (strong,nonatomic) NSMutableArray   *dataSourceArray;

@property (nonatomic,assign) BOOL     isBeganMove;
@end

@implementation MoreAppVC

+(MoreAppVC *)initMoreAppVC{
    MoreAppVC *controller = [StoryboardManager.shared.chatMsg instantiateViewControllerWithIdentifier:@"MoreAppVC"];
    return controller;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.loadMenuBlock) {
        self.loadMenuBlock();
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initDataSourceInfo];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    [self.view addSubview:self.collectionView];
    WS(weakSelf);
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(@(0));
        make.top.equalTo(@(kStatusBarHeight));
    }];
    [self.collectionView setBackgroundColor:[UIColor whiteColor]];
    [self.collectionView registerNib:[UINib nibWithNibName:@"MoreAppCell" bundle:nil] forCellWithReuseIdentifier:@"MoreAppCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView"];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.alwaysBounceVertical = YES;
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];
    [self.collectionView reloadData];
}
#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            if (!self.isBeganMove) {
                self.isBeganMove = YES;
                //获取点击的cell的indexPath
                NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
                //开始移动对应的cell
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:selectedIndexPath];
                for (MoreAppCell *cell in [self.collectionView visibleCells]) {
                    [self starShake:cell];
                }
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            //移动cell
            [self.collectionView updateInteractiveMovementTargetPosition:[gesture locationInView:self.collectionView]];
            break;
        }
        case UIGestureRecognizerStateEnded: {
            self.isBeganMove = NO;
            //结束移动
            [self.collectionView endInteractiveMovement];
            for (MoreAppCell *cell in [self.collectionView visibleCells]) {
                [self stopShake:cell];
            }
            break;
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}
- (void)starShake:(MoreAppCell*)cell{
    CAKeyframeAnimation * keyAnimaion = [CAKeyframeAnimation animation];
    keyAnimaion.keyPath = @"transform.rotation";
    keyAnimaion.values = @[@(-3 / 180.0 * M_PI),@(3 /180.0 * M_PI),@(-3/ 180.0 * M_PI)];//度数转弧度
    keyAnimaion.removedOnCompletion = NO;
    keyAnimaion.fillMode = kCAFillModeForwards;
    keyAnimaion.duration = 0.3;
    keyAnimaion.repeatCount = MAXFLOAT;
    [cell.layer addAnimation:keyAnimaion forKey:@"cellShake"];
}
- (void)stopShake:(MoreAppCell*)cell{
    [cell.layer removeAnimationForKey:@"cellShake"];
}
/**********************************************************************/
#pragma mark -构造WQRefreshCollectionView的数据源对象
/**********************************************************************/
-(void)initDataSourceInfo{
    NSDictionary * chatMenuDict = [[NSUserDefaults standardUserDefaults] objectForKey:CHATMENUBAR];
    for(int m=0;m<2;m++){
        MoreAppModel *bean = [[MoreAppModel alloc] init];
        switch (m) {
            case 0:{
                bean.sectionTitle = @"常用应用";
                bean.isCloseSectionFlag = YES;
                NSArray * array = [chatMenuDict objectForKey:@"common"];
                NSMutableArray * muArray = [NSMutableArray array];
                for (NSDictionary * dict in array) {
                    MoreAppInfoModel * model = [MoreAppInfoModel modelWithDictionary:dict];
                    [muArray addObject:model];
                }
                bean.moreAppInfoArray = muArray;
            }break;
            case 1:{
                bean.sectionTitle = @"更多应用";
                NSArray * array = [chatMenuDict objectForKey:@"more"];
                NSMutableArray * muArray = [NSMutableArray array];
                for (NSDictionary * dict in array) {
                    MoreAppInfoModel * model = [MoreAppInfoModel modelWithDictionary:dict];
                    [muArray addObject:model];
                }
                bean.moreAppInfoArray = muArray;
            }break;
            default:
                break;
        }
        [self.dataSourceArray addObject:bean];
    }
}

/**********************************************************************/
#pragma mark -UICollectionViewDataSource
/**********************************************************************/
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataSourceArray.count;
}

/**********************************************************************/
#pragma mark -GHRefreshCollectionView的section的Count
/**********************************************************************/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    MoreAppModel *bean = [self.dataSourceArray objectAtIndex:section];
    return bean.moreAppInfoArray.count;
}

#pragma mark - UICollectionViewDelegate
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MoreAppModel *bean = [self.dataSourceArray objectAtIndex:indexPath.section];
    MoreAppInfoModel *beanItem = [bean.moreAppInfoArray objectAtIndex:indexPath.item];
    MoreAppCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MoreAppCell" forIndexPath:indexPath];
    cell.showTitleLabel.text = beanItem.title;
    if (indexPath.section == 0 && indexPath.item == 0) {
    }else{
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        cell.userInteractionEnabled = YES;
        [cell addGestureRecognizer:longPressGesture];
    }
    if(beanItem.showEditFlag){
        cell.showIcon.hidden = NO;
        cell.showImgView.image = [UIImage imageNamed:beanItem.imgName];
    }else{
        cell.showIcon.hidden = YES;
        cell.showImgView.image = [UIImage imageNamed:beanItem.notImgName];
    }
    if(indexPath.section == 0){
        [cell.showIcon setImage:[UIImage imageNamed:@"chatmsg_edit_del_icon"]];
    }
    else if (indexPath.section == 1){
        [cell.showIcon setImage:[UIImage imageNamed:@"chatmsg_edit_add_icon"]];
    }
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat w = SCREEN_WIDTH * 0.2;
    CGFloat h = 70;
    return CGSizeMake(w, h);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    MoreAppModel *bean = [self.dataSourceArray objectAtIndex:indexPath.section];
    MoreAppInfoModel *beanItem = [bean.moreAppInfoArray objectAtIndex:indexPath.item];
    if(indexPath.section == 0){
        if (indexPath.item == 0) {
            return;
        }
        [bean.moreAppInfoArray removeObject:beanItem];
        MoreAppModel *moreModel = [self.dataSourceArray lastObject];
        [moreModel.moreAppInfoArray addObject:beanItem];
        NSMutableArray * moreArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in moreModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [moreArray addObject:dict];
        }
        
        MoreAppModel *commonModel = [self.dataSourceArray firstObject];
        NSMutableArray * commonArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in commonModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [commonArray addObject:dict];
        }
        [[NSUserDefaults standardUserDefaults] setObject:@{@"common":commonArray,@"more":moreArray} forKey:CHATMENUBAR];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self.collectionView reloadData];
    }else {
        [bean.moreAppInfoArray removeObject:beanItem];
        MoreAppModel *commonModel = [self.dataSourceArray firstObject];
        [commonModel.moreAppInfoArray addObject:beanItem];
        NSMutableArray * commonArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in commonModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [commonArray addObject:dict];
        }
        MoreAppModel *moreModel = [self.dataSourceArray lastObject];
        NSMutableArray * moreArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in moreModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [moreArray addObject:dict];
        }
        [[NSUserDefaults standardUserDefaults] setObject:@{@"common":commonArray,@"more":moreArray} forKey:CHATMENUBAR];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self.collectionView reloadData];
    }
}

//footer的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(0, 0);
}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 50);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.f;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.f;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
   MoreAppModel *bean = [self.dataSourceArray objectAtIndex:indexPath.section];
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView" forIndexPath:indexPath];
        [headerView removeAllSubviews];
        
        if(indexPath.section == 0){
            UILabel *label = [[UILabel alloc] init];
            [headerView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(headerView).with.offset(0);
                make.left.equalTo(@(15));
            }];
            label.text = bean.sectionTitle;
            label.font = [UIFont systemFontOfSize:17];
            label.textColor = RGB(10, 10, 10);
            [label sizeToFit];
            
            UILabel *label1 = [[UILabel alloc] init];
            [headerView addSubview:label1];
            [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(label);
                make.left.mas_equalTo(label.mas_right).offset(15);
            }];
            label1.text = @"长按可拖动排序";//@"长按可拖动排序";
            label1.font = [UIFont systemFontOfSize:13];
            label1.textColor = RGB(153, 153, 153);
            
            UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [headerView addSubview:closeBtn];
            [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(headerView).with.offset(0);
                make.right.equalTo(@(-17));
            }];
            [closeBtn setTitle:@"" forState:UIControlStateNormal];
            [closeBtn setImage:[UIImage imageNamed:@"chatmsg_moreapp_close_icon"] forState:UIControlStateNormal];
            WS(weakSelf);
            [closeBtn setAction:^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }
        else if (indexPath.section == 1){
            UILabel *label = [[UILabel alloc] init];
            [headerView addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(headerView).with.offset(0);
                make.left.equalTo(@(15));
            }];
            label.text = bean.sectionTitle;
            label.font = [UIFont systemFontOfSize:17];
            label.textColor = RGB(10, 10, 10);
        }
        headerView.backgroundColor = [UIColor whiteColor];
        return headerView;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    WS(weakSelf);
    if (destinationIndexPath.section == 0 && destinationIndexPath.item == 0) {
        MoreAppModel *commonModel = [self.dataSourceArray firstObject];
        NSMutableArray * commonArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in commonModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [commonArray addObject:dict];
        }
        MoreAppModel *moreModel = [self.dataSourceArray lastObject];
        NSMutableArray * moreArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in moreModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [moreArray addObject:dict];
        }
        [[NSUserDefaults standardUserDefaults] setObject:@{@"common":commonArray,@"more":moreArray} forKey:CHATMENUBAR];
        [[NSUserDefaults standardUserDefaults] synchronize];
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.collectionView reloadData];
            });
        });
    }else{
        if (sourceIndexPath.section == 0) {
            if (sourceIndexPath.item == 0) {
                return;
            }
            MoreAppModel *moreModel = [self.dataSourceArray lastObject];
            MoreAppModel *commonModel = [self.dataSourceArray firstObject];
            MoreAppInfoModel * model = commonModel.moreAppInfoArray[sourceIndexPath.item];
            [commonModel.moreAppInfoArray removeObjectAtIndex:sourceIndexPath.item];
            if (destinationIndexPath.section == 0) {
                [commonModel.moreAppInfoArray insertObject:model atIndex:destinationIndexPath.item];
            }else{
                [moreModel.moreAppInfoArray insertObject:model atIndex:destinationIndexPath.item];
            }
        }else{
            MoreAppModel *moreModel = [self.dataSourceArray lastObject];
            MoreAppModel *commonModel = [self.dataSourceArray firstObject];
            MoreAppInfoModel * model = moreModel.moreAppInfoArray[sourceIndexPath.item];
            [moreModel.moreAppInfoArray removeObjectAtIndex:sourceIndexPath.item];
            if (destinationIndexPath.section == 0) {
                [commonModel.moreAppInfoArray insertObject:model atIndex:destinationIndexPath.item];
            }else{
                [moreModel.moreAppInfoArray insertObject:model atIndex:destinationIndexPath.item];
            }
        }

        MoreAppModel *commonModel = [self.dataSourceArray firstObject];
        NSMutableArray * commonArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in commonModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [commonArray addObject:dict];
        }
        MoreAppModel *moreModel = [self.dataSourceArray lastObject];
        NSMutableArray * moreArray = [NSMutableArray array];
        for (MoreAppInfoModel * model in moreModel.moreAppInfoArray) {
            NSDictionary * dict = [model modelToJSONObject];
            [moreArray addObject:dict];
        }
        [[NSUserDefaults standardUserDefaults] setObject:@{@"common":commonArray,@"more":moreArray} forKey:CHATMENUBAR];
        [[NSUserDefaults standardUserDefaults] synchronize];
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.collectionView reloadData];
            });
        });
    }
}


-(NSMutableArray *)dataSourceArray{
    if(!_dataSourceArray){
        _dataSourceArray = [[NSMutableArray alloc] init];
    }
    return _dataSourceArray;
}

@end