//
//  UIView+Request.m
//  MoistureOil
//
//  Created by nana on 2020/4/2.
//  Copyright © 2020 idankee. All rights reserved.
//

#import "UIView+Request.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>

#define kLimitNetwokTimeout (15)


@implementation UIView (Request)
static NSMutableDictionary *defaultDict = nil;
static NSString *defaultHost = nil;

/// 设置授权服务器
+(void)setDefaultHost:(NSString *)host {
    defaultHost = host;
}

+(void)setAuthorizationDefaultRequestValue:(NSString *)value key:(NSString *)key {
    if (!value || !key) {
        return;
    }
    if (!defaultDict) {
        defaultDict = [[NSMutableDictionary alloc] init];
    }
    defaultDict[key] = value;
}

-(NSString *)checkUrlString:(NSString *)url {
    NSString *urlString = url;
    if (![url hasPrefix:@"http:"]) {
        if ([url hasPrefix:@"/"] && [defaultHost hasSuffix:@"/"]) {
            urlString = [NSString stringWithFormat:@"%@%@",defaultHost,[url substringFromIndex:1]];
        }else if (![url hasPrefix:@"/"] && ![defaultHost hasSuffix:@"/"]) {
            urlString = [NSString stringWithFormat:@"%@/%@",defaultHost,url];
        }else {
            urlString = [NSString stringWithFormat:@"%@%@",defaultHost,url];
        }
    }
    return urlString;
}


-(void)postFormDataWithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *responseObject,JFResponseModel *JsonData))success {
    //    self.userInteractionEnabled = NO;
    NSString *urlString = [self checkUrlString:url];
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = kLimitNetwokTimeout;
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //是否允许CA不信任的证书通过
    policy.allowInvalidCertificates = YES;
    //是否验证主机名
    policy.validatesDomainName = NO;
    manager.securityPolicy = policy;
    __block BOOL requestState = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //        self.userInteractionEnabled = YES;
        if (!requestState) {
            [SVProgressHUD show];
        }
    });
    /// 拼接授权
    NSMutableDictionary *apDict = [[NSMutableDictionary alloc] initWithDictionary:params];
    [apDict addEntriesFromDictionary:defaultDict];
    [[manager POST:urlString parameters:apDict  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,apDict,responseObject);
        requestState = YES;
        [SVProgressHUD dismiss];
        JFResponseModel *JsonData = [JFResponseModel mj_objectWithKeyValues:responseObject];
        success(responseObject,JsonData);
        if ([JsonData.code isEqualToString:@"-4"]) {
            [self refreshToken];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestState = YES;
        [SVProgressHUD dismiss];
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,apDict,error);
        success(nil,nil);
        [SVProgressHUD showInfoWithStatus:(@"网络异常,请检查网络设置")];
    }] resume] ;
}

-(void)postJsonWithUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *responseObject,JFResponseModel *JsonData))success {
    //      self.userInteractionEnabled = NO;
    /// 拼接授权
    NSMutableArray *auUrlStringArray = [[NSMutableArray alloc] init];
    for (NSString *key in [defaultDict allKeys]) {
        [auUrlStringArray addObject:[NSString stringWithFormat:@"%@=%@",key,defaultDict[key]]];
    }
    NSString *urlString = [NSString stringWithFormat:@"%@?%@",[self checkUrlString:url],[auUrlStringArray componentsJoinedByString:@"&"]];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = kLimitNetwokTimeout;
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //是否允许CA不信任的证书通过
    policy.allowInvalidCertificates = YES;
    //是否验证主机名
    policy.validatesDomainName = NO;
    manager.securityPolicy = policy;
    __block BOOL requestState = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //        self.userInteractionEnabled = YES;
        if (!requestState) {
            [SVProgressHUD show];
        }
    });
    
    [[manager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,params,responseObject);
        requestState = YES;
        [SVProgressHUD dismiss];
        JFResponseModel *JsonData = [JFResponseModel mj_objectWithKeyValues:responseObject];
        success(responseObject,JsonData);
        if ([JsonData.code isEqualToString:@"-4"]) {
            [self refreshToken];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestState = YES;
        [SVProgressHUD dismiss];
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,params,error);
        success(nil,nil);
        [SVProgressHUD showInfoWithStatus:(@"网络异常,请检查网络设置")];
    }] resume];
}

-(void)postFormDataWithUrl:(NSString *)url params:(NSDictionary *)params showHUD:(BOOL)showHUD success:(void (^)(NSDictionary *responseObject,JFResponseModel *JsonData))success {
    //    self.userInteractionEnabled = NO;
    NSString *urlString = [self checkUrlString:url];
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = kLimitNetwokTimeout;
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //是否允许CA不信任的证书通过
    policy.allowInvalidCertificates = YES;
    //是否验证主机名
    policy.validatesDomainName = NO;
    manager.securityPolicy = policy;
    __block BOOL requestState = NO;
    if (showHUD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //        self.userInteractionEnabled = YES;
            if (!requestState) {
                [SVProgressHUD show];
            }
        });
    }

    /// 拼接授权
    NSMutableDictionary *apDict = [[NSMutableDictionary alloc] initWithDictionary:params];
    [apDict addEntriesFromDictionary:defaultDict];
    [[manager POST:urlString parameters:apDict  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,apDict,responseObject);
        requestState = YES;
        if (showHUD) {
            [SVProgressHUD dismiss];
        }

        JFResponseModel *JsonData = [JFResponseModel mj_objectWithKeyValues:responseObject];
        success(responseObject,JsonData);
        if ([JsonData.code isEqualToString:@"-4"]) {
            [self refreshToken];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestState = YES;
        if (showHUD) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showInfoWithStatus:(@"网络异常,请检查网络设置")];
        }

        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,apDict,error);
        success(nil,nil);

    }] resume] ;
}

-(void)postJsonWithUrl:(NSString *)url params:(NSDictionary *)params showHUD:(BOOL)showHUD success:(void (^)(NSDictionary *responseObject,JFResponseModel *JsonData))success {
    
    NSMutableArray *auUrlStringArray = [[NSMutableArray alloc] init];
    for (NSString *key in [defaultDict allKeys]) {
        [auUrlStringArray addObject:[NSString stringWithFormat:@"%@=%@",key,defaultDict[key]]];
    }
    NSString *urlString = [NSString stringWithFormat:@"%@?%@",[self checkUrlString:url],[auUrlStringArray componentsJoinedByString:@"&"]];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = kLimitNetwokTimeout;
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //是否允许CA不信任的证书通过
    policy.allowInvalidCertificates = YES;
    //是否验证主机名
    policy.validatesDomainName = NO;
    manager.securityPolicy = policy;
    __block BOOL requestState = NO;
    if (showHUD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //        self.userInteractionEnabled = YES;
            if (!requestState) {
                [SVProgressHUD show];
            }
        });
    }
    
    
    [[manager POST:urlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,params,responseObject);
        requestState = YES;
        if (showHUD) {
            [SVProgressHUD dismiss];
        }
        
        JFResponseModel *JsonData = [JFResponseModel mj_objectWithKeyValues:responseObject];
        success(responseObject,JsonData);
        if ([JsonData.code isEqualToString:@"-4"]) {
            [self refreshToken];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        requestState = YES;
        if (showHUD) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showInfoWithStatus:(@"网络异常,请检查网络设置")];
        }
        NSLog(@"url:%@\nparameters:%@\nresponseObject:%@",urlString,params,error);
        success(nil,nil);
    }] resume];
    
}

- (void)refreshToken {

    @weakify(self);
    [self postFormDataWithUrl:@"/token/createToken" params:nil showHUD:NO success:^(NSDictionary * _Nonnull responseObject, JFResponseModel * _Nonnull JsonData) {
        @strongify(self);
        if ([JsonData.code isEqualToString:@"200"] && [JsonData.data isKindOfClass:[NSArray class]]) {
            NSArray *dataArray = (NSArray *)JsonData.data;
            [UIView setAuthorizationDefaultRequestValue:dataArray.firstObject  key:@"token"];
        }
        
    }];
}

@end
