//
//  GMSignInManager.m
//  Gengmei
//
//  Created by Terminator on 2017/8/21.
//  Copyright © 2017年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMSignInManager.h"
#import "GMLocationManager.h"
//#import "WMLocationObject.h"
#import "GMLoginManager.h"
#import "WMUser.h"
//#import "Gengmei-Swift.h"

static  NSString * qqAuthType       = @"QZone";
static  NSString * sinaAuthType     = @"SinaWeibo";
static  NSString * weixinAuthType   = @"Wechat";
static  NSString * key              = @"Up[K+ub%pliOnsO5UavFBd)cw5VcyHSX";  //AES加密密钥

@implementation GMSignInManager

+ (instancetype)sharedManager{
    static GMSignInManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[GMSignInManager alloc] init];
        sharedManager.referer = @"";
    });
    return sharedManager;
}

/**
 *  @brief  获取验证码
 */
+ (void)sendVerifyCodeAccount_type:(ALSignInType)account_type
                           vfcType:(ALVfcType)vfcType
                             email:(NSString *)email
                             phone:(NSString *)phone
                       finishBlock:(FinishBlock)finishBlock {
    
    NSDictionary *param = @{@"account_type":@(account_type),
                            @"code_type":@(vfcType),
                            @"phone":[SafeString(phone) trimBothEnd],
                            @"email": SafeString(email),
                            @"verifier":[[[phone stringByAppendingString:@"_rpwt_zhengxing"] trimBothEnd] stringFromMD5]};
    [GMHudModule showLoading:nil];
    [GMNetworking requestOCWithApi:API_ACCOUNT_GETVFC method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            finishBlock(@"验证码获取成功", YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 *  @brief  用户注册
 */
+ (void)registerWithAccount_type:(ALSignInType)account_type
                                  vfcType:(NSString *)vfcType
                                    email:(NSString *)email
                                    phone:(NSString *)phone
                                      pwd:(NSString *)pwd
                              finishBlock:(FinishBlock)finishBlock {
    
    NSDictionary *param = @{@"account_type":@(account_type),
                            @"vfc_code":SafeString(vfcType),
                            @"phone":[SafeString(phone) trimBothEnd],
                            @"email": SafeString(email),
                            @"pwd":SafeString(pwd)};
    [GMHudModule showLoading:nil];
    [GMNetworking requestOCWithApi:API_ACCOUNT_REGISTER method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            NSDictionary *dataDict = (NSDictionary *)responseObject.data;
            [[GMLoginManager shareInstance] loginSuccessWithUserInfo:dataDict  shouldBroadcast:YES];
            finishBlock(responseObject.message, YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 *  @brief  用户登录
 */
+ (void)loginWithAccount_type:(ALSignInType)account_type
                                    email:(NSString *)email
                                    phone:(NSString *)phone
                                      pwd:(NSString *)pwd
                              finishBlock:(FinishBlock)finishBlock {
    
    NSDictionary *param = @{@"account_type":@(account_type),
                            @"phone":[SafeString(phone) trimBothEnd],
                            @"email": SafeString(email),
                            @"pwd":SafeString(pwd)};
    [GMHudModule showLoading:nil];
    [GMNetworking requestOCWithApi:API_ACCOUNT_LOGIN_PWD method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            NSDictionary *dataDict = (NSDictionary *)responseObject.data;
            [[GMLoginManager shareInstance] loginSuccessWithUserInfo:dataDict  shouldBroadcast:YES];
            finishBlock(@"登录成功", YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 *  @brief  第三方登陆
 */
+ (void)loginWithType:(GMSharePlatform)shareType finishBlock:(FinishBlock)finishBlock {

    [GMThirdPartyLoginHelper loginByPlatform:shareType onUserSync:^(GMShareResponseState state, GMThirdPartyUser *user) {
        if (state == GMShareResponseStateSuccess){
            NSMutableDictionary *parameters = [[GMSignInManager loginParametersWithUser:user] mutableCopy];
            
            [GMHudModule showLoading:nil];
            [GMNetworking requestOCWithApi:API_ACCOUNT_THIRDPART method:GMHTTPMethodPost parameters:parameters completion:^(GMResponseOC * responseObject) {
                [GMHudModule hideLoading];
                if (responseObject.isSuccess) {
                    NSDictionary *dataDict = (NSDictionary *)responseObject.data;
                    [[GMLoginManager shareInstance] loginSuccessWithUserInfo:dataDict  shouldBroadcast:YES];
                    finishBlock(@"登录成功", YES, nil);
                } else {
                    finishBlock(responseObject.message, NO, nil);
                }
            }];
            
        } else if(state == GMShareResponseStateFail){
            finishBlock(@"登录失败，请重试", NO, nil);
        } else if(state == GMShareResponseStateCancel){
            finishBlock(@"登录失败，请重试", NO, nil);
        } else if(state == GMShareResponseStateBack){
            finishBlock(@"登录失败，请重试", NO, nil);
        }
    }];
}

/**
 *  @brief  用户注销
 */
+ (void)loginOut:(FinishBlock)finishBlock {
    
    WMUser *user = [[GMLoginManager shareInstance] user];
    NSDictionary *param = @{@"user_id":@(user.userId)};
    [GMHudModule showLoading:nil];
    // 登出接口，通知服务器清除后台对应当前用户的session
    [GMNetworking requestOCWithApi:API_LOGOUT method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            finishBlock(responseObject.message, YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 * @brief  绑定手机号
 */
+ (void)bindAccount:(ALSignInType)account_type
              email:(NSString *)email
              phone:(NSString *)phone
               code:(NSString *)code
             userId:(NSInteger)userId
        finishBlock:(FinishBlock)finishBlock
{
    NSDictionary *param = @{
                            @"account_type":@(account_type),
                            @"account_id":[SafeString(phone) trimBothEnd],
                            @"vfc_code": SafeString(code),
                            @"user_id":@(userId),
                           };
    [GMNetworking requestOCWithApi:API_BINDPHONE method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        if (responseObject.isSuccess) {
            finishBlock(responseObject.message, YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 * @brief  获取用户基本信息
 */
+ (void)getUserProfileUserId:(NSInteger)userId finishBlock:(FinishBlock)finishBlock {
    
    [GMHudModule showLoading:nil];
    NSDictionary *param = @{@"user_id":@(userId)};
    [GMNetworking requestOCWithApi:API_ACCOUNT_USER_PROFILE method:GMHTTPMethodGet parameters:param completion:^(GMResponseOC * responseObject) {
        [GMHudModule hideLoading];
        if (responseObject.isSuccess) {
            NSDictionary *dataDict = (NSDictionary *)responseObject.data;
            [[GMLoginManager shareInstance] saveUserWithUserInfo:dataDict];
            finishBlock(responseObject.message, YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

/**
 * @brief  设置用户信息
 */
+ (void)setUserProfileUserId:(NSInteger)userId country_id:(NSString *)country_id nick_name:(NSString *)nick_name profile_pic:(NSString *)profile_pic age:(NSString *)age finishBlock:(FinishBlock)finishBlock {
    
    NSDictionary *paramTemp = @{
                                @"user_id":SafeNumber(@(userId)),
                                @"nick_name":SafeString(nick_name),
                                @"profile_pic": SafeString(profile_pic),
                                @"age":SafeString(age)
                                };
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:paramTemp];
    if ([country_id isNonEmpty]) {
        [param setValue:SafeNumber(country_id) forKey:@"country_id"];
    }

    [GMNetworking requestOCWithApi:API_ACCOUNT_USER_SETTLE method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        if (responseObject.isSuccess) {
            NSDictionary *dataDict = (NSDictionary *)responseObject.data;
            [[GMLoginManager shareInstance] saveUserWithUserInfo:dataDict];
            finishBlock(responseObject.message, YES, nil);
        } else {
            finishBlock(responseObject.message, NO, nil);
        }
    }];
}

#pragma mark - 拼接登陆body需要上传的参数
+ (NSDictionary *)loginParametersWithUser:(GMThirdPartyUser *)user{    
    ALSignInType authType = ALSignInTypeUNKNOWN;
    NSString *nickName = nil;
    NSString *authUserId = nil;
    NSString *portrait = user.icon;
    debugLog(@"platformType = %lu",(unsigned long)user.platformType);
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
    if (user.platformType == GMSharePlatformQQ) {
        authType = ALSignInTypeQQ;
        nickName = user.nickname;
        authUserId = user.uid;
    }
    else if(user.platformType == GMSharePlatformSinaWeibo){
        authType = ALSignInTypeSinaBlog;
        nickName = user.nickname;
        authUserId = user.uid;
    }
    else if(user.platformType == GMSharePlatformWechat){
        authType = ALSignInTypeWeChat;
        nickName = user.nickname;
        //5.1微信的auth_user_id改传为unionid
        authUserId = user.unionid;
    }
    param[@"account_type"] = @(authType);
    param[@"nick_name"] = nickName;
    param[@"third_profile_pic"] = portrait;
    
    //加密authUserId
    NSDictionary *enencryptDic = [GMSignInManager encryptAuthUserId:authUserId
                                                       third_detail:user.third_detail];
    [param addEntriesFromDictionary:enencryptDic];
    
    param[@"city"] = user.city;
    param[@"province"] = user.provice;
    param[@"lat"] = @([GMLocationManager shareInstance].location.coordinate.latitude);
    param[@"lng"] = @([GMLocationManager shareInstance].location.coordinate.longitude);
    return param;
}

#pragma mark - 加密AuthUserId
+ (NSDictionary *)encryptAuthUserId:(NSString *)authUserId third_detail:(NSString *)third_detail{
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    NSString * encryptUid = [authUserId AES256EncryptedStringForKey:key];
    
    NSString *encryptDetail = [third_detail AES256EncryptedStringForKey:key];
    //生成sign
    NSString *timeInterval = [NSString stringWithFormat:@"%10ld", (long)[[NSDate date] timeIntervalSince1970]];
    NSString * appendString = [NSMutableString stringWithFormat:@"%@%@%@",encryptUid,encryptDetail,timeInterval];
    //uid+当前时间戳 经过MD5，取前3位+第4位到第7位+最后3位作为sign
    NSString *MD5String = [appendString stringFromMD5];
    NSString *headString = [MD5String substringToIndex:3];
    NSString *middleString = [MD5String substringWithRange:NSMakeRange(4, 4)];
    NSString *tailString = [MD5String substringFromIndex:MD5String.length - 3];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@",headString,middleString,tailString];
    if (sign && timeInterval) {
        dic[@"ts"] = timeInterval;
        dic[@"sign"] = sign;
        dic[@"third_user_id"] = encryptUid;
        dic[@"third_detail"] = encryptDetail;
    }
    return dic;
}

@end
