//
//  GMToFaceDoctorListViewModel.m
//  Gengmei
//
//  Created by zhouLiang on 2020/2/20.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMToFaceDoctorListViewModel.h"

@interface GMToFaceDoctorListViewModel ()<WMFetchDataModelProtocol> {
    NSMutableDictionary *_deduplicationDic;
    NSString *_deduplicationKey;
}
@end

@implementation GMToFaceDoctorListViewModel
- (instancetype)init {
    if (self = [super init]) {
        _deduplicationKey = @"counsellorId";
        _deduplicationDic = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)excuteToFaceTabsDoctorsSuccessBlock:(HttpSuccessBlock)successBlock
                                  failBlock:(HttpFailedBlock)failBlock {
    [[GMInterfaceNetwork shareInstance] excuteToFaceTabsDoctorsTabsId:self.tabId page:self.page SuccessBlock:^(id response) {
        GMToFaceTabsDoctorListModel *model = [[GMToFaceTabsDoctorListModel alloc] initWithDictionary:response error:NULL];
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
            [_deduplicationDic removeAllObjects];
        }
        if (model.counsellors.count) {
            [self deduplicationForArray:model.counsellors buildModelBlock:NULL];
        }
        successBlock(self.dataArray);
    } failureBlock:^(NSInteger errorCode, NSString *message) {
        failBlock(message);
    }];
}
- (NSMutableArray<GMToFaceRecommendsDoctors *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray arrayWithCapacity:15];
    }
    return _dataArray;
}

- (void)deduplicationForArray:(NSArray *)array buildModelBlock:(id (^)(NSDictionary *))buildBlock {
    if (_deduplicationKey.length == 0) {
        return;
    }
    // NSMutableArray 不是线程安全的，不能使用并行枚举。参考https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        id value = [obj valueForKey:_deduplicationKey];
        NSString *key = [value isKindOfClass:[NSString class]] ? value : [value stringValue];
        NSAssert(key.length > 0, @"key 怎么会是一个空???!!!");
        if (!_deduplicationDic[key]) {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                id object = buildBlock(obj);
                [self.dataArray addObject:object];
            }else{
                [self.dataArray addObject:obj];
            }
            _deduplicationDic[key] = @1;
        }
    }];
}
@end
