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

#import "GMToFacePayPopView.h"
#import "GMPayTypeView.h"
#import "GMToFaceOrderFooterView.h"
#import "GMToFacePayViewModel.h"
#import "GMPayResultModel.h"
#import "GMThirdPartyDefine.h"
#import "RequestHeader.h"
#import "GMLibraryHeader.h"
#import <GMBase/GMBaseTool.h>


@interface GMToFacePayPopView ()
@property (nonatomic, strong) GMLabel *titleLabel;
@property (nonatomic, strong) GMButton *cancelButton;
@property (nonatomic, strong) UIView *payTypeView;
@property (nonatomic, strong) GMToFaceOrderFooterView *footerView;
@property (nonatomic, strong) NSMutableArray <GMPayTypeView *>*viewArray;
@property (nonatomic, strong) GMToFacePayViewModel *viewModel;
//选中的支付方式
@property (nonatomic, copy) NSString *payStr;
/** 支付成功:防止在页面重复支付 */
@property (nonatomic, assign) BOOL paiedIsFinish;
/** 支付失败 */
@property (nonatomic, assign) BOOL paiedIsFail;
/** 点击 立即支付 按钮 */
@property (nonatomic, assign) BOOL clickGoPay;
@end

@implementation GMToFacePayPopView

- (void)setup {
    [super setup];
    [self setUI];
    [self setLayout];
    [self setNotification];
}
- (void)setUI {
    [self.container addSubview:self.titleLabel];
    [self.container addSubview:self.cancelButton];
    [self.container addSubview:self.payTypeView];
    [self.container addSubview:self.footerView];
}
- (void)setLayout {
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(24);
        make.right.mas_equalTo(-10);
        make.left.equalTo(self.container.mas_left).offset(20);
        make.top.equalTo(self.container.mas_top).offset(25);
    }];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(17, 17));
        make.top.mas_offset(20);
        make.right.mas_offset(-20);
    }];
    [self.payTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(49+UIView.safeAreaInsetsBottom);
    }];
}
- (void)setNotification {
    //支付宝支付成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderPaySuccess:) name:@"order_pay_success" object:nil];
    //支付宝支付失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderPayFail:) name:@"order_pay_fail"  object:nil];
    //微信支付成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderPaySuccess:) name:@"kWechatPaySuccess" object:nil];
    //微信支付失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderPayFail:) name:@"kWechatPayFail" object:nil];
    //从后台回到前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForground) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)pvPhoboMethod {
    NSDictionary *dict = @{@"page_name":@"video_face_consultation_order",
                           @"popup_name":@"dispatch_order",
                           @"business_id":SafeString(self.orderModel.orderNo),
                           @"counsellor_type":@(self.counsellorType)
    };
    [Phobos track:@"popup_view" attributes:dict];
}
- (void)setOrderModel:(GMToFacePayPrepareModel *)orderModel {
    _orderModel = orderModel;
    self.footerView.model = orderModel;
    //这样创建支付种类的目的是为了防止后端将微信支付与支付宝支付的顺序调换，或者只返回一个支付方式
    __weak typeof(self) weakSelf = self;
    [orderModel.paymentChannels enumerateObjectsUsingBlock:^(GMToFacePayTypeModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GMPayTypeView *view = [[GMPayTypeView alloc] init];
        view.tag = idx;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectPayTypeMethod:)];
        [view addGestureRecognizer:gesture];
        view.typeModel = obj;
        view.isSelected = obj.recommend;
        [weakSelf.payTypeView addSubview:view];
        [weakSelf.viewArray addObject:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(60);
            make.top.mas_equalTo(60*idx);
        }];
        //当前选中的支付方式
        if (obj.recommend) {
            weakSelf.viewModel.payType = [obj.name isEqualToString:@"alipay"] ? GMToFacePayTypeAlipay : GMToFacePayTypeWechat;
        }
    }];
    [self.payTypeView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(60*orderModel.paymentChannels.count);
    }];
    [self.container mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(166+UIView.safeAreaInsetsBottom+60*orderModel.paymentChannels.count);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self containerRectCorner:self.container];
    });
    //这个set方法只会走一次，所以放在这里不会有问题
    [self pvPhoboMethod];
}
- (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)selectPayTypeMethod:(UIGestureRecognizer *)gesture {
    __weak typeof(self) weakSelf = self;
    [self.orderModel.paymentChannels enumerateObjectsUsingBlock:^(GMToFacePayTypeModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GMPayTypeView *view = weakSelf.viewArray[idx];
        view.isSelected = obj.recommend = gesture.view.tag == idx;
        if (obj.recommend) {
            weakSelf.viewModel.payType = [obj.name isEqualToString:@"alipay"] ? GMToFacePayTypeAlipay : GMToFacePayTypeWechat;
        }
    }];
}
#pragma mark - 点击 "立即支付"
- (void)payMethod {
    [self clickPhoboMethod:@"pay_immediately"];
    self.clickGoPay = YES;
    self.viewModel.orderNo = self.orderModel.orderNo;
    self.viewModel.paymentAmount = self.orderModel.paymentAmount;
    //目的是防止重复点击，所以必须要网络请求回来之后才可再次点击
    self.footerView.isCanClick = NO;
    [[GMBaseTool getCurrentViewController] showLoading:nil];
    __weak typeof(self) weakSelf = self;
    [self.viewModel excuteToFacePayCompleteBlock:^(id responseObject) {
        weakSelf.footerView.isCanClick = YES;
        [[GMBaseTool getCurrentViewController] hideLoading];
    } failedBlock:^(NSString *message) {
        //支付参数获取失败 则可以重新支付
        [[GMBaseTool getCurrentViewController] toast:message];
        [[GMBaseTool getCurrentViewController] hideLoading];
        weakSelf.footerView.isCanClick = YES;
    }];
}
- (void)clickPhoboMethod:(NSString *)buttonName {
    NSDictionary *dict = @{@"page_name":@"video_face_consultation_order",
                           @"order_id":self.orderModel.orderNo,
                           @"button_name":buttonName,
                           @"counsellor_type":@(self.counsellorType),
                           @"consultation_type":@"2"
    };
    [Phobos track:@"on_click_button" attributes:dict];
}
#pragma mark - 支付成功回调
- (void)orderPaySuccess:(NSNotification *)notifi{
    self.footerView.isCanClick = YES;
    [GMHudModule hideLoading];
    if (self.paiedIsFinish) {
        return;
    }
    self.paiedIsFinish = YES;
    self.viewModel.needRepeat = YES;
    [GMHudModule showLoading:nil];
    //客户端支付成功后需要查询后端是否支付成功，若后端也显示支付成功了则进行下一步，面诊
    __weak typeof(self) weakSelf = self;
    [self.viewModel excuteToFacePayQueryBacksSuccessBlock:^(GMResponseOC * _Nonnull responseObject) {
        [GMHudModule hideLoading];
        weakSelf.paiedIsFinish = NO;
        NSNumber *status = responseObject.data[@"order_status"];
        if ([status integerValue] == 2) {
            [[GMBaseTool getCurrentViewController] toast:@"支付成功，不要走开，立即进入视频面诊连线"];
            //回调到信息卡页面去做一些操作
            if (weakSelf.PaySuccessBlock) {
                weakSelf.PaySuccessBlock();
                [weakSelf hide];
            }
        }else {
            [[GMBaseTool getCurrentViewController] toast:responseObject.message];
        }
        
    } failBlock:^(NSString *message) {
        weakSelf.paiedIsFinish = NO;
        [GMHudModule hideLoading];
        [[GMBaseTool getCurrentViewController] toast:message];
    }];
}

#pragma mark - 支付失败回调
- (void)orderPayFail:(NSNotification *)noti{
    self.paiedIsFail = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[GMBaseTool getCurrentViewController] showWarning:@"支付失败"];
        self.paiedIsFail = NO;
    });
    [[GMBaseTool getCurrentViewController] hideLoading];
    self.footerView.isCanClick = YES;
}
#pragma mark - notification
- (void)enterForground {
    if (!self.clickGoPay) {
        return;
    }
    self.clickGoPay = NO;
    self.footerView.isCanClick = YES;
    //进到前台的方法会先于支付成功的回调走，所以需要延时执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.footerView.isCanClick = YES;
        //成功：收到成功回调则一直轮循后端的支付状态接口
        if (self.paiedIsFinish) {
            //证明已经走到支付成功的回调，已经开始调用递归，所以直接return就好
            return;
        }
        if (self.paiedIsFail) {
            return;
        }
        [GMHudModule hideLoading];
        //只有支付成功走递归，其他情况都只请求一次
        self.viewModel.needRepeat = NO;
        [GMHudModule showLoading:nil];
        __weak typeof(self) weakSelf = self;
        [self.viewModel excuteToFacePayQueryBacksSuccessBlock:^(GMResponseOC * _Nonnull responseObject) {
            [GMHudModule hideLoading];
            NSNumber *status = responseObject.data[@"order_status"];
            if ([status integerValue] == 2) {
                [[GMBaseTool getCurrentViewController] toast:@"支付成功，不要走开，立即进入视频面诊连线"];
                //回调到信息卡页面去做一些操作
                if (weakSelf.PaySuccessBlock) {
                    weakSelf.PaySuccessBlock();
                    [weakSelf hide];
                }
            }else {
                [[GMBaseTool getCurrentViewController] toast:responseObject.message];
            }
            
        } failBlock:^(NSString *message) {
            [GMHudModule hideLoading];
            [[GMBaseTool getCurrentViewController] toast:message];
        }];
    });
}
- (void)clickHide {
    [self clickPhoboMethod:@"exit"];
    [GMHudModule showLoading:nil];
    __weak typeof(self) weakSelf = self;
    [GMNetworking requestOCWithApi:API_ORDER_CANCEL method:GMHTTPMethodPost parameters:@{@"order_no":self.orderModel.orderNo} completion:^(GMResponseOC * _Nonnull responseObject) {
        [GMHudModule hideLoading];
        [weakSelf hide];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf.CloseView) {
                weakSelf.CloseView();
            }
        });
    }];
}
- (void)hide {
    [super hide];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didTapView {
    
}
- (GMLabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:22.5];
        _titleLabel.font = [UIFont gmBoldFont:22.5];
        _titleLabel.text = @"请选择支付方式";
    }
    return _titleLabel;
}
- (GMButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [GMButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.enableAdaptive = YES;
        [_cancelButton setBackgroundImage:[UIImage imageNamed:@"wt_cancel_icon"] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(clickHide) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
- (UIView *)payTypeView {
    if (!_payTypeView) {
        _payTypeView = [[UIView alloc] init];
    }
    return _payTypeView;
}
- (GMToFaceOrderFooterView *)footerView {
    if (!_footerView) {
        __weak typeof(self) weakSelf = self;
        _footerView = [[GMToFaceOrderFooterView alloc ]initWithClickBlock:^{
            [weakSelf payMethod];
        }];
    }
    return _footerView;
}
- (NSMutableArray <GMPayTypeView *>*)viewArray {
    if (!_viewArray) {
        _viewArray = [NSMutableArray arrayWithCapacity:2];
    }
    return _viewArray;
}
- (GMToFacePayViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[GMToFacePayViewModel alloc] init];
    }
    return _viewModel;
}
@end
