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

#import "GMDiagnosisWorkingTableViewController.h"
#import "GMDiagnosisWorkingTableHeaderView.h"
#import "GMOnlineStatusView.h"
#import "GMWorkingTableCell.h"
#import "GMDiagnosisWorkingTableSwitch.h"
#import "GMDiagnosisWorkingTableChooseIdentityView.h"
#import "WMTagObject.h"
#import "UIAlertController+gm.h"
//#import "UIView+GMExtension.h"
#import "GMCommonTipAlertView.h"
#import "GMLibraryHeader.h"
#import <AVFoundation/AVFoundation.h>
#import <GMBase/GMBaseTool.h>

@interface GMDiagnosisWorkingTableViewController ()<UITableViewDelegate, UITableViewDataSource, GMDiagnosisWorkingTableSwitchDelegate, GMDiagnosisWorkingTableChooseIdentityViewDelegate> {
    GMDiagnosisWorkingTableSwitch *_switchView;
}
@property (nonatomic, strong) GMDiagnosisWorkingTableHeaderView *headerView;
@property (nonatomic, strong) GMOnlineStatusView *statusView;
@property (nonatomic, strong) GMDiagnosisWorkingTableChooseIdentityView *chooseIdentityView;
@property (nonatomic, copy) void (^OpenSuccessBlock)(BOOL isSuccess);
@end

@implementation GMDiagnosisWorkingTableViewController
@synthesize viewModel;

- (void)initController {
    [super initController];
    self.viewModel = [[GMDiagnosisWorkingTableViewModel alloc] init];
    _needHeaderRefresh = NO;
    _needFooterRefresh = NO;
    self.immediateLoad = NO;
    self.controlNavigationByYou = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 请求面诊工作台数据 （每次进来刷新数据，保持数据实时更新）
    [self fetchData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"面诊工作台";
    
    self.statusView.hidden = YES;
    [self.navigationBar.itemView addSubview:self.statusView];
    
    [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(15);
        make.centerY.mas_equalTo(self.navigationBar.itemView);
        make.right.mas_equalTo(-15);
    }];
    
    [self addDiagnosisWorkingTableSwitch];
    
    
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table registerCell:[GMWorkingTableCell class]];
    
    self.table.tableHeaderView = self.headerView;
    self.table.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];

    [self.table mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.mas_equalTo(OCNavigationBar.barHeight);
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchData) name:@"doctor_finshed_video" object:nil];
}

- (void)fetchData {
    __weak typeof(self)weakSelf = self;
    [self.viewModel fetchWorkBenchHomeData:^(APIStatusCode apiStatus, NSString *message) {
        [[GMBaseTool getCurrentViewController] hideLoading];
        
        if (APIStatusCodeFailed == apiStatus) { // 失败
            [weakSelf showEmptyView:GMEmptyViewTypeException];
            if ([message isNonEmpty]) {
                [weakSelf toast:message];
            }
        } else {
            if (weakSelf.viewModel.workTableObject) {
                [weakSelf hideEmptyView];

                weakSelf.headerView.doctorId = weakSelf.viewModel.doctorId;
                weakSelf.headerView.workTableObject = weakSelf.viewModel.workTableObject;
                _switchView.isSelected = (weakSelf.viewModel.workTableObject.status != DiagnosisWorkingTableSwitchStatusOff);
                // 判断权限是否开启,如果没有则告诉backend关闭权限
                if (weakSelf.viewModel.workTableObject.status != DiagnosisWorkingTableSwitchStatusOff) {
                    weakSelf.statusView.hidden = NO;
                    weakSelf.statusView.descLabel.text = weakSelf.viewModel.workTableObject.statusText;
                }
            }
            [weakSelf.table reloadData];
        }

    }];
}

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

- (void)addDiagnosisWorkingTableSwitch {
    _switchView = [[GMDiagnosisWorkingTableSwitch alloc] init];
    _switchView.delegate = self;
    [self.view addSubview:_switchView];
    [_switchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-28);
        make.bottom.mas_equalTo(-65);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(80);
    }];
}

- (NSString *)doctorStatusDesc {
    if (self.viewModel.workTableObject.identity == 1) {
        return @"医生助理在线";
    }
    return @"医生本人在线";
}

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

-(void)gotoSetting:(UIButton *)sender {
    [GMCommonTipAlertView hideAtertView];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

#pragma mark GMDiagnosisWorkingTableSwitchDelegate
- (void)diagnosisWorkingTableSwitchDidSelectedWithStatus:(DiagnosisWorkingTableSwitchStatus)status successBlock:(void (^)(BOOL))successBlock {
    _OpenSuccessBlock = successBlock;
    __weak typeof(self)weakSelf = self;
    if (status == DiagnosisWorkingTableSwitchStatusOff) { // 关闭
        [self.viewModel stopConsultationWithSuccessBlock:^(id responseObject) {
            [weakSelf toast:@"已关闭面诊"];
            // 开启成功 改变按钮图片
            if (weakSelf.OpenSuccessBlock) {
                weakSelf.OpenSuccessBlock(YES);
            }
            weakSelf.statusView.hidden = YES;
        } failBlock:^(NSString *message) {
            [GMHudModule showWarning:message];
        }];
    } else { // 开启
        // 1. 判断权限
        if ([self necessaryAuthority]) {
            // 通知权限
            [GMBaseTool userIsAllowPush:^(BOOL status) {
                if (!status) { // 未开通知
                    [GMCommonTipAlertView showAtertWithTitle:@"" content:@"为了及时收到用户的呼叫提醒，需先开启系统通知" leftBtnText:@"以后再说" rightBtnText:@"立即打开" leftAction:@selector(cancelAction:) rightAction:@selector(gotoSetting:) target:weakSelf];
                } else {
                    // 面诊师不需要选择身份
                    if (self.viewModel.workTableObject.counsellorType == 2) {
                        [weakSelf openFaceCheck];
                    } else {
                        // 2. 身份选择
                        [weakSelf.viewModel getAllTagsWithSuccessBlock:^(id responseObject) {
                            GMResponseOC *response = (GMResponseOC *)responseObject;
                            [weakSelf.view addSubview:weakSelf.chooseIdentityView];
                            NSDictionary *data = response.data;
                            weakSelf.chooseIdentityView.tagsArray = [WMTagObject arrayOfModelsFromDictionaries:data[@"good_at_list"] error:NULL];
                        } failBlock:^(NSString *message) {
                            [GMHudModule showWarning:message];
                        }];
                    }
                }
            }];
        }
    }
}

#pragma mark GMDiagnosisWorkingTableSwitchDelegate
- (void)openWorkTableDidclickedWithTags:(NSArray *)tags{
    
    [_chooseIdentityView hide];
    
    self.viewModel.tagIds = [tags mutableCopy];
    
    [self openFaceCheck];
}

- (void)openFaceCheck {
    // 开启面诊
    __weak typeof(self)weakSelf = self;
    [self.viewModel startConsultationWithSuccessBlock:^(id responseObject) {
        GMResponseOC *response = responseObject;
        weakSelf.statusView.hidden = NO;
        if (response.data) {
            weakSelf.statusView.descLabel.text = response.data[@"online_text"];
        }

        [weakSelf toast:@"视频面诊开启成功"];
        // 开启成功 改变按钮图片
        if (weakSelf.OpenSuccessBlock) {
            weakSelf.OpenSuccessBlock(YES);
        }
    } failBlock:^(NSString *message) {
        [GMHudModule showWarning:message];
    }];
}

- (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];
}


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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMWorkingTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GMWorkingTableCell class]) forIndexPath:indexPath];
   GMWorkTableNotifyObject *obj = self.viewModel.workTableObject.notifies[indexPath.row];
    [cell.icon sd_setImageWithURL:[NSURL URLWithString:obj.image]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GMWorkTableNotifyObject *obj = self.viewModel.workTableObject.notifies[indexPath.row];
    [[GMRouter sharedInstance] pushScheme:obj.url];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 要求4 ：1
    CGFloat imgW = MAINSCREEN_WIDTH - 30;
    CGFloat imgH = imgW / 4.0;
    return imgH + 8;
}

#pragma mark - 懒加载
- (GMOnlineStatusView *)statusView {
    if (!_statusView) {
        _statusView = [[GMOnlineStatusView alloc] initWithFrame:CGRectZero desc:@"医生本人在线"];
    }
    return _statusView;
}

- (GMDiagnosisWorkingTableHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[GMDiagnosisWorkingTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, 365)];
    }
    return _headerView;
}

- (GMDiagnosisWorkingTableChooseIdentityView *)chooseIdentityView {
    if (!_chooseIdentityView) {
        _chooseIdentityView = [[GMDiagnosisWorkingTableChooseIdentityView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT)];
        _chooseIdentityView.openDelegate = self;
    }
    return _chooseIdentityView;
}

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

@end
