//
//  UIViewController+UrlScheme.m
//  Gengmei
//
//  Created by Thierry on 4/21/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "WMNetService.h"
#import "ALUrlSchemeMacro.h"
#import "UIViewController+UrlScheme.h"
@import GMAlbum;
#import "AppDelegate+ViewControl.h"
@import GMJSONModel;

#import "ALSetterUserInfoViewController.h"
#import "WMBaseWebViewController.h"

#import "ALGroupListVController.h"
#import "ALTopicListVController.h"
#import "ALPersonViewController.h"
#import "ALRankContainerViewController.h"
#import "ALFaceFittingViewController.h"
#import "ALScanFaceHomeViewController.h"


@implementation UIViewController (UrlScheme)

/**
 *  @brief  返回由此类处理的链接Host
 *
 *  @return
 */
- (NSDictionary *)getHostDictionary {

    static NSDictionary *dicts = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dicts = @{
                  HOST_LOGOUT:                    @"logoutAction:",
                  HOST_EDIT_USER_INFO:            @"pushToEditUserInfo:",
                  HOST_COMMON_WEBVIEW:            @"pushToCommonWebView:",
                  HOST_GROUP_DETAIL:              @"pushToGroupDetail:",
                  HOST_TOPIC_DETAIL:              @"pushToTopicDetail:",
                  HOST_USER_DETAIL:               @"pushToUserDetail:",
                  HOST_SELECT_TAB:                @"tabSelected:",//tab切换,根据不同的page
                  HOST_SCAN_FACE:                 @"pushToScanFace:",//去扫脸Vc
                  HOST_FACE_FITTING:              @"pushToFaceFitting:",//去人脸拟合
                  };
    });

    return dicts;
}

- (void)pushHost:(NSString *)host query:(NSString *)format, ... NS_FORMAT_FUNCTION(2,3) {
    if (![host isNonEmpty]) {
        return;
    }

    NSMutableString *url = [NSMutableString stringWithString:URL_SCHEME_PREFIX];
    [url appendString:host];

    if ([format isNonEmpty]) {
        va_list ap;
        va_start(ap, format);

        NSString *query = [[NSString alloc] initWithFormat:format arguments:ap];
        [url appendFormat:@"?%@", query];
    }
    [self pushScheme:url];
}

- (void)pushScheme:(NSString *)urlScheme
{
    @try {
        NSLog(@"pushScheme: %@", urlScheme);
        if (![urlScheme hasPrefix:URL_SCHEME_PREFIX]) {
            debugLog(@"url sheme without a right prefix");
        }
        else{
            // 很早以前的，有些更美协议是没有encode，而有些encode了，问题就出在这些没有encode过的更美协议，没有encode的更美协议一旦包含中文，query将无法解析
            // 为了保证所有更美协议工作正常，不得不对所有更美协议都在本地encode一次，再解析query时，会检查是否被二次encode
            NSString * encodeUrlScheme = [urlScheme URLEncodeString];
            NSURL* url = [NSURL URLWithString:encodeUrlScheme];
            if (!url) {
                debugLog(@"协议出错了!");
            }
            NSString* host = [url host];
            NSDictionary *params;
            if ([host isEqualToString:@"third_webview"] || [host isEqualToString:@"common_webview"]) {
                NSArray *array = [encodeUrlScheme componentsSeparatedByString:@"url="];
                NSString *value = array[1];
                while ([value rangeOfString:@"%"].length != 0) {
                    value = [value URLDecodedString];
                }
                params = @{@"url":value};
            } else {
                params = [encodeUrlScheme urlQueryToDictionary];
            }
            NSString *selectorName = [[self getHostDictionary] objectForKey:host];
            if(selectorName){
                SEL selector = NSSelectorFromString(selectorName);
                if([self respondsToSelector:selector]){
                    [self performSelector:selector withObject:params];
                }
            }
        }
    }
    @catch (NSException *exception) {
        debugLog(@"%@-%@",exception.reason,exception.description);
    }
}

/**
 *  @brief 登出操作
 *
 *  @param param
 *
 *  @since 5.7.0
 */
- (void)logoutAction:(NSDictionary *)param {
    [[GMLoginManager shareInstance] doLogout];
}

// 修改用户信息
- (void)pushToEditUserInfo:(NSDictionary *)param {
    
    [[AppDelegate shareInstance] enableShowNextRootView:[ALQAWebViewController class]];
    
}

// 跳转commonWebView
- (void)pushToCommonWebView:(NSDictionary *)param {
    
    WMBaseWebViewController *webViewCtrl = [WMBaseWebViewController new];
    webViewCtrl.path = param[@"url"];
    [AppDelegate.navigation pushViewController:webViewCtrl animated:YES];
}

// 根据groupId,去小组详情
- (void)pushToGroupDetail:(NSDictionary *)param {
    NSInteger group_id = [param[@"group_id"] integerValue];
    NSInteger topic_id = [param[@"topic_id"] integerValue];
    WMCommentHandle commentHandle = WMCommentHandleNoShow;
    if ([param[@"open_comment"] boolValue]) {
        if ([param[@"call_keyboard"] boolValue]) {
            commentHandle = WMCommentHandleReply;
        } else {
            commentHandle = WMCommentHandleLook;
        }
    }
    ALGroupListVController *toVc = [[ALGroupListVController alloc] initWithGroupId:group_id topicId:topic_id];
    toVc.showComment = commentHandle;
    [AppDelegate.navigation pushViewController:toVc animated:YES];
}

// 根据topicId,去帖子详情
- (void)pushToTopicDetail:(NSDictionary *)param {
    
    NSInteger topic_id = [param[@"topic_id"] integerValue];
    WMCommentHandle commentHandle = WMCommentHandleNoShow;    
    if ([param[@"open_comment"] boolValue]) {
        if ([param[@"call_keyboard"] boolValue]) {
            commentHandle = WMCommentHandleReply;
        } else {
            commentHandle = WMCommentHandleLook;
        }
    }
    ALTopicListVController *toVc = [[ALTopicListVController alloc] initWithTopicId:topic_id];
    toVc.showComment = commentHandle;
    [AppDelegate.navigation pushViewController:toVc animated:YES];
}

// 根据用户id,去用户中心Vc
- (void)pushToUserDetail:(NSDictionary *)param {
    NSInteger user_id = [param[@"user_id"] integerValue];
    ALPersonViewController *toVc = [[ALPersonViewController alloc]initWithUserId:user_id];
    [AppDelegate.navigation pushViewController:toVc animated:YES];
}


- (void)tabSelected:(NSDictionary *)param {
    NSString *page = [NSString stringWithFormat:@"%@", param[@"page"]];
    GMTabBarController *tabBarVc = AppDelegate.tabBarController;
    if ([page isEqualToString:@"home"]) {
        [tabBarVc selectTab:0];
    }else if ([page isEqualToString:@"group"]) {
        [tabBarVc selectTab:1];
    }else if ([page isEqualToString:@"pick"]) {
        NSInteger pick_id = [param[@"pick_id"] integerValue] ? : 0;
        NSInteger pick_user_id = [param[@"pick_user_id"] integerValue] ? : 0;
        UIViewController *toVc = tabBarVc.childViewControllers[2];
        if (![toVc isKindOfClass:[ALRankContainerViewController class]]) return;
        ALRankContainerViewController *goToVc = (ALRankContainerViewController *)toVc;
        goToVc.viewModel.refreshData = YES;
        if (pick_id != 0) {
            goToVc.viewModel.pick_id = [NSString stringWithFormat:@"%ld", (long)pick_id];
        }
        if (pick_user_id != 0) {
            goToVc.viewModel.pick_user_id = [NSString stringWithFormat:@"%ld", (long)pick_user_id];
        }
        [tabBarVc selectTab:2];
    }else if ([page isEqualToString:@"message"]) {
        [tabBarVc selectTab:3];
    }else if ([page isEqualToString:@"personal"]) {
        [tabBarVc selectTab:4];
    }
}

- (void)pushToScanFace:(NSDictionary *)param {
    ALScanFaceHomeViewController *toVc = [[ALScanFaceHomeViewController alloc] init];
    [AppDelegate.navigation pushViewController:toVc animated:YES];
}

- (void)pushToFaceFitting:(NSDictionary *)param {
    ALFaceFittingViewController *toVc = [[ALFaceFittingViewController alloc] init];
    [AppDelegate.navigation pushViewController:toVc animated:YES];
}

@end
