//
//  ZJAppInstance.m
//  HDMall
//
//  Created by Javen on 2017/7/27.
//  Copyright © 2017年 上海勾芒信息科技. All rights reserved.
//

#import "ZJAppInstance.h"
static NSString *const zj_saved_name = @"zj_saved_name";
static NSString *const zj_saved_pwd = @"zj_saved_pwd";
static NSString *const zj_saved_isMall = @"zj_saved_isMall";

@implementation ZJAppInstance
+ (ZJAppInstance *)shareInstance {
    static ZJAppInstance *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [ZJAppInstance new];
        NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
        instance.savedName = [d objectForKey:zj_saved_name];
        instance.savedPWD = [d objectForKey:zj_saved_pwd];
        instance.isMall = [d boolForKey:zj_saved_isMall];
    });
    return instance;
}

- (void)saveBaseInfo {
    NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
    [d setObject:self.savedName forKey:zj_saved_name];
    [d setObject:self.savedPWD forKey:zj_saved_pwd];
    [d setBool:self.isMall forKey:zj_saved_isMall];
    [d synchronize];
}

- (void)setUser:(UserInfo *)user {
    _user = user;
    [self.permission updatePermissions:user.permissions];
}

- (NSMutableArray *)getUserContractUuids {
    NSMutableArray *arr = [NSMutableArray array];
    for (UserInfo_contracts *contract in self.user.contracts) {
        [arr addObject:contract.uuid];
    }
    return arr;
}

/** 获取商户用户的合同（默认是第一个） */
- (UserInfo_contracts *)getTenantContract{
    if (self.isMall) {
        [MBProgressHUD j_warningMessage:@"该用户是商场用户"];
        return nil;
    }
    
    UserInfo_contracts *contract = [self.user.contracts firstObject];
    if (!contract) {
        [MBProgressHUD j_warningMessage:@"该商户没有合同"];;
    }else if(self.user.contracts.count > 1){
        [MBProgressHUD j_warningMessage:@"该商户有多个合同，默认选取第一个"];
    }
    
    return contract;
}

- (void)loginOut {
    [self saveInfoWithUserName:nil pwd:nil];
}

/**
 *  保存登录信息以及用户名密码
 *
 *  @param name 用户名
 *  @param pwd  密码
 *
 *  @return 是否成功
 */
- (void)saveInfoWithUserName:(NSString *)name pwd:(NSString *)pwd {
    self.savedName = name;
    self.savedPWD = pwd;
    [self saveBaseInfo];
}

ZJLazy(ZJPermissionManager, permission)
@end
