//
//  PictureTableViewCell.m
//  patrol
//
//  Created by Javen on 2017/3/2.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "ZJPictureTableViewCell.h"
#import "ZJAddPictureCollectionCell.h"
#import "DBCameraLibraryViewController.h"
#import "DBCameraContainerViewController.h"
#import "ImageTool.h"

@interface ZJPictureTableViewCell ()

@end
@implementation ZJPictureTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.layOut.itemSize = kPicCellSize;
    self.layOut.minimumInteritemSpacing = 10;
    self.layOut.minimumLineSpacing = 10;
    self.layOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
}

- (void)configCellWithViewModel:(PicViewModel *)viewModel indexPath:(NSIndexPath *)indexPath target:(UIViewController *)target remarkString:(NSString *)remarkString photoType:(PHOTO_TYPE)photoType {
    self.vc = target;
    self.viewModel = viewModel;
    self.remarkString = remarkString;
    self.type = photoType;
    //如果是只读的，则直接刷新。
    if (self.viewModel.type == kPicCellTypeRead) {
        [self.collectionView reloadData];
        return;
    }
    //非只读情况，则是添加或者编辑
    if (self.viewModel.arrPics.count == self.viewModel.maxPictureNumber) {
        self.viewModel.type = kPicCellTypeEdit;
    } else {
        self.viewModel.type = kPicCellTypeAdd;
    }
    [self.collectionView reloadData];
}

#pragma mark - collectionView DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (self.viewModel.type) {
        case kPicCellTypeAdd: {
            return self.viewModel.arrPics.count + 1;
            break;
        }
        default: {
            return self.viewModel.arrPics.count;
            break;
        }
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZJAddPictureCollectionCell *cell = [collectionView
        dequeueReusableCellWithReuseIdentifier:@"ZJAddPictureCollectionCell"
                                  forIndexPath:indexPath];
    [cell configCellWithArr:self.viewModel.arrPics indexPath:indexPath viewModel:self.viewModel];
    //删除
    @weakify(self);
    cell.blockDelete = ^(NSInteger index) {
        @strongify(self);
        ShowAlertView(@"提示", @"确定删除照片吗?", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ZERO) {
                [self.viewModel.arrPics removeObjectAtIndex:index];
                self.blockReloadData();
            }
        });
    };
    return cell;
}

#pragma mark - collectionView DataSource
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    switch (self.viewModel.type) {
        case kPicCellTypeRead: {
            [self seePicsWithIndex:indexPath.item];
            break;
        }
        default: {
            if (indexPath.row == self.viewModel.arrPics.count) { //说明点击的是添加图片的那个按钮
                [self pushImagePickerController];
            } else { //点击查看大图
                [self seePicsWithIndex:indexPath.item];
            }
            break;
        }
    }
}
#pragma mark - UIImagePicker Controller Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    [self.vc dismissViewControllerAnimated:YES completion:nil];
    if (self.viewModel.arrPics.count + 1 > self.viewModel.maxPictureNumber) {
        [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"最多添加%.0f张照片",self.viewModel.maxPictureNumber]];
        return;
    }
    [IBTLoadingView showProgressLabel:@"图片处理中"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *newImage = [image rescaleImageToPX:1080];
        NSDictionary *fontDict = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
        UIImage *waterImage = [newImage imageWaterMarkWithString:self.remarkString point:CGPointMake(20, newImage.size.height - 20) attribute:fontDict];
        NSString *imageName = [self saveImageToLocal:waterImage];
        [self.viewModel.arrPics addObject:imageName];
        dispatch_async(dispatch_get_main_queue(), ^{
            [IBTLoadingView hideHUDWithText:nil];
            self.blockReloadData();
        });
    });
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.vc dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - TZImagePickerController
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [self.vc dismissViewControllerAnimated:YES completion:nil];
    if (self.viewModel.arrPics.count + 1 > self.viewModel.maxPictureNumber) {
        [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"最多添加%.0f张照片",self.viewModel.maxPictureNumber]];
        return;
    }
    [IBTLoadingView showProgressLabel:@"图片处理中"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int imageMaxCount = self.viewModel.maxPictureNumber - self.viewModel.arrPics.count;
        imageMaxCount = imageMaxCount > photos.count ? photos.count : imageMaxCount;
                for (int index = 0; index < imageMaxCount; index++){
                    UIImage *newImage = [photos[index] rescaleImageToPX:1080];
                    NSDictionary *fontDict = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
                    UIImage *waterImage = [newImage imageWaterMarkWithString:self.remarkString point:CGPointMake(20, newImage.size.height - 20) attribute:fontDict];
                    NSString *imageName = [self saveImageToLocal:waterImage];
                    [self.viewModel.arrPics addObject:imageName];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [IBTLoadingView hideHUDWithText:nil];
                    self.blockReloadData();
                });
            });
}
- (void)pushImagePickerController {
    switch (self.type) {
        case PHOTO_TYPE_ONLYPHOTO:
        {
            UIImagePickerController * imagePickerVc = [[UIImagePickerController alloc]init];
            imagePickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerVc.delegate = self;
            imagePickerVc.allowsEditing = NO;
            [self.vc presentViewController:imagePickerVc animated:YES completion:nil];
        }
            break;
        case PHOTO_TYPE_ONLYLBUM:
        {
            ShowAlertView(@"提示", @"此分类需要您提前拍摄好照片,拍摄之前请确保手机处于飞行模式下。您拍摄好了吗？", @[@"没有",@"拍照完成"], UIAlertControllerStyleAlert, ^(NSInteger index) {
                if (index == ZERO) {
                    return;
                }
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
                imagePickerVc.allowPickingOriginalPhoto = NO;
                imagePickerVc.allowTakeVideo = NO;
                imagePickerVc.allowPickingVideo = NO;
                imagePickerVc.allowPickingGif = NO;
                imagePickerVc.allowTakePicture = NO;
                imagePickerVc.maxImagesCount = self.viewModel.maxPictureNumber - self.viewModel.arrPics.count;
                imagePickerVc.showSelectedIndex = true;
                [IBTLoadingView showProgressLabel:@"加载中"];
                [self.vc presentViewController:imagePickerVc animated:YES completion:^{
                    [IBTLoadingView hideHUDWithText:nil];
                }];
            });
        }
            break;
        case PHOTO_TYPE_NO:
        case PHOTO_TYPE_ALL:
        {
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
            imagePickerVc.allowPickingOriginalPhoto = NO;
            imagePickerVc.allowTakeVideo = NO;
            imagePickerVc.allowPickingVideo = NO;
            imagePickerVc.allowPickingGif = NO;
            imagePickerVc.showSelectedIndex = true;
            imagePickerVc.maxImagesCount = self.viewModel.maxPictureNumber - self.viewModel.arrPics.count;
            [self.vc presentViewController:imagePickerVc animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark - DBCameraViewControllerDelegate
- (void) dismissCamera:(id)cameraViewController{
    [self.vc dismissViewControllerAnimated:YES completion:nil];
    [cameraViewController restoreFullScreenMode];
}

- (void)camera:(id)cameraViewController didFinishWithImage:(UIImage *)image withMetadata:(NSDictionary *)metadata
{
    [cameraViewController restoreFullScreenMode];
    [self.vc dismissViewControllerAnimated:YES completion:nil];
    if (self.viewModel.arrPics.count + 1 > self.viewModel.maxPictureNumber) {
        [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"最多添加%.0f张照片",self.viewModel.maxPictureNumber]];
        return;
    }
    UIImage *newImage = [image rescaleImageToPX:1080];
    NSDictionary *fontDict = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};
    UIImage *waterImage = [newImage imageWaterMarkWithString:self.remarkString point:CGPointMake(20, newImage.size.height - 20) attribute:fontDict];
    NSString *imageName = [self saveImageToLocal:waterImage];
    [self.viewModel.arrPics addObject:imageName];
    self.blockReloadData();
}

#pragma mark - DBCameraContainerDelegate
- (void) backFromController:(id)fromController
{
    [self.vc dismissViewControllerAnimated:YES completion:nil];
    [fromController restoreFullScreenMode];
}

- (void) switchFromController:(id)fromController toController:(id)controller
{
    
}
    
#pragma mark -保存到本地
- (NSString *)saveImageToLocal:(UIImage *)image
{
    //加密
    NSData *newimageData = UIImageJPEGRepresentation(image, 0.1);
    NSLog(@"%lu",(unsigned long)newimageData.length);
    NSString *imageName = [ToolsManager md5Data:newimageData];
    
    //获取沙盒目录
    NSString *fullPath = [kPathDocument stringByAppendingPathComponent:imageName];
    //将图片写入文件
    [newimageData writeToFile:fullPath atomically:NO];
    return imageName;
}

/**
 查看大图
 
 @param index 点击中的图片下标
 */
- (void)seePicsWithIndex:(NSInteger)index {
    NSMutableArray *imageArray = [NSMutableArray array];
    PYPhotoBrowseView *photoBroseView = [[PYPhotoBrowseView alloc] init];
    photoBroseView.currentIndex = ZERO;
    for (int i=0; i<self.viewModel.arrPics.count; i++) {
        ZJAddPictureCollectionCell *cell = (ZJAddPictureCollectionCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:ZERO]];
        [imageArray addObject:cell.imgPicture];
    }
    photoBroseView.currentIndex = index;
    photoBroseView.sourceImgageViews = imageArray;
    [photoBroseView show];
}



@end
