KWMShoppingCart.m 8.04 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
- (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$"]) {
68 69 70
        if(!self.sync) {
            return;
        }
u  
lee committed
71 72 73 74 75 76 77 78
    }
    [self.tasks addObject:object];
    if (self.tasks.count == 1) {
        [object resume];
    }
    
}

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

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

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

-(void)updateProductWithVariantIds:(NSArray<NSNumber *> *)variantIds quantitties:(NSArray<NSNumber *> *)quantites callback:(ShoppingCartCallBack)callback {
u  
lee committed
134 135
//    CGFloat version = [[NSDate date] timeIntervalSince1970];
//    _version = version;
136
    __weak typeof(self) this = self;
u  
lee committed
137 138 139
    id task = [[KWMAPIManager sharedManager] updateProductWithVariantIds:variantIds quantities:quantites success:^(NSURLSessionDataTask *task, KWMCartResult *result) {
        [this missionCompleted];
//        if (version == this.version) {
140
            [[KWMShoppingCart sharedInstance] setResult:result];
lee committed
141
        if(this.sync)callback(nil,result);
u  
lee committed
142
//        }
lee committed
143
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
u  
lee committed
144
        [this missionCompleted];
lee committed
145
//        callback(error,nil);
lee committed
146
    }];
u  
lee committed
147
    [self addTasksObject:task];
lee committed
148 149 150 151 152
    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
153
    }
lee committed
154 155 156
}

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

u  
lee committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
- (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
181 182 183 184
- (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
185 186 187
    NSUInteger size = items.count;
    for (int i=0;i < size; i++) {
        KWMShopCartModel *item = items[i];
lee committed
188 189 190 191
        if (item.identifier.integerValue == variantId.integerValue) {
            switch (flag) {
                case 0:
                    count -= item.quantity;
lee committed
192
                    [self.items removeObjectAtIndex:i];
lee committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
                    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
211 212
//        [items addObject:model];
        [items insertObject:model atIndex:0];
lee committed
213 214 215 216 217
    }
    self.result.item_count = @(count);
    return self.result;
}

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

- (id)copy {
    return self;
}

- (id)mutableCopy {
    return self;
}

@end