//
//  HttpCilent.m
//  Car
//
//  Created by Javen on 2016/12/23.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "HttpCilent.h"
#import "AFNetworking.h"

@interface HttpCilent ()
@property(nonatomic, strong) AFHTTPSessionManager *manager;
@end

@implementation HttpCilent

+ (HttpCilent *_Nullable)shareCilent {
  static HttpCilent *cilent;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    cilent = [[HttpCilent alloc] init];
  });
  return cilent;
}

- (AFHTTPSessionManager *)manager {
  if (!_manager) {
    _manager = [[AFHTTPSessionManager alloc]
                initWithBaseURL:[NSURL URLWithString:REST_BASE_URL]];
    CLog(@"%@", REST_BASE_URL);
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];
    _manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [_manager.requestSerializer setValue:@"application/json;charset=utf-8"
                      forHTTPHeaderField:@"Content-Type"];
    [_manager.requestSerializer setValue:@"application/json;charset=utf-8"
                      forHTTPHeaderField:@"Accept"];
    _manager.requestSerializer.timeoutInterval = 15.0f;
  }
  return _manager;
}

- (void)POST:(NSString *)URLString
  parameters:(id)parameters
    complete:(void (^)(id response, NSError *error))complete {
  HIDE_KEYBOARD;
  NSString *url = [URLString
                   stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  WS(weakSelf);
  [self.manager POST:url
          parameters:parameters
            progress:^(NSProgress *_Nonnull uploadProgress) {
              
            }
             success:^(NSURLSessionDataTask *_Nonnull task,
                       id _Nullable response) {
               NSDictionary *dic = response;
               NSString *paramJsonString = [weakSelf dictionaryToJson:parameters];
               CLog(@"\n--------------------\n\n POST URL:\n %@/%@\n\n PARAMS: "
                    @"\n%@\n\n RESPONSE: \n%@\n\n--------------------\n",
                    REST_BASE_URL, url, paramJsonString,
                    [weakSelf dictionaryToJson:dic]);
               complete(response, nil);
             }
             failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
               complete(nil, error);
               CLog(@"\n--------------------\n\n POST URL:\n %@/%@\n\n PARAMS: "
                    @"\n%@\n\n FAILED:\n%@\n\n--------------------\n",
                    REST_BASE_URL, url, [weakSelf dictionaryToJson:parameters],
                    [error localizedDescription]);
#ifdef DEBUG
               NSString *errorInfo =
               [NSString stringWithFormat:@"url = %@ \n %@", URLString,
                [error localizedDescription]];
               [MBProgressHUD j_error:errorInfo complete:nil];
#else
               [MBProgressHUD j_error:@"网络错误，请检查网络！" complete:nil];
#endif
             }];
}

- (void)GET:(NSString *)URLString
 parameters:(id)parameters
   complete:(void (^)(id responseObject, NSError *error))complete {
  HIDE_KEYBOARD;
  WS(weakSelf);
  [self.manager GET:URLString
         parameters:parameters
           progress:^(NSProgress *_Nonnull downloadProgress) {
             
           }
            success:^(NSURLSessionDataTask *_Nonnull task,
                      id _Nullable responseObject) {
              
              NSDictionary *dic = responseObject;
              CLog(@"\n--------------------\n\n GET URL:\n %@/%@\n\n PARAMS: "
                   @"\n%@\n\n RESPONSE: \n%@\n\n--------------------\n",
                   REST_BASE_URL, URLString, [weakSelf dictionaryToJson:parameters],
                   [weakSelf dictionaryToJson:dic]);
              complete(responseObject, nil);
            }
            failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
              CLog(@"\n----------request fail----------\n\n GET URL:\n %@/%@\n\n "
                   @"PARAMS: \n%@\n\n FAILED:\n%@\n\n--------------------\n",
                   REST_BASE_URL, URLString, [weakSelf dictionaryToJson:parameters],
                   [error localizedDescription]);
#ifdef DEBUG
              NSString *errorInfo =
              [NSString stringWithFormat:@"url = %@ \n %@", URLString,
               [error localizedDescription]];
              [MBProgressHUD j_error:errorInfo complete:nil];
#else
              [MBProgressHUD j_error:@"网络错误，请检查网络！" complete:nil];
#endif
              complete(nil, error);
            }];
}

- (void)checkUpdateOnVC:(UIViewController *)vc
       completeIsLatest:(void (^)(void))compelete {
  //版本号 取的是build
  NSString *version = APP_VERSION;
  
  NSDictionary *myDictionary = @{@"apptype" : @"merchant_ios",
                                 @"version" : version};
 __weak typeof(vc) weakVC = vc;
  [[[self class] shareCilent]
   GET:@"stationUser/getUpgrade"
   parameters:myDictionary
   complete:^(id response, NSError *error) {
     if ([response[@"code"] isEqualToNumber:@0]) {
       CLog(@"本地版本：%@", version);
       
       NSDictionary *dic = response[@"data"];
       if ([dic isKindOfClass:[NSNull class]]) {
         return;
       }
      TOAppversionEntity *appVersion = [[TOAppversionEntity alloc] initWithDictionary:dic error:nil];
       NSString *lastestVersion = appVersion.version;
       BOOL isForceUpdate = [appVersion.forceupdate isEqualToString:@"true"];
       NSString *trackViewUrl = dic[@"url"];
       

       
       
       if ([self version:version lessthan:lastestVersion]) { //版本号不同
         NSString *alertTitle =
         [NSString stringWithFormat:@"有新版本%@可以下载",
          lastestVersion];
         UIAlertController *alert = [UIAlertController
                                     alertControllerWithTitle:@"提示"
                                     message:alertTitle
                                     preferredStyle:UIAlertControllerStyleAlert];
         __weak typeof(alert) weakAlert = alert;
         UIAlertAction *action = [UIAlertAction
                                  actionWithTitle:@"前往更新"
                                  style:UIAlertActionStyleDestructive
                                  handler:^(UIAlertAction *_Nonnull action) {
                                    [weakVC presentViewController:weakAlert
                                                         animated:YES
                                                       completion:nil];
                                    [[UIApplication sharedApplication]
                                     openURL:[NSURL URLWithString:trackViewUrl]];
                                  }];
         [alert addAction:action];
         
         if (!isForceUpdate) {
           
           [alert addAction:({
             UIAlertAction *action = [UIAlertAction
                                      actionWithTitle:@"暂不更新"
                                      style:UIAlertActionStyleDefault
                                      handler:nil];
             action;
           })];
         }
         
         [weakVC presentViewController:alert animated:YES completion:nil];
       } else {
         compelete();
       }
     }
   }];
}

- (BOOL)version:(NSString *)_oldver
       lessthan:(NSString *)_newver //系统api
{
  if ([_oldver compare:_newver options:NSNumericSearch] == NSOrderedAscending) {
    return YES;
  }
  return NO;
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic {
  NSString *jsonString = nil;
  if (![dic isKindOfClass:[NSDictionary class]]) {
    return @"param is not dic";
  }
  if (dic == nil) {
    return @"param is nil";
  } else {
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dic
                        options:NSJSONWritingPrettyPrinted // Pass 0 if you don't
                        // care about the
                        // readability of the
                        // generated string
                        error:&parseError];
    if (!jsonData) {
      CLog(@"Got an error: %@", parseError);
    } else {
      jsonString = [[NSString alloc] initWithData:jsonData
                                         encoding:NSUTF8StringEncoding];
    }
  }
  return jsonString;
}

- (NSString *)checkUrl:(NSString *)url {
  if ([self stringIsHasChinese:url]) {
    return [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  } else {
    return url;
  }
}

/** 是否含有汉字 */
- (BOOL)stringIsHasChinese:(NSString *)string {
  int length = (int)[string length];
  for (int i = 0; i < length; ++i) {
    NSRange range = NSMakeRange(i, 1);
    NSString *subString = [string substringWithRange:range];
    const char *cString = [subString UTF8String];
    if (strlen(cString) == 3) {
      return YES;
    }
  }
  return NO;
}


@end
