//
//  GMToFaceContainerViewController.m
//  Gengmei
//
//  Created by zhouLiang on 2020/2/19.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMToFaceContainerViewController.h"
#import "GMToFaceDoctorListController.h"
#import "JXPagerListRefreshView.h"
#import "JXCategoryView.h"
#import <GMRefresh/GMRefreshHeader.h>
#import "GMToFaceDoctorListModel.h"
#import "GMToFaceDoctorBlockInfoView.h"
#import "GMBasicInfoCardView.h"
#import "GMToFaceDoctorListNewHeaderView.h"

@interface GMToFaceContainerViewController ()<GMInfinitelViewDelegate, UIScrollViewDelegate>
/** 头部视图 */
@property (nonatomic, strong) GMToFaceDoctorListNewHeaderView *contentHeaderView;
/** 网络监听 */
@property (nonatomic, strong) NSMutableArray *tabInfoArray;
@property (nonatomic, strong) NSMutableArray *childControllers;
@property (nonatomic, strong) GMToFaceDoctorListModel *recommendDoctorListModel;
/** 封禁的view */
@property (nonatomic, strong) GMToFaceDoctorBlockInfoView *blockInfoView;
/** 是否需要请求下面的医生列表 */
@property (nonatomic, assign) BOOL isReloadList;
/** 如果要是登录成功过来的就不用请求viewWillAppear接口了，因为登录成功也会请求 */
@property (nonatomic, assign) BOOL isLoginSuccess;
/** 底部立即视频面诊按钮 */
@property (nonatomic, strong) UIImageView *bottomView;
@end

@implementation GMToFaceContainerViewController
@synthesize viewModel;
- (void)initController {
    [super initController];
    self.pageName = @"video_face_consultation";
    self.viewModel = [[GMToFaceDoctorListViewModel alloc] init];
    self.immediateLoad = NO;
    _needHeaderRefresh = NO;
    self.needExpo = YES;
    self.subViewVc = self;
    self.segmentFullScreen = NO;
    self.controlNavigationByYou = YES;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //此时进来的请求不需要更新下面的列表，因为目的是刷新 关注 的状态
    self.isReloadList = _recommendDoctorListModel != nil;
    if (self.isLoginSuccess) {
        return;
    }
    [self prepareToLoad];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setconfig];
    [self reSetSegmentView];
    [self.view addSubview:self.blockInfoView];
    [self.blockInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(OCNavigationBar.barHeight);
    }];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(70+UIView.safeAreaInsetsBottom);
    }];
    self.navigationBar.isShowShadow = NO;
    self.fd_interactivePopDisabled = YES;
    self.navigationBar.title = @"更美视频面诊";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDoctorListMethod) name:LOGIN_SUCCESS_NOTIFICATION object:nil];
    
}
- (void)backAction:(OCNavigationBarButton *)button {
    [super backAction:button];
    [Phobos track:@"on_click_button" attributes:@{@"page_name":self.pageName,
                                                  @"button_name":@"exit",
                                                  @"business_id":SafeString(self.businessId)
    }];
}
- (void)setconfig {
    __weak __typeof(self)weakSelf = self;
    CGFloat pagerViewH = MAINSCREEN_HEIGHT - OCNavigationBar.barHeight;
    self.pagerView.hidden = YES;
    self.pagerView.frame = CGRectMake(0, OCNavigationBar.barHeight, MAINSCREEN_WIDTH, pagerViewH);
    self.pagerView.mainTableView.mj_header = [GMRefreshHeader headerWithRefreshingBlock:^{
        weakSelf.isReloadList = NO;
        [weakSelf prepareToLoad];
    }];
}
- (void)reSetSegmentView {
    self.segmentView.isShowShadow = NO;
    self.segmentView.backgroundColor = GMColorF7F6FA;
    self.segmentView.indicatorColor = GMColorFF8C8D;
    self.segmentView.height = 74.f;
    self.segmentView.titleTextAttributes = @{NSFontAttributeName:[UIFont gmBoldFont:15],
                                             NSForegroundColorAttributeName:GMColor696969};
    self.segmentView.selectedTitleTextAttributes = @{NSFontAttributeName:[UIFont gmBoldFont:16],
                                                     NSForegroundColorAttributeName:GMColor2A2828};
}
- (void)setupChildViews {
    CGFloat height = self.recommendDoctorListModel.recommendsCounsellors.count > 0 ? [GMToFaceDoctorListNewHeaderView viewHeight] : 0;
    self.contentHeaderView.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, height);
    [self layoutHomeSubviews];
    // 整体headView
    self.headViewHeight = self.contentHeaderView.height;
    self.headerView = self.contentHeaderView;
    self.contentHeaderView.hidden = height == 0;
    self.blockInfoView.blockInfo = self.recommendDoctorListModel.blockInfo;
    self.contentHeaderView.dataArray = self.recommendDoctorListModel.recommendsCounsellors;
    [self.pagerView reloadData];
}
- (void)prepareToLoad {
    if (!self.isReloadList) {
        //此时是非viewWillAppear时进行的请求
        [self showLoading:nil];
    }
    __weak typeof(self)weakSelf = self;
    [[GMInterfaceNetwork shareInstance] excuteToFaceRecommendDoctorsSuccessBlock:^(id response) {
        NSError *error = [[NSError alloc] init];
        weakSelf.recommendDoctorListModel = [[GMToFaceDoctorListModel alloc] initWithDictionary:response error:&error];
        [weakSelf loadHome];
        //登录成功回调完成后就置为NO
        weakSelf.isLoginSuccess = NO;
        weakSelf.bottomView.hidden = NO;
        weakSelf.pagerView.hidden = NO;
    } failureBlock:^(NSInteger errorCode, NSString *message) {
        //登录成功回调完成后就置为NO
        weakSelf.pagerView.hidden = NO;
        weakSelf.isLoginSuccess = NO;
        [weakSelf showLoading:nil];
        [weakSelf toast:message];
        [weakSelf showEmptyView:GMEmptyViewTypeException];
    }];
}
- (void)loadHome {
    [self headerRefresh];
    [self.pagerView.mainTableView.mj_header endRefreshing];
    [self setupChildViews];
    [self hideEmptyView];
    [self isAddEmptyView];
    [self hideLoading];
}

#pragma mark - tab 数据刷新
- (void)headerRefresh {
    // 请求tab下controller
    NSInteger selectedIndex = self.segmentView.selectedSegmentIndex;
    if (selectedIndex < self.viewControllers.count) {
        if (self.recommendDoctorListModel.tabs.count == 0) {
            return;
        }
        //如果isReloadList = YES是为了刷新医生是否被关注，所以医生列表接口不用请求
        if (self.isReloadList) {
            return;
        }
        GMToFaceDoctorListController *vc = (GMToFaceDoctorListController *)self.viewControllers[selectedIndex];
        vc.viewModel.page = 1;
        GMToFaceTabs *firTabs = self.recommendDoctorListModel.tabs[selectedIndex];
        vc.viewModel.tabId = firTabs.id;
        vc.viewModel.tabName = firTabs.name;
        [vc requestData];
    }
}
- (void)isAddEmptyView {
    if (self.recommendDoctorListModel.tabs.count == 0 && self.recommendDoctorListModel.recommendsCounsellors.count == 0) {
        [self showEmptyView:GMEmptyViewTypeEmpty];
    }else {
        [self hideEmptyView];
    }
}
- (void)emptyViewDidClickReload {
    [self hideEmptyView];
    self.isReloadList = NO;
    [self prepareToLoad];
}

- (void)layoutHomeSubviews {
    NSMutableArray *tabNames = [NSMutableArray array];
    [self.recommendDoctorListModel.tabs enumerateObjectsUsingBlock:^(GMToFaceTabs *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [tabNames addObject:obj.name];
    }];
    self.segmentView.sectionTitles = tabNames;
    self.tabName = tabNames.firstObject;
    __weak __typeof(self)weakSelf = self;
    self.segmentView.didSelectedBlock = ^(NSUInteger index) {
        [weakSelf.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        [weakSelf segmentDidSelectedIndex:index];
        GMToFaceTabs *tabs = weakSelf.recommendDoctorListModel.tabs[index];
        [Phobos track:@"on_click_tab" attributes:@{@"page_name":SafeString(weakSelf.pageName),
                                                   @"position":@(index),
                                                   @"tab_name":SafeString(tabs.name),
                                                   @"business_id":SafeString(weakSelf.businessId)
        }];
    };
    self.segmentView.updateIndicatorFrame = ^(UIView *indicator, UIButton *button) {
        // 在 _sectionTitles 还没有数据时，button 并没有被添加，会是 nil, 所以添加如下判断
        if (button == nil || indicator == nil) {
            return;
        }
        // 改变indicator
        indicator.frame = CGRectMake(button.titleLabel.width * 1 / 6, CGRectGetMaxY(button.frame)-25, button.titleLabel.width * 2 / 3, 3);
        indicator.centerX = button.centerX;
        indicator.layer.cornerRadius = 3/2.f;
        indicator.layer.masksToBounds = YES;
    };
    [self.segmentView setSelectedSegmentIndex:self.index animated:YES];
    [self.segmentView layoutSegments];
}

- (void)pagerView:(JXPagerView *)pagerView didScroll:(NSInteger)row {
    if (self.index != row) {
        [self switchToNextControllerAtIndex:row];
        [self.segmentView setSelectedSegmentIndex:row animated:YES];
        [self segmentDidSelectedIndex:row];
    }
}

- (void)switchToNextControllerAtIndex:(NSInteger)index {
    GMToFaceDoctorListController *to  = (GMToFaceDoctorListController *)self.viewControllers[index];
    GMToFaceDoctorListController *from = (GMToFaceDoctorListController *)self.viewControllers[self.index];
    [to beginAppearanceTransition:YES animated:NO];
    
    [from beginAppearanceTransition:NO animated:NO];
    [to endAppearanceTransition];
    
    [[GMExposureManager sharedManager] clearExposureDataForPage:self];
    [from endAppearanceTransition];
}

- (void)segmentDidSelectedIndex:(NSInteger)index {
    GMToFaceTabs *tabs = self.recommendDoctorListModel.tabs[index];
    self.tabName = self.segmentView.sectionTitles[index];
    self.index = index;
    UIViewController *viewCtrl = (UIViewController *)self.viewControllers[index];
    GMToFaceDoctorListController *doctorCtrl = (GMToFaceDoctorListController *)viewCtrl;
    if (!doctorCtrl.viewModel.dataArray || doctorCtrl.viewModel.dataArray.count == 0) {
        doctorCtrl.viewModel.page = 1;
        doctorCtrl.viewModel.tabId = tabs.id;
        doctorCtrl.viewModel.tabName = tabs.name;
        [doctorCtrl requestData];
    }
}
#pragma mark - 立即视频面诊
- (void)bottomBtnClick {
    [Phobos track:@"on_click_button" attributes:@{@"page_name":self.pageName,@"button_name":@"video_interview_now"}];
    __weak __typeof(self)weakSelf = self;
    [[GMInterfaceNetwork shareInstance] excuteToFaceBlockInfoSuccessBlock:^(id response) {
        NSDictionary *dict = response[@"block_info"];
        NSString *alert = dict[@"alert"];
        if (![alert isNonEmpty]) {
            //未被禁止
            //请求用户填面诊信息的弹框
            GMBasicInfoCardView *cardView = [GMBasicInfoCardView new];
            cardView.isDispatch = YES;
            cardView.tabName = @"dispatch";
            [GMBasicInfoCardView showWithCorrectFrameView:cardView resultBlock:nil];
        }else {
            //被禁止
            weakSelf.blockInfoView.blockInfo = alert;
            weakSelf.blockInfoView.hidden = NO;
        }
    } failureBlock:^(NSInteger errorCode, NSString *message) {
        [GMHudModule toast:message];
    }];
}
- (void)mainTableViewDidScroll:(UIScrollView *)scrollView {
    self.navigationBar.isShowShadow = scrollView.contentOffset.y >= self.headViewHeight;
}

- (NSMutableArray *)childControllers {
    if (!_childControllers || _childControllers.count == 0) {
        NSMutableArray *childControllers = [NSMutableArray array];
        __weak __typeof(self)weakSelf = self;
        [self.recommendDoctorListModel.tabs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            GMToFaceDoctorListController *service = [[GMToFaceDoctorListController alloc] init];
            service.topViewHeight = weakSelf.headViewHeight;
            service.navigationBar.hidden = YES;
            service.blockInfoCallback = ^(NSString *blockInfo) {
                weakSelf.blockInfoView.hidden = ![blockInfo isNonEmpty];
                weakSelf.blockInfoView.blockInfo = blockInfo;
            };
            [weakSelf synchronizePVData:service];
            [childControllers addObject:service];
        }];
        _childControllers = childControllers;
    }
    return _childControllers;
}

- (NSArray<UIViewController *> *)viewControllers {
    return self.childControllers;
}

- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 禁止collectionview左右滑动的时候，上下和左右都可以滚动
    if (otherGestureRecognizer == self.contentHeaderView.collectView.panGestureRecognizer) {
        return NO;
    }
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    UIViewController *viewCtrl = (UIViewController *)self.viewControllers[index];
    return viewCtrl;
}
#pragma mark - 登录成功重新请求接口
- (void)updateDoctorListMethod {
    if (self.isLoginSuccess == YES) {
        return;
    }
    self.isLoginSuccess = YES;
    self.isReloadList = YES;
     [self prepareToLoad];
}

- (GMToFaceDoctorListNewHeaderView *)contentHeaderView {
    if (!_contentHeaderView) {
        _contentHeaderView = [[GMToFaceDoctorListNewHeaderView alloc] init];
        _contentHeaderView.pageCtrl = self;
        __weak __typeof(self)weakSelf = self;
        _contentHeaderView.blockInfoCallback = ^(NSString * _Nonnull blockInfo) {
            weakSelf.blockInfoView.hidden = ![blockInfo isNonEmpty];
            weakSelf.blockInfoView.blockInfo = blockInfo;
        };
    }
    return _contentHeaderView;
}
- (GMToFaceDoctorListModel *)recommendDoctorListModel {
    if (!_recommendDoctorListModel) {
        _recommendDoctorListModel = [[GMToFaceDoctorListModel alloc] init];
    }
    return _recommendDoctorListModel;
}
- (GMToFaceDoctorBlockInfoView *)blockInfoView {
    if (!_blockInfoView) {
        _blockInfoView = [[GMToFaceDoctorBlockInfoView alloc] init];
        _blockInfoView.hidden = YES;
    }
    return _blockInfoView;
}

- (UIImageView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"to_face_alpha_bottomView"]];
        _bottomView.hidden = YES;
        _bottomView.userInteractionEnabled = YES;
        GMButton *bottomBtn = [GMButton buttonWithType:(UIButtonTypeCustom)];
        bottomBtn.multiControlTimeInterva = 2.f;
        [bottomBtn addTarget:self action:@selector(bottomBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
        [bottomBtn setImage:[UIImage imageNamed:@"to_face_bottomView_icon"] forState:(UIControlStateNormal)];
        [_bottomView addSubview:bottomBtn];
        [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_bottomView.mas_centerX);
            make.bottom.mas_equalTo(-16-UIView.safeAreaInsetsBottom);
        }];
    }
    return _bottomView;
}

@end
