//
//  GMWaitingGrabListViewController.m
//  Gengmei
//
//  Created by Jessica on 2020/3/6.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMWaitingGrabListViewController.h"
#import "GMWaitingGrabListCell.h"
#import "GMGrabLoadingView.h"
#import "GMDoctorVideoTelephoneLogin.h"
#import "GMDispatchWaitingGrabObject.h"
#import "GMWeakProxy.h"
#import "GMVideoPhobos.h"

@interface GMWaitingGrabListViewController ()
@property(nonatomic, strong) GMGrabLoadingView *loadingView;
@property(nonatomic, strong) NSDictionary *recordInfo;
@property (nonatomic, strong) NSTimer *getDateTimer;

@end

@implementation GMWaitingGrabListViewController

@dynamic viewModel;

- (void)initController{
    [super initController];
    _needFooterRefresh = NO;
    self.immediateLoad = NO;
    self.viewModel = [GMWaitingGrabViewModel new];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self headerRereshing];
    // 5秒轮询请求最新数据
    [self setupTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 销毁定时器
    [self invalidateTimer];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加通知
    [self addNotificationObserver];
    
    self.view.backgroundColor = UIColor.whiteColor;
    _table.estimatedRowHeight = 75;
    [self hideNavigationBar];
    [_table registerClass:[GMWaitingGrabListCell class] forCellReuseIdentifier:NSStringFromClass([GMWaitingGrabListCell class])];
    [_table mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
}

- (void)setupTimer {
    // 本页面在进入页面后的每5刷新一次，页面可见时刷新即可
    self.getDateTimer = [NSTimer timerWithTimeInterval:5 target:[GMWeakProxy proxyWithTarget:self] selector:@selector(fetchListData) userInfo:nil repeats:YES];
      [[NSRunLoop mainRunLoop] addTimer:self.getDateTimer forMode:NSDefaultRunLoopMode];
}

- (void)invalidateTimer {
    [self.getDateTimer invalidate];
    self.getDateTimer = nil;
}

- (void)addNotificationObserver {
    // 收到通知刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRereshing) name:NEED_REFRESH_DISPATCH object:nil];
    // 在应用进入前台时，刷新一下数据，保证倒计时准确
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRereshing) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)headerRereshing {
    [super headerRereshing];
    [self fetchListData];
}

// 点击 重新加载
- (void)emptyViewDidClickReload {
    [self fetchListData];
}

- (void)fetchListData {
    __weak typeof(self)weakSelf = self;
    [self.viewModel fetchWaitingListData:^(APIStatusCode apiStatus, NSString *message) {
        if (APIStatusCodeFailed == apiStatus) { // 失败
            [weakSelf showEmptyView:GMEmptyViewTypeException];
            if ([message isNonEmpty]) {
                [weakSelf toast:message];
            }
        } else {
            if (apiStatus == APIStatusCodeEmpty) { // 空
                [weakSelf showEmptyView:GMEmptyViewTypeEmpty];
            } else {
                [weakSelf hideEmptyView];
            }
            [weakSelf.table.mj_header endRefreshing];
            [weakSelf.table reloadData];
        }
    }];
}

#pragma mark 判断权限
- (BOOL)necessaryAuthority {
    // 1.麦克风、相机 权限
    // 2.通知权限
    // 3. 医生是否在线
    // 4. 医生是否被禁止
    if ([self requestAccessForVideo] && [self requestAccessForAudio]) {
        return YES;
    }
    return NO;
}

- (BOOL)requestAccessForVideo {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {

        }];
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [self showCameraAlert];
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        return YES;
    }
    return NO;
}

- (BOOL)requestAccessForAudio {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
            
        }];
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [self showAudioAlert];
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        return YES;
    }
    return NO;
}

- (void)showAudioAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更美APP需要访问你的麦克风" message:@"请在【设置-隐私-相机】选项中，允许更美访问你的麦克风" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showCameraAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更美APP需要访问你的相机" message:@"请在【设置-隐私-相机】选项中，允许更美访问你的相机" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)configureDataForCell:(GMWaitingGrabListCell *)cell atIndexPath: (NSIndexPath *)indexPath {
    if (self.viewModel.dataArray.count > 0) {
        GMDispatchWaitingGrabObject *object = self.viewModel.dataArray[indexPath.row];
        cell.infoView.locationLabel.text = object.cityText;
        cell.infoView.infoLabel.text = object.userContent;
        cell.infoView.projectLabel.text = object.projectContent;
        __weak typeof(self) weakSelf = self;
        __weak typeof(cell) weakCell = cell;
        cell.grabBtnClicked = ^() {
            [GMVideoPhobos video_monitoringWithActionStep:@"点击抢单按钮" consultId:nil taskId:object.dispatchId];
            // 抢单
            // 判断权限
            if ([weakSelf necessaryAuthority]) {
                // 点击「抢单」按钮后，出现「抢单loading」页
                [AppDelegate.visibleController.view addSubview:weakSelf.loadingView];
                [weakSelf.loadingView showLoading:YES];
                [weakSelf.viewModel grabOrderWithTaskId:object.dispatchTaskId successBlock:^(id responseObject) {
                    GMResponseOC *response = (GMResponseOC *)responseObject;
                    NSDictionary *data = response.data;
                    NSInteger countDown = [(data[@"countdown"]) integerValue];
                    weakSelf.recordInfo = data[@"consultation_record_info"];
                    // 1.抢单成功后进入「抢单成功-视频通话正开启」页面
                    weakSelf.loadingView.timeCount = countDown;
                    [weakSelf.loadingView showLoading:NO];
                    [weakCell updateGrabBtnStatusWithCanClicked:NO];
                    [GMVideoPhobos video_monitoringWithActionStep:@"收到抢单成功回执" consultId:weakSelf.recordInfo[@"consultation_record_id"] traceId:nil];

                } failBlock:^(NSString *message) {
                    // 2.抢单失败后关闭「抢单loading」页，并toast提示，按钮置灰
                    [weakSelf toast:message];
                    [weakSelf.loadingView hide];
                    
                    // 抢单失败的情况（已被抢、用户已取消），toast提示完之后，倒计时清零，抢单按钮置灰
                    [weakCell updateGrabBtnStatusWithCanClicked:NO];
                }];
            }
        };
        cell.isShowSameCity = object.isSameCity;
        [cell updateCellConstraints];
        [cell begainTimerWithRemainingTime:object.countdown * 10 maxTime:object.countdownMax * 10];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GMWaitingGrabListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GMWaitingGrabListCell class]) forIndexPath:indexPath];
    __weak __typeof(self)weakSelf = self;
    [weakSelf configureDataForCell:cell atIndexPath:indexPath];
    return cell;
}

- (GMGrabLoadingView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[GMGrabLoadingView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT)];
        // 倒计时结束，此页面不可点击和关闭，倒计时结束之后直接进入视频通话页面
        __weak typeof(self) weakSelf = self;
        _loadingView.countDownDone = ^{
            // 弹起视频页面
            [[GMDoctorVideoTelephoneLogin sharedDoctorVideoTelephoneLogin] doctorCreatVideoRoom:weakSelf.recordInfo extension:@{}];
        };
    }
    return _loadingView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self invalidateTimer];
}

@end
