KWMShoppingCart.m 8 KB
Newer Older
lee committed
1 2 3 4 5 6 7 8 9 10 11
//
//  KWMShoppingCart.m
//  iCemarose
//
//  Created by lee on 2017/5/18.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMShoppingCart.h"
#import "KWMCartResult.h"
#import "KWMShopCartData.h"
u  
lee committed
12
#import <RegexKitLite/RegexKitLite.h>
u  
lee committed
13
#import <RXCollections/RXCollection.h>
lee committed
14 15 16 17

@interface KWMShoppingCart ()

@property (nonatomic, strong) KWMCartResult *result;
u  
lee committed
18 19
//@property (nonatomic, assign) CGFloat version;
@property (nonatomic, strong) NSMutableArray<NSURLSessionDataTask *> *tasks;
lee committed
20 21 22 23 24 25 26 27 28

@end

@implementation KWMShoppingCart

- (NSMutableArray<KWMShopCartModel *> *)items {
    return (NSMutableArray *)_result.items;
}

lee committed
29 30 31 32
- (NSNumber *)count {
    return _result.item_count;
}

lee committed
33 34 35 36 37
- (void)setResult:(KWMCartResult *)result {
    _result = result;
    [[KWMShopCartData alloc] syncCartProducts:result.items];
}

u  
lee committed
38 39 40 41
- (void)setResultNoSync:(KWMCartResult *)result {
    _result = result;
}

lee committed
42 43 44 45 46
+ (instancetype)sharedInstance {
    static KWMShoppingCart *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
u  
lee committed
47
        instance.tasks = [[NSMutableArray alloc] init];
lee committed
48
    });
lee committed
49
    if (!instance.result) {
u  
lee committed
50
        [instance setResultNoSync:[KWMCartResult new]];
lee committed
51 52 53 54 55 56 57
        instance.result.items = [[[KWMShopCartData alloc] getALLItems] mutableCopy];
        NSInteger count = 0;
        for (KWMShopCartModel *item in instance.items) {
            count += item.quantity;
        }
        instance.result.item_count = @(count);
    }
lee committed
58 59 60
    return instance;
}

u  
lee committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
- (void) missionCompleted {
    [self.tasks removeObjectAtIndex:0];
    [self.tasks.firstObject resume];
}

- (void) addTasksObject:(NSURLSessionDataTask *)object {
    if (self.tasks.lastObject && [self.tasks.lastObject.currentRequest.URL.absoluteString isEqualToString:object.currentRequest.URL.absoluteString] && [object.currentRequest.URL.absoluteString isMatchedByRegex:@"cart.js$"]) {
        return;
    }
    [self.tasks addObject:object];
    if (self.tasks.count == 1) {
        [object resume];
    }
    
}

lee committed
77
- (void)allItemsWithCallback:(ShoppingCartCallBack)callback {
u  
lee committed
78 79
//    CGFloat version = [[NSDate date] timeIntervalSince1970];
//    _version = version;
80
    __weak typeof(self) this = self;
u  
lee committed
81 82 83
    id task = [[KWMAPIManager sharedManager] getCartSuccess:^(NSURLSessionDataTask *task, KWMCartResult *result) {
        [this missionCompleted];
//        if (version == this.version) {
84 85
            [[KWMShoppingCart sharedInstance] setResult:result];
            callback(nil,result);
u  
lee committed
86
//        }
lee committed
87
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
u  
lee committed
88
        [this missionCompleted];
lee committed
89 90
        callback(error,nil);
    }];
u  
lee committed
91
    [self addTasksObject:task];
lee committed
92 93 94
}

- (void)increaseProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity callback:(ShoppingCartCallBack)callback {
u  
lee committed
95 96
//    CGFloat version = [[NSDate date] timeIntervalSince1970];
//    _version = version;
97
    __weak typeof(self) this = self;
u  
lee committed
98 99 100
    id task = [[KWMAPIManager sharedManager] addProductWithVariantId:variantId quantity:quantity success:^(NSURLSessionDataTask *task, KWMRequestResult *result) {
        [this missionCompleted];
//        if (version == this.version) {
101
            [[KWMShoppingCart sharedInstance] allItemsWithCallback:^(NSError *error, KWMCartResult *cart) {
lee committed
102
                if(this.sync)callback(error,cart);
103
            }];
u  
lee committed
104
//        }
lee committed
105
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
u  
lee committed
106
        [this missionCompleted];
lee committed
107
//        callback(error,nil);
lee committed
108
    }];
u  
lee committed
109
    [self addTasksObject:task];
lee committed
110
    if(!this.sync)callback(nil,[self changeLocalCartWithVariantId:variantId quantity:quantity flag:1]);
lee committed
111 112
}

lee committed
113
- (void)changeProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity callback:(ShoppingCartCallBack)callback {
u  
lee committed
114 115
//    CGFloat version = [[NSDate date] timeIntervalSince1970];
//    _version = version;
116
    __weak typeof(self) this = self;
u  
lee committed
117 118 119
    id task = [[KWMAPIManager sharedManager] changeProductWithVariantId:variantId quantity:quantity success:^(NSURLSessionDataTask *task, KWMCartResult *result) {
        [this missionCompleted];
//        if (version == this.version) {
120
            [[KWMShoppingCart sharedInstance] setResult:result];
lee committed
121
        if(this.sync)callback(nil,result);
u  
lee committed
122
//        }
lee committed
123
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
u  
lee committed
124
        [this missionCompleted];
lee committed
125 126
//        callback(error,nil);
    }];
u  
lee committed
127
    [self addTasksObject:task];
lee committed
128
    if(!this.sync)callback(nil,[self changeLocalCartWithVariantId:variantId quantity:quantity flag:quantity ? 2 : 0]);
lee committed
129 130 131
}

-(void)updateProductWithVariantIds:(NSArray<NSNumber *> *)variantIds quantitties:(NSArray<NSNumber *> *)quantites callback:(ShoppingCartCallBack)callback {
u  
lee committed
132 133
//    CGFloat version = [[NSDate date] timeIntervalSince1970];
//    _version = version;
134
    __weak typeof(self) this = self;
u  
lee committed
135 136 137
    id task = [[KWMAPIManager sharedManager] updateProductWithVariantIds:variantIds quantities:quantites success:^(NSURLSessionDataTask *task, KWMCartResult *result) {
        [this missionCompleted];
//        if (version == this.version) {
138
            [[KWMShoppingCart sharedInstance] setResult:result];
lee committed
139
        if(this.sync)callback(nil,result);
u  
lee committed
140
//        }
lee committed
141
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
u  
lee committed
142
        [this missionCompleted];
lee committed
143
//        callback(error,nil);
lee committed
144
    }];
u  
lee committed
145
    [self addTasksObject:task];
lee committed
146 147 148 149 150
    if(!this.sync) {
        for (int i=0; i<quantites.count && self.items.count; i++) {
            [self changeLocalCartWithVariantId:variantIds[i] quantity:quantites[i].integerValue flag:quantites[i].integerValue ? 2 : 0];
        }
        callback(nil,self.result);
lee committed
151
    }
lee committed
152 153 154
}

- (void)deleteProductWithVariantId:(NSNumber *)variantId callback:(ShoppingCartCallBack)callback {
lee committed
155
    [self changeProductWithVariantId:variantId quantity:0 callback:callback];
lee committed
156 157
}

u  
lee committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
- (void)clearCartWithCallback:(ShoppingCartCallBack)callback {
    NSMutableArray *quantity = [NSMutableArray new];
    NSArray *ids = [self.items rx_mapWithBlock:^id(KWMShopCartModel* each) {
        [quantity addObject:@(0)];
        return each.identifier;
    }];
    [self setResult:[KWMCartResult new]];
    __weak typeof(self) this = self;
    id task = [[KWMAPIManager sharedManager] updateProductWithVariantIds:ids quantities:quantity success:^(NSURLSessionDataTask *task, KWMCartResult *result) {
        [this missionCompleted];
        //        if (version == this.version) {
        [[KWMShoppingCart sharedInstance] setResult:result];
        callback(nil,result);
        //        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [this missionCompleted];
        callback(error,nil);
    }];
    [self addTasksObject:task];
}

lee committed
179 180 181 182
- (KWMCartResult *) changeLocalCartWithVariantId:(NSNumber *) variantId quantity:(NSInteger) quantity flag:(NSInteger) flag {
    NSMutableArray<KWMShopCartModel *> *items= self.items;
    NSInteger count = self.result.item_count.integerValue;
    BOOL processed = NO;
lee committed
183 184 185
    NSUInteger size = items.count;
    for (int i=0;i < size; i++) {
        KWMShopCartModel *item = items[i];
lee committed
186 187 188 189
        if (item.identifier.integerValue == variantId.integerValue) {
            switch (flag) {
                case 0:
                    count -= item.quantity;
lee committed
190
                    [self.items removeObjectAtIndex:i];
lee committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
                    break;
                case 1:
                    count += quantity;
                    item.quantity += quantity;
                    break;
                default:
                    count -= item.quantity - quantity;
                    item.quantity = quantity;
            }
            processed = YES;
            break;
        }
    }
    if (!processed) {
        KWMShopCartModel *model = [[KWMShopCartModel alloc] init];
        model.identifier = variantId.stringValue;
        model.quantity = quantity;
        count += quantity;
lee committed
209 210
//        [items addObject:model];
        [items insertObject:model atIndex:0];
lee committed
211 212 213 214 215
    }
    self.result.item_count = @(count);
    return self.result;
}

lee committed
216 217 218 219 220 221 222 223 224 225 226 227 228
+ (id)allocWithZone:(struct _NSZone *)zone {
    return [KWMShoppingCart sharedInstance];
}

- (id)copy {
    return self;
}

- (id)mutableCopy {
    return self;
}

@end