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

#import "GMBasicInfoCardView.h"
#import <WebKit/WebKit.h>
//#import "GMDetailWebViewController.h"
//#import "Gengmei-Swift.h"
//#import "GMCommentPopupView.h"
#import "GMUserVideoTelephoneLogin.h"
#import "GMVideoWaitingView.h"
#import "GMDoctorInfoPopupView.h"
#import "GMConsultantInfoModel.h"
#import "GMVideoPhobos.h"
#import "GMToFacePayPrepareModel.h"
#import "GMToFaceOrderViewController.h"
#import "GMToFacePayPopView.h"
#import "RequestHeader.h"
#import <GMBase/GMBaseTool.h>

@import GMBaseWeb;
#define counsellorAllHeight (573 + UIView.safeAreaInsetsBottom)
#define counsellorHalfHeight (366 + UIView.safeAreaInsetsBottom)
#define doctorAllHeight (573 + UIView.safeAreaInsetsBottom)
#define doctorHalfHeight (280 + UIView.safeAreaInsetsBottom)

#define dispatchAllHeight (522 + UIView.safeAreaInsetsBottom)
#define dispatchHalfHeight (286 + UIView.safeAreaInsetsBottom)

@interface GMBasicInfoCardView ()<WKBaseWebViewDelegate>
@property (nonatomic, strong) GMBaseWebViewComponent *webCompent;
@property (nonatomic, strong) GMVideoWaitingView *waitingView;
@property (nonatomic, assign) int currentTime;
@property (nonatomic, copy) NSString *traceId;
/** 面诊顾问类型, 1: 医生, 2:面诊师 */
@property (nonatomic, assign) NSInteger type;
//三个属性埋点用的
@property (nonatomic, assign) BOOL isOpenVideo;
@property (nonatomic, assign) BOOL isOpenAudio;
@property (nonatomic, assign) BOOL isClickVideo;
/** 订单号 */
@property (nonatomic, copy) NSString *orderNo;
@end

@implementation GMBasicInfoCardView


- (void)setup {
    [super setup];
    self.container.size = CGSizeMake(MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT);
    [self.webCompent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, UIView.safeAreaInsetsBottom, 0));
    }];
    [self containerRectCorner:self.container];
}

- (void)containerRectCorner:(UIView *)view {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(12, 12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}
+ (void)showWithCorrectFrameView:(GMBasicInfoCardView *)cardView resultBlock:(nonnull void (^)(void))resultBlock {
    [GMNetworking requestOCWithApi:API_CONSULTATION__COUNSEL_CUSTOMER method:GMHTTPMethodGet parameters:@{@"counsellor_id": SafeString(cardView.counsellorId), @"doctor_id": SafeString(cardView.doctorId)} completion:^(GMResponseOC * response) {
        if (response.isSuccess) {
            NSDictionary *dic = (NSDictionary *)response.data;
            BOOL hasRecord = [dic.allKeys containsObject:@"has_record"] ? [dic[@"has_record"] boolValue] : NO;
            if (!cardView.isDispatch && [dic.allKeys containsObject:@"counsellor_type"] && dic[@"counsellor_type"] != NULL) {
                cardView.type = [dic[@"counsellor_type"] integerValue];
            }
            [cardView updateConstraintsWithHasRecord:hasRecord];
            [[GMBaseTool getCurrentViewController].view addSubview:cardView];
        } else {
            [cardView updateConstraintsWithHasRecord:NO];
            [[GMBaseTool getCurrentViewController].view addSubview:cardView];
        }
        if (resultBlock) {
            resultBlock();
        }
       }];
}

- (void)updateConstraintsWithHasRecord:(BOOL)hasRecord {
    if (_isDispatch) { // 派单
        if (hasRecord) {
            self.container.size = CGSizeMake(MAINSCREEN_WIDTH, MAINSCREEN_WIDTH == 414 ? dispatchHalfHeight + 20 :  dispatchHalfHeight);
        } else {
            self.container.size = CGSizeMake(MAINSCREEN_WIDTH, dispatchAllHeight);
        }
    } else { // 1V1视频面诊
        if (self.type == 2) { // 面诊师(有简介)
            if (hasRecord) {
                self.container.size = CGSizeMake(MAINSCREEN_WIDTH, MAINSCREEN_WIDTH == 414 ? counsellorHalfHeight + 20 : counsellorHalfHeight);
            } else {
                self.container.size = CGSizeMake(MAINSCREEN_WIDTH, counsellorAllHeight);
            }
        } else if (self.type == 1) { // 医生（无简介）
            if (hasRecord) {
                self.container.size = CGSizeMake(MAINSCREEN_WIDTH, MAINSCREEN_WIDTH == 414 ? doctorHalfHeight + 20 : doctorHalfHeight);
            } else {
                self.container.size = CGSizeMake(MAINSCREEN_WIDTH, doctorAllHeight);
            }
        }
    }
    [self.webCompent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, UIView.safeAreaInsetsBottom, 0));
    }];
    
    [self layoutIfNeeded];
    
}

- (void)setDoctorId:(NSString *)doctorId {
    _doctorId = doctorId;
    self.webCompent.fullUrl = [NSString stringWithFormat:@"%@/phantom/treatment/user/typing_info_v4/%@?counsellor_id=%@&record_type=1",[GMWebutil getCurrentApiHost], SafeString(doctorId), SafeString(self.counsellorId)];
    [self.webCompent webviewLoad:self];
}

- (void)setIsDispatch:(BOOL)isDispatch {
    _isDispatch = isDispatch;
    if (self.isDispatch) {
        self.webCompent.fullUrl = [NSString  stringWithFormat:@"%@/phantom/treatment/user/typing_info_v4?record_type=2",[GMWebutil getCurrentApiHost]];
        [self.webCompent webviewLoad:self];
    }
}

- (void)getVideoPermission:(NSDictionary *)data {
    //先请求订单接口，付款完成后再进行面诊
    self.dict = [NSMutableDictionary dictionaryWithDictionary:data];
    self.traceId = [GMVideoPhobos getTraceId];
    [self requestAccessForVideo];
    [self requestAccessForAudio];
}

- (void)showCounsellorCard:(NSString *)string {
    [self closeCurrentPage];
    //弹出面诊师卡片
    [GMNetworking requestOCWithApi:API_CONSULTATION__COUNSEL_CONSULTANT method:GMHTTPMethodGet parameters:@{@"counsellor_id": SafeString(string)} completion:^(GMResponseOC * response) {
        if (response.isSuccess) {
            GMConsultantInfoModel *model = [[GMConsultantInfoModel alloc] initWithDictionary:response.data error:NULL];
            GMDoctorInfoPopupView *popupView = [[GMDoctorInfoPopupView alloc] init];
            popupView.tabName = @"医生推荐";
            popupView.model = model;
            [[GMBaseTool getCurrentViewController].view addSubview:popupView];
        } else {
            [[GMBaseTool getCurrentViewController] toast:response.message];
        }
    }];
}

- (void)showAllCard {
    if (_isDispatch) { // 派单
        self.container.frame = CGRectMake(0, MAINSCREEN_HEIGHT - dispatchAllHeight, MAINSCREEN_WIDTH, dispatchAllHeight);
    } else {
        self.container.frame = CGRectMake(0, MAINSCREEN_HEIGHT - doctorAllHeight, MAINSCREEN_WIDTH, doctorAllHeight);
    }
    [self.webCompent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, UIView.safeAreaInsetsBottom, 0));
    }];
    [self layoutIfNeeded];
}

-(void)globalDataLoaded:(NSDictionary *)data {
    int consultation_type = [data[@"consultation_type"] intValue];
    int counsellor_type = [data[@"counsellor_type"] intValue];
    NSDictionary *dict = @{@"page_name":[GMBaseTool getCurrentViewController].pageName,
                           @"popup_name":@"basic_info",
                           @"referrer_link":[GMBaseTool getCurrentViewController].referrerLink ? : @[],
                           @"consultation_type":@(consultation_type),
                           @"counsellor_type":@(counsellor_type),
                           @"tab_name":SafeString(self.tabName),
                           @"doctor_id":SafeString(_doctorId),
    };
    [Phobos track:@"popup_view" attributes:dict];
}

- (void)closeCurrentPage {
    [self removeFromSuperview];
}

- (void)pushToVideoDiagnose {
    if (self.isDispatch && [self showAlertIfNotAllowed]) {
        return;
    }
    // 埋点
    if (!self.isDispatch) {
        [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.One2One.LaunchButtion.Click" status:@"success" extraParam:@{@"counsellor_id": SafeString(self.counsellorId), @"referer": SafeString(self.referer)}];
    }
    [self payMoney];
}

- (void)videoDiagnose {
    if (self.isDispatch) {
        [GMVideoPhobos video_monitoringWithActionStep:@"免费派单呼叫" consultId:nil traceId:self.traceId];
        //派单
        [self disPatch];
    } else {
        [GMVideoPhobos video_monitoringWithActionStep:@"点击免费呼叫_链路监控" consultId:nil traceId:self.traceId];
        if ([self.referer isEqualToString:@"conversation_detail"]) {
            // 私信详情
            [self.dict setValue:self.doctorId forKey:@"doctor_id"];
        }
        [self.dict setValue:SafeString(self.traceId) forKey:@"trace_id"];
        [self.dict setValue:SafeString(self.orderNo) forKey:@"order_no"];
        [self.dict setValue:@(1) forKey:@"consultation_type"];//1v1
        NSDictionary *dict = @{@"isAssistant": SafeString(self.dict[@"isAssistant"])};
        [self.dict removeObjectForKey:@"isAssistant"];
        [[GMUserVideoTelephoneLogin sharedVideoTelephoneLogin] userCreateVideoRoom:self.dict extension:dict];
        [self hide];
    }
}
#pragma mark - 需要付款的面诊
- (void)payMoney {
    [GMHudModule showLoading:nil];
    __weak typeof(self) weakSelf = self;
    NSString *url = self.isDispatch ? API_PREPARE_DISPATCH:API_PREPARE_PREPARE_ONE2ONE;
    if ([url isEqual: API_PREPARE_PREPARE_ONE2ONE]) {
        [self.dict setValue:SafeString(self.referer) forKey:@"referer"];
    }
    [GMNetworking requestOCWithApi:url method:GMHTTPMethodPost parameters:self.dict completion:^(GMResponseOC * _Nonnull responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            NSError *error = [[NSError alloc] init];
            GMToFacePayPrepareModel *model = [[GMToFacePayPrepareModel alloc] initWithDictionary:responseObject.data error:&error];
            weakSelf.orderNo = model.orderNo;
            // 埋点
            [weakSelf consultation_traceWithStatus:@"success"];
            NSNumber *fee;
            if (weakSelf.isDispatch) {
                //派单的付款金额字段
                fee = weakSelf.dict[@"consultation_type_fee"];
            } else {
                //1v1的付款金额字段
                fee = weakSelf.dict[@"service_fee"];
            }
            //需要付款
            //是否需要付款（逻辑改为和安卓一致）
            if (!model.needPay) {
                //金额为0则直接开启面诊
                [self videoDiagnose];
            }else {
                //需要付款则先付款再面诊
                [self needPay:model];
            }
        }else {
            [weakSelf consultation_traceWithStatus:@"failed"];
            [GMHudModule toast:responseObject.message];
        }
    }];
}

- (void)consultation_traceWithStatus:(NSString *)status {
        // 埋点
    [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.CreateOrder" status:status extraParam:@{ @"order_no": SafeString(self.orderNo)}];
}

#pragma mark - 需要付款，先付款、后面诊
- (void)needPay:(GMToFacePayPrepareModel *)model {
    __weak typeof(self) weakSelf = self;
    if (self.isDispatch) {
        GMToFacePayPopView *popView = [[GMToFacePayPopView alloc] init];
        popView.counsellorType = [self.dict[@"counsellor_type"] integerValue];
        popView.orderModel = model;
        popView.PaySuccessBlock = ^{
            //支付成功发起派单
            [weakSelf disPatch];
            //付款成功，显示派单的View
            weakSelf.alpha = 1.f;
        };
        //点击关闭支付view的时候将当前view也关闭
        popView.CloseView = ^{
            [weakSelf hide];
        };
        [[GMBaseTool mainWindow]  addSubview:popView];
        //进到付款页面先隐藏view，等到付款成功的回调来了之后再显示
        self.alpha = 0.f;
    }else {
        GMToFaceOrderViewController *controller = [[GMToFaceOrderViewController alloc] init];
        controller.counsellorId = SafeString(self.dict[@"counsellor_id"]);
        controller.counsellorType = [self.dict[@"counsellor_type"] integerValue];
        controller.orderModel = model;
        controller.PaySuccessBlock = ^(NSString *referer) {
            weakSelf.referer = referer;
            //支付成功发起面诊
            [weakSelf videoDiagnose];
        };
        [[GMBaseTool getCurrentViewController] pushViewController:controller animated:YES completion:nil];
    }
}
- (BOOL)showAlertIfNotAllowed {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if(status == kCLAuthorizationStatusDenied) {
        NSString *detail = @"为了能更快找到适合您的医生/面诊师，更美需要知道您的位置请进入系统设置-隐私-定位服务，开启更美权限";
        NSString *otherButton = @"立即开启";
        NSString *cancelButton = @"取消";
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:detail preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:cancelButton style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [self disPatch];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:otherButton style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [GMLocationManager jumpToSettings];
        }]];
        [[GMBaseTool getCurrentViewController] presentViewController:alert animated:YES completion:NULL];
        return YES;
    }
    return NO;
}


- (void)cancelDispatch {
    [GMNetworking requestOCWithApi:API_CONSULTATION_CANCEL_DISPATCH method:GMHTTPMethodPost parameters:nil completion:^(GMResponseOC * _Nonnull response) {
        
    }];
}
#pragma mark - 派单
- (void)disPatch {
    __weak __typeof(self)weakSelf = self;
    NSDictionary *param = @{@"use_last_data":@(0),
                            @"user_gender":self.dict[@"user_gender"],
                            @"user_age":self.dict[@"user_age"],
                            @"user_has_aesthetic_medicine":self.dict[@"user_has_aesthetic_medicine"],
                            @"user_target_project":self.dict[@"user_target_project"],
                            @"trace_id":SafeString(self.traceId),
                            @"counsellor_type":self.dict[@"counsellor_type"],
                            @"order_no":SafeString(self.orderNo)
    };
    [GMNetworking requestOCWithApi:API_LAUNCH_DISPATCH method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * _Nonnull response) {
        if (response.isSuccess) {
            [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.Dispatch.Launch" status:@"success" extraParam:@{@"order_no": SafeString(self.orderNo)}];
            [GMVideoPhobos video_monitoringWithActionStep:@"进入正在匹配页" consultId:nil traceId:weakSelf.traceId];
            weakSelf.waitingView.currentTime = [response.data[@"countdown"] intValue];
            weakSelf.waitingView.orderNo = weakSelf.orderNo;
            dispatch_main_async_safe(^{
                [weakSelf.waitingView addCountDownTimer];
//                weakSelf.alpha = 0.f;
                [weakSelf hide];
            });
        } else {
            [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.Dispatch.Launch" status:@"failed" extraParam:@{@"order_no": SafeString(self.orderNo)}];
            [[GMBaseTool getCurrentViewController] toast:response.message];
        }
    }];
}

- (void)requestAccessForVideo {
    __weak __typeof(self)weakSelf = self;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                weakSelf.isOpenVideo = YES;
            }else {
                weakSelf.isOpenVideo = NO;
            }
        }];
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [self showCameraAlert];
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        self.isOpenVideo = YES;
    }
}

- (void)requestAccessForAudio {
    __weak __typeof(self)weakSelf = self;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    if (weakSelf.isOpenVideo) {
                        [weakSelf pushToVideoDiagnose];
                    }
                    weakSelf.isOpenAudio = YES;
                }else {
                    weakSelf.isOpenAudio = NO;
                }
                [weakSelf audioAndVideoJurisdiction:weakSelf.isOpenAudio && weakSelf.isOpenVideo];
            });
        }];
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [self showAudioAlert];
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        if (self.isOpenVideo) {
            [self pushToVideoDiagnose];
        }
    }
}

- (void)showAudioAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更美APP需要访问你的麦克风" message:@"请在【设置-隐私-麦克风】选项中，允许更美访问你的麦克风" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (!self.isClickVideo) {
            [self audioAndVideoJurisdiction:NO];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (!self.isClickVideo) {
            [self audioAndVideoJurisdiction:NO];
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    if (![[GMBaseTool getCurrentViewController] isKindOfClass:[UIAlertController class]]) {
        [[GMBaseTool getCurrentViewController] 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) {
        self.isClickVideo = YES;
        [self audioAndVideoJurisdiction:NO];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isClickVideo = YES;
        [self audioAndVideoJurisdiction:NO];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    
    if (![[GMBaseTool getCurrentViewController] isKindOfClass:[UIAlertController class]]) {
        [[GMBaseTool getCurrentViewController] presentViewController:alert animated:YES completion:nil];
    }
}
#pragma mark - 权限获取埋点（只有两个权限全部为点同一状态才算YES，并且必须两个都音视频都授权才进行埋点）
- (void)audioAndVideoJurisdiction:(BOOL)isOpen {
    NSString *str = isOpen ? @"获取到用户权限":@"用户拒绝权限";
    [GMVideoPhobos video_monitoringWithActionStep:str consultId:nil traceId:self.traceId];
}

- (GMBaseWebViewComponent *)webCompent {
    if (!_webCompent) {
        _webCompent = [GMBaseWebViewComponent new];
        _webCompent.delegate = self;
    }
    if (!_webCompent.superview) {
        [self.container addSubview:_webCompent];
    }
    return _webCompent;
}

- (GMVideoWaitingView *)waitingView {
    if (!_waitingView) {
        _waitingView = [GMVideoWaitingView new];
        _waitingView.counsellorType = [self.dict[@"counsellor_type"] integerValue];        
        _waitingView.consultationType = self.isDispatch?2:1;
        __weak typeof(self) weakSelf = self;
        //等待倒计时结束要返回面诊信息卡
//        _waitingView.timerOverBlock = ^{
//            weakSelf.alpha = 1.f;
//        };
        //取消连线要隐藏面诊信息卡
        _waitingView.cancelBlock = ^{
            [weakSelf hide];
        };
    }
    if (!_waitingView.superview) {
        [[GMBaseTool getCurrentViewController].view addSubview:_waitingView];
        [_waitingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    return _waitingView;
}
@end
