//
//  WDNetwork.m
//  Open
//
//  Created by 雷俊博 on 2020/9/2.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "WDNetwork.h"

@implementation WDNetwork
//把产品请求和判断是否开户两种请求封装到一块
+ (void)productListAndQueryAccountStateRequestWithComplection:(void(^)(bool success,SaveSubProductModel* proModel,SaveAccountInfoModel*accModel,NSString*errMessage))complection{
    
    
    //init
   __block SaveSubProductModel* currentModel = nil;
   __block NSString* currentMessage1 = nil;
    
    __block SaveAccountInfoModel*accountModel;
    __block NSString* currentMessage2 = nil;
    
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //网络请求1
        NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSGetProductListRequest];
        NSLog(@"银数产品列表url:%@",url);
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        NSLog(@"strHeader:%@",strHeader);
        [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
           
        dispatch_group_enter(group);
        [manager POST:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
           
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSLog(@"responseObject:%@",responseObject);
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString* result = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
            NSString* describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                NSDictionary*dic = [Tools dencode:result];
                NSLog(@"result:%@",[Tools dencode:result]);
                SaveProductModel*model = [SaveProductModel mj_objectWithKeyValues:dic];
                if (model.SUBPACKS.count > 0) {
                    NSData *archiveCarPriceData = [NSKeyedArchiver archivedDataWithRootObject:model];
                    [[NSUserDefaults standardUserDefaults]setObject:archiveCarPriceData forKey:@"productInfo"];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    NSLog(@"CURRNO:%@",model.CURRNO);
                    currentModel = model.SUBPACKS[0];
                }else{
                    currentMessage1 = @"暂无产品";
                }
               
                
            }else{
                NSDictionary*dic = [Tools dictionaryWithJsonString:describe];
                NSLog(@"describe:%@",dic);
                NSString*code = nil;
                NSString*message = nil;
                if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"code"]]]) {
                    code = [NSString stringWithFormat:@"%@",dic[@"code"]];
                }else if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"RETCODE"]]]){
                    code = [NSString stringWithFormat:@"%@",dic[@"RETCODE"]];
                }
                
                if (code) {
                    message = [KBankErrorCode showErrorMessageWithErrorCode:code];
                    
                    if (!message) {
                       message = @"系统错误";
                    }
                }else{
                    message = @"系统错误";
                }
                currentMessage1 = message;
            }
            
            dispatch_group_leave(group);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           NSLog(@"error:%@",error);
            currentMessage1 = @"网络异常";
            dispatch_group_leave(group);
        }];
    });
    
    
    
    
    
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       //网络请求2
        NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSQueryAccountStateRequest];
           
           NSDictionary*params = @{
               @"bankName":@"乌当银行",
               @"id":@([getPeopleID PeopleID]),
               @"tel":[getPeopleID PeopleIphoneNmber]
           };
           
           NSLog(@"银数查询是否开通账户url:%@",url);
           NSLog(@"params:%@",params);
           
           AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
           NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
           NSLog(@"strHeader:%@",strHeader);
           [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
           dispatch_group_enter(group);
            [manager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
               
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
               NSLog(@"responseObject:%@",responseObject);
                NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
                NSString* result = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                NSString* describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
                if ([state isEqualToString:@"200"]) {
                    NSDictionary*dic = [Tools dencode:result];
                    NSLog(@"result:%@",[Tools dencode:result]);
                    SaveAccountInfoModel*infoModel = [SaveAccountInfoModel mj_objectWithKeyValues:dic];
                    if (infoModel.SUBPACKS.count > 0) {
                        
                        accountModel = infoModel;
                    }else{
                        currentMessage2 = @"开通账户异常";
                    }
                       
                    
                }else if ([state isEqualToString:@"201"]){
                    currentMessage2 = state;
                }else{
                        NSDictionary*dic = [Tools dictionaryWithJsonString:describe];
                        NSLog(@"describe:%@",dic);
                        NSString*code = nil;
                        NSString*message = nil;
                        if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"code"]]]) {
                            code = [NSString stringWithFormat:@"%@",dic[@"code"]];
                        }else if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"RETCODE"]]]){
                            code = [NSString stringWithFormat:@"%@",dic[@"RETCODE"]];
                        }
                        
                        if (code) {
                            message = [KBankErrorCode showErrorMessageWithErrorCode:code];
                            
                            if (!message) {
                                message = @"系统错误";
                            }
                        }else{
                            message = @"系统错误";
                        }
                        
                        
                    currentMessage2 = message;
                    }
                dispatch_group_leave(group);
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               NSLog(@"error:%@",error);
                currentMessage2 = @"网络异常";
                dispatch_group_leave(group);
            }];
    });
   
       dispatch_group_notify(group, dispatch_get_main_queue(), ^{
           // 等前面的异步任务1、任务2都执行完毕后，回到主线程执行下边任务
           if (currentMessage1) {
               complection(NO,nil,nil,currentMessage1);
               return;
           }
           
           if (currentMessage2) {
               if ([currentMessage2 isEqualToString:@"201"]) {
                   complection(YES,currentModel,nil,currentMessage2);
               }else{
                    complection(NO, nil,nil,currentMessage2);
               }
              
           }
           
           if (currentModel&& accountModel) {
               if ([currentModel.PRSTATUS isEqualToString:@"0"]) {
                   complection(YES,currentModel,accountModel,nil);
               }else if ([currentModel.PRSTATUS isEqualToString:@"1"]){
                   complection(NO,nil,nil,@"活动产品已停止发售");
               }else if ([currentModel.PRSTATUS isEqualToString:@"2"]){
                   complection(NO,nil,nil,@"活动产品已售罄");
               }
               //产品状态(0：正常 1：停止发售 2：售罄)
               
           }
       });
    
    

}

+ (void)getProductListRequestWithComplection:(void(^)(bool success,SaveSubProductModel* proModel,NSString*errMessage))complection
{
    //init
    __block SaveSubProductModel* currentModel = nil;
    __block NSString* currentMessage1 = nil;
    
    //网络请求1
   NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSGetProductListRequest];
   NSLog(@"银数产品列表url:%@",url);
   
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
   NSLog(@"strHeader:%@",strHeader);
   [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
      
   [manager POST:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
      
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      NSLog(@"responseObject:%@",responseObject);
       NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
       NSString* result = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
       NSString* describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
       if ([state isEqualToString:@"200"]) {
           NSDictionary*dic = [Tools dencode:result];
           NSLog(@"result:%@",[Tools dencode:result]);
           SaveProductModel*model = [SaveProductModel mj_objectWithKeyValues:dic];
           if (model.SUBPACKS.count > 0) {
               NSData *archiveCarPriceData = [NSKeyedArchiver archivedDataWithRootObject:model];
               [[NSUserDefaults standardUserDefaults]setObject:archiveCarPriceData forKey:@"productInfo"];
               [[NSUserDefaults standardUserDefaults]synchronize];
               NSLog(@"CURRNO:%@",model.CURRNO);
               currentModel = model.SUBPACKS[0];
           }else{
               currentMessage1 = @"暂无产品";
           }
          
           
       }else{
           NSDictionary*dic = [Tools dictionaryWithJsonString:describe];
           NSLog(@"describe:%@",dic);
           NSString*code = nil;
           NSString*message = nil;
           if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"code"]]]) {
               code = [NSString stringWithFormat:@"%@",dic[@"code"]];
           }else if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"RETCODE"]]]){
               code = [NSString stringWithFormat:@"%@",dic[@"RETCODE"]];
           }
           
           if (code) {
               message = [KBankErrorCode showErrorMessageWithErrorCode:code];
               
               if (!message) {
                  message = @"系统错误";
               }
           }else{
               message = @"系统错误";
           }
           currentMessage1 = message;
       }
       
       if (currentModel) {
           if (complection) {
                complection(YES,currentModel,nil);
           }
       }else{
           if (complection) {
                complection(NO,nil,currentMessage1);
           }
       }
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      NSLog(@"error:%@",error);
       currentMessage1 = @"网络异常";
       if (complection) {
            complection(NO,nil,currentMessage1);
       }
      
   }];
}

@end
