//
//  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"


@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 - TZImagePickerController
- (void)pushImagePickerController {
    switch (self.type) {
        case PHOTO_TYPE_NO:
            ShowDefaultErrorView(@"此分类不用拍照", nil);
            break;
        case PHOTO_TYPE_ONLYPHOTO:
        {
            DBCameraViewController *cameraVc = [DBCameraViewController initWithDelegate:self];
            [cameraVc setUseCameraSegue:NO];
            [self.vc presentViewController:cameraVc animated:YES completion:nil];
        }
            break;
        case PHOTO_TYPE_ONLYLBUM:
        {
            ShowAlertView(@"提示", @"此分类需要您提前拍摄好照片,拍摄之前请确保手机处于飞行模式下。您拍摄好了吗？", @[@"没有",@"拍照完成"], UIAlertControllerStyleAlert, ^(NSInteger index) {
                if (index == ZERO) {
                    return;
                }
                DBCameraLibraryViewController *vc = [[DBCameraLibraryViewController alloc] init];
                [vc setDelegate:self];
                [IBTLoadingView showProgressLabel:@"加载中"];
                [self.vc presentViewController:vc animated:YES completion:^{
                    [IBTLoadingView hideHUDWithText:nil];
                }];
            });
        }
            break;
        case PHOTO_TYPE_ALL:
        {
            DBCameraViewController *cameraController = [DBCameraViewController initWithDelegate:self];
            [cameraController setUseCameraSegue:NO];
            DBCameraContainerViewController *container = [[DBCameraContainerViewController alloc] initWithDelegate:self];
            [container setCameraViewController:cameraController];
            [container setFullScreenMode];
            [self.vc presentViewController:container 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 rescaleImageToSize:CGSizeMake(ScreenSize.width, ScreenSize.width * 4 / 3)];
    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.5);
    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
