//
//  AddChannelController.m
//  TheoryNetwork
//
//  Created by tederen on 2019/9/20.
//  Copyright © 2019 tederen. All rights reserved.
//

#import "AddChannelController.h"
#import "TDHorizontalWaterFlowLayout.h"
#import "MyChanelCollectionReusableViewTop.h"
#import "MyChanelCollectionViewCell.h"
#import "ChannelModel.h"
#import "AddChanelNoDataCell.h"

@interface AddChannelController () <UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) TDHorizontalWaterFlowLayout *layout;
@property (strong, nonatomic) TDButton *dismissButton;

@property (copy, nonatomic) NSMutableArray *channelMainArr;
@property (copy, nonatomic) NSMutableArray *channelSelectArr;
@property (copy, nonatomic) NSMutableArray *channelOtherArr;


@end

@implementation AddChannelController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = YES;
    [self createCollectionView];
    [self getData];
    [self.view addSubview:self.dismissButton];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self.collectionView.collectionViewLayout invalidateLayout];
}

- (void)dismissAction {
    if ([self.delegate respondsToSelector:@selector(upadateChannel)]) {
        [self.delegate upadateChannel];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)loadChannelModel
{
    [self.channelSelectArr removeAllObjects];
    ChannelModel * model = [[ChannelModel alloc] init];
    model.ArticleGroupId = 0;
    model.ArticleGroupName = @"推荐";
    model.IsSelect = YES;
    [self.channelSelectArr addObject:model];
//    ChannelModel * workModel = [[ChannelModel alloc] init];
//    workModel.ArticleGroupId = 1;
//    workModel.ArticleGroupName = @"待办工作";
//    workModel.IsSelect = NO;
//    [self.channelSelectArr addObject:workModel];
    ChannelModel * sModel = [[ChannelModel alloc] init];
    sModel.ArticleGroupId = 2;
    sModel.ArticleGroupName = @"信源听说";
    sModel.IsSelect = NO;
    [self.channelSelectArr addObject:sModel];
    ChannelModel * mModel = [[ChannelModel alloc] init];
    mModel.ArticleGroupId = 3;
    mModel.ArticleGroupName = @"名校";
    mModel.IsSelect = NO;
    [self.channelSelectArr addObject:mModel];
}
- (void)getData
{
    WS(weakSelf);
    [self.channelMainArr removeAllObjects];
    [self loadChannelModel];
    [self.channelOtherArr removeAllObjects];
    
    [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,Article_Pindao_User_Post] parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *array = responseObject;
            for (NSInteger i = 0 ; i < array.count; i ++) {
                NSDictionary *dic = array[i];
                ChannelModel *model = [ChannelModel modelWithDictionary:dic];
                [weakSelf.channelSelectArr addObject:model];
            }
            [[HttpManager sharedHttpManager] GETUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,Article_Pindao_Post] parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
                if ([responseObject isKindOfClass:[NSArray class]]) {
                    NSArray *array = responseObject;
                    for (NSDictionary * dic in array) {
                        ChannelModel *model = [ChannelModel modelWithDictionary:dic];
                        [weakSelf.channelOtherArr addObject:model];
                    }
                    [weakSelf.channelMainArr addObject:weakSelf.channelSelectArr];
                    [weakSelf.channelMainArr addObject:weakSelf.channelOtherArr];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.collectionView reloadData];
                    });
                }
            } failure:^(NSError * _Nonnull error) {
                REMOVESHOW
            }];
        }
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
    }];
}

- (void)createCollectionView {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    CGFloat itemWidth = (kGXScreenWidth - (3 * 12.f)) / 4;
//    flowLayout.itemSize = CGSizeMake(itemWidth - 8.f, 42.f);
//    flowLayout.minimumLineSpacing = 12.f;
//    flowLayout.minimumInteritemSpacing = 12.f;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12,Height_Layout(74), kGXScreenWidth - 24.f, kGXScreenHeigh - (Height_Layout(74))) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.scrollEnabled = YES;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 12.f, 0);
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyChanelCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyChanelCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"AddChanelNoDataCell" bundle:nil] forCellWithReuseIdentifier:@"AddChanelNoDataCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyChanelCollectionReusableViewTop" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyChanelCollectionReusableViewTop"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    [self.collectionView addGestureRecognizer:longPressGesture];
    [self.view addSubview:self.collectionView];
}
    
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.channelMainArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *array = self.channelMainArr[section];
    if (section == 1 && array.count == 0) {
        return 1;
    }
    return array.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (self.channelOtherArr.count > 0) {
            CGFloat itemWidth = (kGXScreenWidth - (3 * 12.f)) / 4;
            return CGSizeMake(itemWidth - 8.f, 42.f);
        }else{
            return CGSizeMake(SCREEN_WIDTH, 120.f);
        }
    }else{
        CGFloat itemWidth = (kGXScreenWidth - (3 * 12.f)) / 4;
        return CGSizeMake(itemWidth - 8.f, 42.f);
    }
}
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(0, 0, 0, 0);;
//}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 12.f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 12.f;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    MyChanelCollectionReusableViewTop *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyChanelCollectionReusableViewTop" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        headerView.labelTitle.text = @"我的频道";
        headerView.labelDetail.text = @"长按可拖动排序";
    }else{
        headerView.labelTitle.text = @"更多频道";
        headerView.labelDetail.text = @"点击添加到我的频道";
    }
    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kGXScreenWidth, 72);
}

- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.item == 0) {
        return false;
    }
    if (indexPath.section == 1) {
        return false;
    }
    return true;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.item == 0) {
        return false;
    }
    if (indexPath.section == 1) {
        return false;
    }
    return true;
}

// 在移动结束的时候调用此代理方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    NSMutableArray *arraySource = @[].mutableCopy;
    NSMutableArray *arrayDestination = @[].mutableCopy;
    if (sourceIndexPath.section == 0) {
        arraySource = self.channelSelectArr;
    } else {
        arraySource = self.channelOtherArr;
    }
    if (destinationIndexPath.section == 0) {
        arrayDestination = self.channelSelectArr;
    } else {
        arrayDestination = self.channelOtherArr;
    }

    NSString *string = arraySource[sourceIndexPath.row];
    [arraySource removeObjectAtIndex:sourceIndexPath.row];
    [arrayDestination insertObject:string atIndex:destinationIndexPath.row];
    [self.channelMainArr removeAllObjects];
    [self.channelMainArr addObject:self.channelSelectArr];
    [self.channelMainArr addObject:self.channelOtherArr];
    [self.collectionView reloadData];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyChanelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyChanelCollectionViewCell" forIndexPath:indexPath];
    NSArray *arrayTmp = self.channelMainArr[indexPath.section];
    ChannelModel *model = arrayTmp[indexPath.row];
    cell.labelTitle.text = model.ArticleGroupName.length ? model.ArticleGroupName : model.Name;
    if (indexPath.section) {
        if (arrayTmp.count > 0) {
            cell.deleteButton.hidden = YES;
            cell.labelTitle.text = [NSString stringWithFormat:@"+%@",model.ArticleGroupName.length ? model.ArticleGroupName : model.Name];
            return cell;
        }else{
            AddChanelNoDataCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddChanelNoDataCell" forIndexPath:indexPath];
            return cell;
        }
    } else {
        cell.deleteButton.hidden = NO;
        if ((indexPath.item == 0) || (indexPath.item == 1)||(indexPath.item == 2)||(indexPath.item == 3)) {
            cell.deleteButton.hidden = YES;
        }
        cell.deleteButton.tag = indexPath.row;
        [cell.deleteButton addTarget:self action:@selector(deleteChannelAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        WS(weakSelf);
        ChannelModel * model = self.channelOtherArr[indexPath.item];
        if (model) {
            [[HttpManager sharedHttpManager] POSTUrl:Host(Article_Pindao_User_add) parameters:@{@"ArticleGroupId":@(model.Id)} responseStyle:DATA success:^(id  _Nonnull responseObject) {
                [weakSelf getData];
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
    }
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    MyChanelCollectionViewCell *cell;
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            if (indexPath == nil||indexPath.item == 0||indexPath.section == 1 || indexPath.item == 1) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            cell = (MyChanelCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            cell.isEditing = YES;
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:{
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            if (indexPath == nil||indexPath.item == 0||indexPath.section == 1 || indexPath.item == 1) {
                break;
            }
            //移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
        }break;
        case UIGestureRecognizerStateEnded:
            //移动结束后关闭cell移动
            cell.isEditing = NO;
            [self.collectionView endInteractiveMovement];
            break;
        default:
            cell.isEditing = NO;
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

- (void)deleteChannelAction:(UIButton *)sender {
    WS(weakSelf);
    ChannelModel * model = self.channelSelectArr[sender.tag];
    if (model) {
        NSString * url = [NSString stringWithFormat:@"%@%ld",Host(Article_Pindao_User_Delete),(long)model.Id];
        [[HttpManager sharedHttpManager] DeleteUrl:url parameters:@{} responseStyle:DATA success:^(id  _Nonnull responseObject) {
            [weakSelf getData];
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark - setter
- (TDHorizontalWaterFlowLayout *)layout {
    if (!_layout) {
        _layout = [[TDHorizontalWaterFlowLayout alloc] init];
        _layout.dataList = self.channelMainArr;
    }
    return _layout;
}

- (NSMutableArray *)channelMainArr {
    if (!_channelMainArr) {
        _channelMainArr = [NSMutableArray array];
    }
    return _channelMainArr;
}

- (NSMutableArray *)channelSelectArr {
    if (!_channelSelectArr) {
        _channelSelectArr = [NSMutableArray array];
    }
    return _channelSelectArr;
}

- (NSMutableArray *)channelOtherArr {
    if (!_channelOtherArr) {
        _channelOtherArr = [NSMutableArray array];
    }
    return _channelOtherArr;
}

- (TDButton *)dismissButton {
    if (!_dismissButton) {
        _dismissButton = [[TDButton alloc] init];
        _dismissButton.frame = CGRectMake(kGXScreenWidth - (Width_Layout(50)),kStatusBarHeight,Width_Layout(40), Height_Layout(40));
        [_dismissButton setCurrentButtonHotSize:CGSizeZero];
        [_dismissButton setImage:IMG(@"icon_dissmiss") forState:UIControlStateNormal];
        [_dismissButton addTarget:self action:@selector(dismissAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dismissButton;
}
@end