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

#import "GMToFacePayViewModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiObject.h"
#import "WXApi.h"
#import "GMPayResultModel.h"
#import "GMThirdPartyDefine.h"
#import "RequestHeader.h"
#import "GMLibraryHeader.h"
#import <GMBase/GMBaseTool.h>

/***  @brief 订单支付部分*/
#define ORDER_PAY_SUCCESS                       @"order_pay_success"
//订单支付成功
#define ORDER_PAY_FAIL                          @"order_pay_fail"

@interface GMToFacePayViewModel ()

@end

@implementation GMToFacePayViewModel
/**
 * 支付接口
 */
- (void)excuteToFacePayCompleteBlock:(HttpSuccessBlock)successBlock failedBlock:(HttpFailedBlock)failedBlock {
    if (self.payType == GMToFacePayTypeAlipay && ![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]]) {
        [[GMBaseTool getCurrentViewController] toast:@"请安装支付宝"];
        return;
    }
    if (self.payType == GMToFacePayTypeWechat && ![WXApi isWXAppInstalled]) {
        [[GMBaseTool getCurrentViewController] toast:@"请安装微信"];
        return;
    }
    NSString *channel;
    if (self.payType == GMToFacePayTypeAlipay) {
        channel = @"alipay";
    }else if (self.payType == GMToFacePayTypeWechat) {
        channel = @"wechat";
    }
    NSDictionary *params = @{@"order_no":SafeString(self.orderNo),
                             @"payment_amount":@(self.paymentAmount),
                             @"channel":SafeString(channel)
    };
    __weak typeof(self) weakSelf = self;
    [GMNetworking requestOCWithApi:API_ORDER_PAYMENT method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * _Nonnull responseObject) {
        if (responseObject.isSuccess) {
            if (weakSelf.payType == GMToFacePayTypeAlipay) {
                [weakSelf payMoneyWithAlipay:responseObject.data];
            }else if(weakSelf.payType == GMToFacePayTypeWechat) {
                [weakSelf payMoneyWithWeixin:responseObject.data];
            }
            successBlock(responseObject);
        } else {
            failedBlock(responseObject.message);
        }
    }];
}
/**
 * 查询后端的支付状态
 */
- (void)excuteToFacePayQueryBacksSuccessBlock:(HttpSuccessBlock)successBlock failBlock:(HttpFailedBlock)failBlock {
    NSDictionary *params = @{@"order_no":SafeString(self.orderNo)};
    __weak typeof(self) weakSelf = self;
    [GMNetworking requestOCWithApi:API_ORDER_PAY_STATUS method:GMHTTPMethodGet parameters:params completion:^(GMResponseOC * _Nonnull responseObject) {
        if (responseObject.isSuccess) {            
            NSNumber *status = responseObject.data[@"order_status"];
            if ([status integerValue] == 0) {
                //如果请求成功且待支付状态则需要轮循请求后端状态，原因是前后端支付状态可能会不一致
                if (weakSelf.needRepeat) {
                    [weakSelf excuteToFacePayQueryBacksSuccessBlock:successBlock failBlock:failBlock];
                }else {
                    successBlock(responseObject);
                }
            }else {
                successBlock(responseObject);
            }
        } else {
            failBlock(responseObject.message);
        }
    }];
}
/***  @brief  支部宝支付,采用客户端签名*/
- (void)payMoneyWithAlipay:(NSDictionary *)dictionary{
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"gengmei";
    NSString *orderString = dictionary[@"payment_params"];
    if ([orderString isNonEmpty]) {
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //不会走到这里，因为没有支付宝会让下载支付宝
            //支付宝wap通道支付结果回调
            int statusCode = [resultDic[@"resultStatus"] intValue];
            if (statusCode == 9000) {
                //验证签名成功，交易结果无篡改，这里是wap支付成功回调
                [[NSNotificationCenter defaultCenter] postNotificationName:ORDER_PAY_SUCCESS object:nil];
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:ORDER_PAY_FAIL object:nil];
            }
        }];
    }
}
/***  @brief  微信支付--支付宝采用客户端签名，微信采用是服务器端签名*/
- (void)payMoneyWithWeixin:(NSDictionary *)dictionary{
    
    //调起微信支付
    NSDictionary *dict = dictionary[@"payment_params"];
    PayReq* request             = [[PayReq alloc] init];
    request.openID              = [dict objectForKey:@"appid"];
    request.partnerId           = [dict objectForKey:@"partnerid"];
    request.prepayId            = [dict objectForKey:@"prepayid"];
    request.nonceStr            = [dict objectForKey:@"noncestr"];
    request.timeStamp           = [[dict objectForKey:@"timestamp"] intValue];
    request.package             = @"Sign=WXPay"; //这里是填写固定的字符串
    request.sign                = [dict objectForKey:@"sign"];
    [WXApi sendReq:request completion:^(BOOL success) {
        
    }];    
}
@end
