//
//  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 {
    [self postData];
}
- (void)loadChannelModel
{
    [self.channelSelectArr removeAllObjects];
//    ChannelModel * model = [[ChannelModel alloc] init];
//    model.ArticleGroupId = 0;
//    model.ArticleGroupName = @"推荐";
//    model.IsSelect = YES;
//    [self.channelSelectArr addObject:model];
//    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];
//    ChannelModel * aModel = [[ChannelModel alloc] init];
//    aModel.ArticleGroupId = 4;
//    aModel.ArticleGroupName = @"会员特供";
//    aModel.IsSelect = NO;
//    [self.channelSelectArr addObject:aModel];
//    ChannelModel * bModel = [[ChannelModel alloc] init];
//    bModel.ArticleGroupId = 5;
//    bModel.ArticleGroupName = @"每日微课";
//    bModel.IsSelect = NO;
//    [self.channelSelectArr addObject:bModel];
//    ChannelModel * cModel = [[ChannelModel alloc] init];
//    cModel.ArticleGroupId = 6;
//    cModel.ArticleGroupName = @"每日技能";
//    cModel.IsSelect = NO;
//    [self.channelSelectArr addObject:cModel];
//    ChannelModel * dModel = [[ChannelModel alloc] init];
//    dModel.ArticleGroupId = 7;
//    dModel.ArticleGroupName = @"每日好书";
//    dModel.IsSelect = NO;
//    [self.channelSelectArr addObject:dModel];
//    ChannelModel * eModel = [[ChannelModel alloc] init];
//    eModel.ArticleGroupId = 8;
//    eModel.ArticleGroupName = @"每日好文";
//    eModel.IsSelect = NO;
//    [self.channelSelectArr addObject:eModel];
//    ChannelModel * fModel = [[ChannelModel alloc] init];
//    fModel.ArticleGroupId = 9;
//    fModel.ArticleGroupName = @"名师";
//    fModel.IsSelect = NO;
//    [self.channelSelectArr addObject:fModel];
//    ChannelModel * gModel = [[ChannelModel alloc] init];
//    gModel.ArticleGroupId = 10;
//    gModel.ArticleGroupName = @"大咖讲座";
//    gModel.IsSelect = NO;
//    [self.channelSelectArr addObject:gModel];
}
- (void)getData
{
    WS(weakSelf);
    [self.channelMainArr removeAllObjects];
    [self.channelSelectArr removeAllObjects];
    [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 NO;
    }
    if (indexPath.section == 1) {
        return NO;
    }
    return YES;
}

// 在移动结束的时候调用此代理方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    if (destinationIndexPath.section == 0 && sourceIndexPath.section == 0) {
        ChannelModel * model = self.channelSelectArr[sourceIndexPath.item];
//        ChannelModel * smodel = self.channelSelectArr[destinationIndexPath.item];
        [self.channelSelectArr  removeObject:model];
        [self.channelSelectArr insertObject:model atIndex:destinationIndexPath.item];
        [self.channelMainArr replaceObjectAtIndex:0 withObject:self.channelSelectArr];
        [self.collectionView reloadData];
//    }else{
//        ChannelModel * model = self.channelSelectArr[sourceIndexPath.item];
//        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) {
//
//            }];
//        }
    }
//    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 {
        if (indexPath.item == 0) {
            cell.deleteButton.hidden = YES;
        }else{
            cell.deleteButton.hidden = NO;
            cell.deleteButton.tag = indexPath.item;
            [cell.deleteButton addTarget:self action:@selector(deleteChannelAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        ChannelModel * model = self.channelOtherArr[indexPath.item];
        if (model) {
            [self.channelOtherArr removeObject:model];
            [self.channelSelectArr addObject:model];
            [self.collectionView reloadData];
        }
    }
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    MyChanelCollectionViewCell *cell;
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
            if (indexPath.item == 0 && indexPath.section == 0) {
                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.item == 0 && indexPath.section == 0) {
                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 {
    ChannelModel * model = self.channelSelectArr[sender.tag];
    if (model) {
        [self.channelOtherArr addObject:model];
        [self.channelSelectArr removeObject:model];
        [self.collectionView reloadData];
    }
}
#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;
}
- (void)postData
{
    WS(weakSelf);
    NSMutableArray * array = [NSMutableArray array];
    NSMutableArray * sArray = self.channelMainArr.firstObject;
    for (NSInteger i = 1; i < sArray.count; i ++) {
        ChannelModel *model = sArray[i];
        [array addObject:[NSNumber numberWithInteger:model.ArticleGroupId]];
    }
    [[HttpManager sharedHttpManager] POSTUrl:Host(Article_Pindao_User_Delete) parameters:@{@"ArticleGroupId":array} responseStyle:DATA success:^(id  _Nonnull responseObject) {
        if ([weakSelf.delegate respondsToSelector:@selector(upadateChannel)]) {
            [weakSelf.delegate upadateChannel];
        }
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
@end