//
//  RepairAddPicCollectionViewCell.m
//  patrol
//
//  Created by Javen on 2016/10/23.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ZJAddPictureCollectionCell.h"

@implementation ZJAddPictureCollectionCell
- (void)awakeFromNib {
    [super awakeFromNib];
    self.longPress = [[UILongPressGestureRecognizer alloc]
        initWithTarget:self
                action:@selector(actionDelete:)];
    [self addGestureRecognizer:self.longPress];
    self.img.image = TCImage(@"addimage");
}

- (void)configCellWithArr:(NSMutableArray *)array indexPath:(NSIndexPath *)indexPath viewModel:(PicViewModel *)viewModel {
    
    if (viewModel.type == kPicCellTypeRead) {
        [self removeGestureRecognizer:self.longPress];
    }
    if (indexPath.row == array.count) { //说明是添加按钮
        self.img.hidden = NO;
        self.imgPicture.hidden = YES;
        self.index = 999;
    } else {
        self.img.hidden = YES;
        self.imgPicture.hidden = NO;

        id imageUrl = [array yx_objectAtIndex:indexPath.row];
        if ([imageUrl isKindOfClass:[NSString class]]) {
            if ([imageUrl hasPrefix:@"http://"]) {
                [self.imgPicture sd_setImageWithURL:[NSURL URLWithString:imageUrl]
                                   placeholderImage:KNODATAIMAGE completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                       if (image) {
                                           //加密
                                           NSData *newimageData = UIImageJPEGRepresentation(image, 1);
                                           NSString *imageName = [ToolsManager md5Data:newimageData];
                                           //获取沙盒目录
                                           NSString *fullPath = [kPathDocument stringByAppendingPathComponent:imageName];
                                           //将图片写入文件
                                           [newimageData writeToFile:fullPath atomically:NO];
                                           [array replaceObjectAtIndex:indexPath.row withObject:imageName];
                                       }
                                   }];

            } else {
                self.imgPicture.image = [UIImage imageWithContentsOfFile:[kPathDocument stringByAppendingPathComponent:[array yx_objectAtIndex:indexPath.item]]];
                ;
            }
        } else if ([imageUrl isKindOfClass:[UIImage class]]) {
            self.imgPicture.image = imageUrl;
        }
        self.index = indexPath.row;
    }
}

- (void)actionDelete:(UILongPressGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        self.blockDelete(self.index);
    }
}
@end
