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

#import "GMToFaceOrderViewController.h"
#import "GMToFaceOrderHeaderView.h"
#import "GMToFacePaySectionHeaderView.h"
#import "GMToFacePayTypeCell.h"
#import "GMToFaceOrderFooterView.h"
#import "GMToFacePayViewModel.h"
#import "GMPayResultModel.h"
#import "GMThirdPartyDefine.h"
#import "RequestHeader.h"
#import "GMLibraryHeader.h"
#import <GMBase/GMBaseTool.h>
#import "NSString+AIJsonData.h"

@import GMNetworking;
@interface GMToFaceOrderViewController ()
@property (nonatomic, strong) GMToFacePayViewModel *payViewModel;
/** 头部视图 */
@property (nonatomic, strong) GMToFaceOrderHeaderView *headerView;
/** 组头 */
@property (nonatomic, strong) GMToFacePaySectionHeaderView *sectionView;
/** 底部提交按钮 */
@property (nonatomic, strong) GMToFaceOrderFooterView *bottomView;
/** 防止在页面重复支付 */
@property (nonatomic, assign) BOOL paiedIsFinish;
/** 支付失败的回调 */
@property (nonatomic, assign) BOOL paiedIsFail;
/** 点击 立即支付 按钮 */
@property (nonatomic, assign) BOOL clickGoPay;
@end

@implementation GMToFaceOrderViewController

- (void)initController {
    [super initController];
    self.immediateLoad = NO;
    _needHeaderRefresh = NO;
    _needFooterRefresh = NO;
    self.pageName = @"video_face_consultation_order";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNotification];
}
- (void)setUI {
    self.title = @"提交订单";
    self.navigationBar.isShowShadow = NO;
    [_table registerClass:[GMToFacePayTypeCell class] forCellReuseIdentifier:NSStringFromClass([GMToFacePayTypeCell class])];
    _table.tableHeaderView = self.headerView;
    _table.tableHeaderView.height = 122;
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(49+UIView.safeAreaInsetsBottom);
    }];
    /** 扩展参数 */
    NSMutableDictionary *param = [self.extraParam isNonEmpty] ? [[self.extraParam dictionaryWithJsonString] mutableCopy] : [NSMutableDictionary new];
    [param setValue:@(self.counsellorType) forKey:@"counsellor_type"];
    [param setValue:SafeString(self.counsellorId) forKey:@"doctor_id"];
    self.extraParam = [NSString convertToBriefJsonString:param];
    self.businessId = self.orderModel.orderNo;
}


- (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)backAction:(OCNavigationBarButton *)button {
    [Phobos track:@"popup_view" attributes:@{@"page_name":self.pageName,
                                             @"order_id":self.orderModel.orderNo,
                                             @"popup_name":@"retain",
                                             @"doctor_id":SafeString(self.counsellorId),
                                             @"counsellor_type":@(self.counsellorType)
    }];
    [self showAlert];
    [self btnPhoboMethod:@"exit"];
}

- (void)setOrderModel:(GMToFacePayPrepareModel *)orderModel {
    _orderModel = orderModel;
    self.payViewModel.orderNo = orderModel.orderNo;
    self.payViewModel.paymentAmount = orderModel.paymentAmount;
    self.headerView.model = self.bottomView.model = orderModel;
    [_table reloadData];
}
#pragma mark - delegate and dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orderModel.paymentChannels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMToFacePayTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GMToFacePayTypeCell class]) forIndexPath:indexPath];
    cell.typeModel = self.orderModel.paymentChannels[indexPath.row];
    if (cell.typeModel.recommend) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.orderModel.paymentChannels enumerateObjectsUsingBlock:^(GMToFacePayTypeModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.recommend = indexPath.row == idx;
    }];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.sectionView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = UIColor.whiteColor;
    GMLabel *label = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x999999) fontSize:11];
    label.frame = CGRectMake(15, 28, MAINSCREEN_WIDTH - 15, 12);
    label.text = @"为避免订单失效，建议您在3分钟内完成支付";
    [backView addSubview:label];
    return backView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 55.f;
}
#pragma mark - 页面挽留弹窗
- (void)showAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"真的要离开吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"去意已决" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancelOrderMethod];
        [self btnPhoboMethod:@"definitely_decided"];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"继续支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self btnPhoboMethod:@"continue_to_pay"];
    }]];
    UIAlertAction *action = alert.actions.firstObject;
    //这个key是用 runtime属性列表Ivar遍历得到的
    [action setValue:RGBCOLOR_HEX(0x282828) forKey:@"titleTextColor"];
    [self presentViewController:alert animated:YES completion:nil];
}
//页面按钮的点击埋点
- (void)btnPhoboMethod:(NSString *)button_name {
    NSDictionary *dict = @{@"page_name":self.pageName,
                           @"order_id":self.orderModel.orderNo,
                           @"button_name":button_name,
                           @"doctor_id":self.counsellorId,
                           @"counsellor_type":@(self.counsellorType),
                           @"consultation_type":@(1),
    };
    [Phobos track:@"on_click_button" attributes:dict];
}
#pragma mark - 点击 "去意已决" 取消订单 成功后 并且返回
- (void)cancelOrderMethod {
    [GMHudModule showLoading:nil];
    [GMNetworking requestOCWithApi:API_ORDER_CANCEL method:GMHTTPMethodPost parameters:@{@"order_no":self.orderModel.orderNo} completion:^(GMResponseOC * _Nonnull responseObject) {
        [GMHudModule hideLoading];
        [GMHudModule toastInView:[UIApplication sharedApplication].keyWindow text:responseObject.message];
        [[GMBaseTool getCurrentViewController] popViewControllerAnimated:YES completion:nil];
    }];
}
#pragma mark - 点击 "立即支付"
- (void)payMethod {
    self.clickGoPay = YES;
    [self btnPhoboMethod:@"pay_immediately"];
    __weak typeof(self) weakSelf = self;
    [self.orderModel.paymentChannels enumerateObjectsUsingBlock:^(GMToFacePayTypeModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //取出选中的支付方式
        if (obj.recommend) {
            weakSelf.payViewModel.payType = [obj.name isEqualToString:@"alipay"] ? GMToFacePayTypeAlipay : GMToFacePayTypeWechat;
        }
    }];
    //目的是防止重复点击，所以必须要网络请求回来之后才可再次点击
    self.bottomView.isCanClick = NO;
    [self showLoading:nil];
    [self.payViewModel excuteToFacePayCompleteBlock:^(id responseObject) {
        weakSelf.bottomView.isCanClick = YES;
        [weakSelf hideLoading];
    } failedBlock:^(NSString *message) {
        //支付参数获取失败 则可以重新支付
        [weakSelf toast:message];
        [weakSelf hideLoading];
        weakSelf.bottomView.isCanClick = YES;
    }];
}
#pragma mark - notification
- (void)enterForground {
    if (!self.clickGoPay) {
        return;
    }
    self.clickGoPay = NO;
    self.bottomView.isCanClick = YES;
    //进到前台的方法会先于支付成功的回调走，所以需要延时执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //成功：收到成功回调则一直轮循后端的支付状态接口
        if (self.paiedIsFinish) {
            //证明已经走到支付成功的回调，已经开始调用递归，所以直接return就好
            return;
        }
        if (self.paiedIsFail) {
            return;
        }
        [GMHudModule hideLoading];
        //只有支付成功走递归，其他情况都只请求一次
        self.payViewModel.needRepeat = NO;
        [GMHudModule showLoading:nil];
        __weak typeof(self) weakSelf = self;
        [self.payViewModel excuteToFacePayQueryBacksSuccessBlock:^(GMResponseOC * _Nonnull responseObject) {
            [GMHudModule hideLoading];
            NSNumber *status = responseObject.data[@"order_status"];
            if ([status integerValue] == 2) {
                //2为已付款
                [weakSelf toast:@"支付成功，不要走开，立即进入视频面诊连线"];
                //回调到信息卡页面去做一些操作
                if (weakSelf.PaySuccessBlock) {
                    weakSelf.PaySuccessBlock(weakSelf.referer);
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf popViewControllerAnimated:NO completion:nil];
                    });
                }
            }else {
                [weakSelf toast:responseObject.message];
            }
        } failBlock:^(NSString *message) {
            [GMHudModule hideLoading];
            [weakSelf toast:message];
        }];
    });
}
#pragma mark - 支付成功回调
- (void)orderPaySuccess:(NSNotification *)notifi{
    self.bottomView.isCanClick = YES;
    [GMHudModule hideLoading];
    if (self.paiedIsFinish) {
        return;
    }
    self.paiedIsFinish = YES;
    [GMHudModule showLoading:nil];
    //客户端支付成功后需要查询后端是否支付成功，若后端也显示支付成功了则进行下一步，面诊
    __weak typeof(self) weakSelf = self;
    //循环调用请求订单状态接口
    self.payViewModel.needRepeat = YES;
    [self.payViewModel excuteToFacePayQueryBacksSuccessBlock:^(GMResponseOC * _Nonnull responseObject) {
        [GMHudModule hideLoading];
        weakSelf.paiedIsFinish = NO;
        NSNumber *status = responseObject.data[@"order_status"];
        if ([status integerValue] == 2) {//2为已付款
            [weakSelf toast:@"支付成功，不要走开，立即进入视频面诊连线"];
            //回调到信息卡页面去做一些操作
            if (weakSelf.PaySuccessBlock) {
                weakSelf.PaySuccessBlock(weakSelf.referer);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf popViewControllerAnimated:NO completion:nil];
                });
            }
        }else {
            [weakSelf toast:responseObject.message];
        }
    } failBlock:^(NSString *message) {
        weakSelf.paiedIsFinish = NO;
        [GMHudModule hideLoading];
        [weakSelf 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(), ^{
        [self showWarning:@"支付失败"];
        self.paiedIsFail = NO;
    });
    [GMHudModule hideLoading];
    self.bottomView.isCanClick = YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - getter
- (GMToFaceOrderHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[GMToFaceOrderHeaderView alloc] init];
        _headerView.backgroundColor = UIColor.whiteColor;
    }
    return _headerView;
}
- (GMToFacePaySectionHeaderView *)sectionView {
    if (!_sectionView) {
        _sectionView = [[GMToFacePaySectionHeaderView alloc] init];
    }
    return _sectionView;
}
- (GMToFaceOrderFooterView *)bottomView {
    if (!_bottomView) {
        __weak typeof(self) weakSelf = self;
        _bottomView = [[GMToFaceOrderFooterView alloc] initWithClickBlock:^{
            [weakSelf payMethod];
        }];
    }
    return _bottomView;
}
- (GMToFacePayViewModel *)payViewModel {
    if (!_payViewModel) {
        _payViewModel = [[GMToFacePayViewModel alloc] init];
    }
    return _payViewModel;
}
@end
