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

#import "GMToFaceDoctorListController.h"
#import "GMToFaceDoctorListVerCell.h"
#import "GMToFaceDoctorListModel.h"
#import "GMToFaceCommonEmptyView.h"
#import "GMBasicInfoCardView.h"
#import "UIView+GMGradient.h"
#import "GMDoctorInfoPopupView.h"
#import "RequestHeader.h"
#import "GMToFaceNetworking.h"
#import "GMLibraryHeader.h"
#import <GMBase/GMBaseTool.h>


@interface GMToFaceDoctorListController ()<UICollectionViewDelegate, UICollectionViewDataSource, GMToFaceCommonEmptyViewDelegate>
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) GMToFaceCommonEmptyView *commonEmptyView;
@end

@implementation GMToFaceDoctorListController
@synthesize viewModel;
- (void)initController {
    [super initController];
    self.pageName = @"video_face_consultation";
    self.viewModel = [[GMToFaceDoctorListViewModel alloc] init];
    self.needExpo = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self refreshFooter];
}
- (void)setUI {
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.collectView];
    [self.view addSubview:self.commonEmptyView];
    [self.collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(MAINSCREEN_HEIGHT - OCNavigationBar.barHeight - 74 - self.topViewHeight);
    }];
    [self.commonEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(MAINSCREEN_HEIGHT - OCNavigationBar.barHeight - 74);
    }];
}
- (void)refreshFooter {
    __weak typeof(self)weakSelf = self;
    self.collectView.mj_footer = [GMRefreshFooter footerWithRefreshingBlock:^{
        weakSelf.viewModel.page++;
        [weakSelf requestData];
    }];
}
- (void)requestData {
    if (self.viewModel.page == 1) {
        [[GMBaseTool getCurrentViewController] showLoading:nil];
    }
    self.commonEmptyView.hidden = YES;
    [self.viewModel excuteToFaceTabsDoctorsSuccessBlock:^(id responseObject) {
        [[GMBaseTool getCurrentViewController] hideLoading];
        if (self.viewModel.dataArray.count == 0) {
            self.commonEmptyView.type = GMToFaceCommonEmptyViewTypeEmpty;
        }
        [self.collectView.mj_footer endRefreshing];
        [self.collectView reloadData];
    } failBlock:^(NSString *message) {
        [[GMBaseTool getCurrentViewController] hideLoading];
        [self.collectView.mj_footer endRefreshing];
        self.commonEmptyView.type = GMToFaceCommonEmptyViewTypeError;
    }];
}
- (void)emptyViewDidClickReload {
    [self requestData];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.viewModel.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GMToFaceDoctorListVerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([GMToFaceDoctorListVerCell class]) forIndexPath:indexPath];
    self.tabName = self.viewModel.tabName;
    cell.pageCtrl = self;
    cell.doctorsModel = self.viewModel.dataArray[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GMToFaceRecommendsDoctors *model = self.viewModel.dataArray[indexPath.row];
    //埋点
    [self clickPhobosMethod:model indexPath:indexPath];
    if (model.status == 2) {
        [self counsellorFillInfoView:model indexPath:indexPath];
    }else {
        if (model.type == 1) {
            //医生主页            
            [[GMRouter sharedInstance] pushScheme:model.gm_url];
        }else {
            //面诊师信息页
            [self counsellorInfoView:model indexPath:indexPath];
        }
    }
}
- (void)clickPhobosMethod:(GMToFaceRecommendsDoctors *)model indexPath:(NSIndexPath *)indexPath {
    [Phobos track:@"on_click_card" attributes:@{@"page_name":SafeString(self.pageName),
                                                @"tab_name":SafeString(self.viewModel.tabName),
                                                @"card_id":SafeString(model.counsellorId),
                                                @"position":@(indexPath.item),
                                                @"referrer_link":(self.referrerLink ? : @[]),
                                                @"card_type":@"card",
                                                @"card_content_type":@"doctor",
                                                @"card_status":@(model.status),
                                                @"is_doctor_assistant":@(model.isAssistant),
                                                @"card_name":SafeString(model.name),
                                                @"good_at_project":SafeString(model.goodAt),
                                                @"transaction_type":@"-1",
                                                @"counsellor_type":@(model.type)
    }];
    [GMBaseTool getCurrentViewController].tabName = SafeString(self.viewModel.tabName);
}

- (void)counsellorFillInfoView:(GMToFaceRecommendsDoctors *)model indexPath:(NSIndexPath *)indexPath{
    BOOL status = (BOOL)[[GMRouter sharedInstance] pushScheme:@"gengmei://gm_showLoginViewIfNeeded"];

    if (status) {
        return;
    }
    if (self.indexPath == indexPath) {//目的是防止重复点击
        return;
    }
    self.collectView.userInteractionEnabled = NO;
    self.indexPath = indexPath;
    __weak __typeof(self)weakSelf = self;
    [[GMToFaceNetworking shareInstance] excuteToFaceBlockInfoSuccessBlock:^(id response) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.indexPath = nil;
        });        
        NSDictionary *dict = response[@"block_info"];
        NSString *alert = dict[@"alert"];
        if (![alert isNonEmpty]) {
            //请求用户填面诊信息的弹框
            GMBasicInfoCardView *cardView = [GMBasicInfoCardView new];
            cardView.referer = self.pageName;
            cardView.counsellorId = model.counsellorId;
            cardView.doctorId = model.doctorId;
            cardView.tabName = self.viewModel.tabName;
            [GMBasicInfoCardView showWithCorrectFrameView:cardView resultBlock:^{
                weakSelf.collectView.userInteractionEnabled = YES;
            }];
        }else {
            if (self.blockInfoCallback) {
                self.blockInfoCallback(alert);
            }
            weakSelf.collectView.userInteractionEnabled = YES;
        }
    } failureBlock:^(NSInteger errorCode, NSString *message) {
        [GMHudModule toast:message];
        weakSelf.collectView.userInteractionEnabled = YES;
    }];
}
- (void)counsellorInfoView:(GMToFaceRecommendsDoctors *)model indexPath:(NSIndexPath *)indexPath{
    //面诊师卡片
    if (self.indexPath == indexPath) {
        return;
    }
    self.indexPath = indexPath;
    self.collectView.userInteractionEnabled = NO;
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:API_CONSULTATION__COUNSEL_CONSULTANT method:GMHTTPMethodGet parameters:@{@"counsellor_id": SafeString(model.counsellorId)} completion:^(GMResponseOC * response) {
        weakSelf.indexPath = nil;
        if (response.isSuccess) {
            GMConsultantInfoModel *model = [[GMConsultantInfoModel alloc] initWithDictionary:response.data error:NULL];
            GMDoctorInfoPopupView *popupView = [[GMDoctorInfoPopupView alloc] init];
            popupView.tabName = self.viewModel.tabName;
            popupView.blockInfoCallback = ^(NSString *blockInfo) {
                if (weakSelf.blockInfoCallback) {
                    weakSelf.blockInfoCallback(blockInfo);
                }
            };
            popupView.model = model;
            [[GMBaseTool getCurrentViewController].view addSubview:popupView];
        } else {
            [[GMBaseTool getCurrentViewController] toast:response.message];
        }
        weakSelf.collectView.userInteractionEnabled = YES;
    }];
}
- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.itemSize = CGSizeMake((MAINSCREEN_WIDTH - 32) / 2, (MAINSCREEN_WIDTH - 32) / 2 + 104.5);
        _layout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12);
        _layout.minimumLineSpacing = 8;
        _layout.minimumInteritemSpacing = 8;
    }
    return _layout;
}
- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.collectView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.scrollCallback) {
        self.scrollCallback(scrollView);
    }
}
- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}
- (UICollectionView *)collectView {
    if (!_collectView) {
        _collectView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.layout];        
//        [_collectView setGradientBackgroundWithColors:@[RGBCOLOR_HEX(0xFFFFFF) ,GMColorF7F6FA] locations:nil startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 0.1)];
        _collectView.backgroundColor = RGBCOLOR_HEX(0xF7F6FA);
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        [_collectView registerClass:[GMToFaceDoctorListVerCell class] forCellWithReuseIdentifier:NSStringFromClass([GMToFaceDoctorListVerCell class])];
    }
    return _collectView;
}
- (GMToFaceCommonEmptyView *)commonEmptyView {
    if (!_commonEmptyView) {
        _commonEmptyView = [[GMToFaceCommonEmptyView alloc] init];
        _commonEmptyView.delegate = self;
        _commonEmptyView.hidden = YES;
    }
    return _commonEmptyView;
}
@end
