//
//  NSString+GMediator.m
//  Gengmei
//
//  Created by licong on 12/28/15.
//  Copyright © 2015 Wanmeichuangyi. All rights reserved.
//

#import "NSString+GMediator.h"

@implementation NSString (GMediator)
- (NSDictionary*)GMediator_urlQueryToDictionary {
    NSURL *url = [NSURL URLWithString:self];
    if (!url) {
        return nil;
    }
    NSString *query = [url query];
    @try {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        NSArray *components = [query componentsSeparatedByString:@"&"];
        for (NSString *component in components) {
            NSArray *keyValue = [component componentsSeparatedByString:@"="];
            if ([keyValue count] > 1) {
                NSString *key = [[keyValue objectAtIndex:0] GMediator_URLDecodedString];
                NSString *value = [keyValue objectAtIndex:1];

                // 参数中依然包含超过2个“=”号（多数发生在common_webview后的url参数中），则后面的数组的元素需要拼接成一个字符串
                if ([keyValue count] > 2) {
                    for (int i = 2; i < [keyValue count]; i++) {
                        value = [value stringByAppendingString:@"="];
                        value = [value stringByAppendingString:keyValue[i]];
                    }
                }

                // 因为这种情况服务器和客户端都转义了一次，所以要两次反转义还原中文
                while ([value rangeOfString:@"%"].length != 0) {
                    value = [value GMediator_URLDecodedString];
                }
                [dict setObject:value forKey:key];
            }
        }
        return dict;
    }
    @catch (NSException *exception) {

    }
}

- (NSString *)GMediator_URLDecodedString {
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault,
                                                                                                             (CFStringRef)self,
                                                                                                             CFSTR("")));
    return result;
}

@end




