//
//  AddPictureViewController.m
//  redstar
//
//  Created by admin on 15/12/7.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "AddPictureViewController.h"
#import "AddPictureTableCell.h"
#import "InspectPicAddCell.h"
#import "InspectAddCell.h"
#import "InpectPictureCell.h"

#define kAddPicTableViewCell @"addPicTableCell"
#define kAddAndPicCell @"inspectPictureAndAddCell"
#define kAddTableViewCell @"inspectAddCell"
#define kPicTableViewCell @"inspectPictureCell"

@interface AddPictureViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *imageNameArray;

@property (nonatomic, assign) int rowNumber;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIButton *reportButton;

@end

@implementation AddPictureViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"新增口碑"];
    customLab.font = [UIFont boldSystemFontOfSize:19];
    self.navigationItem.titleView = customLab;
    
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    
    [backBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = self.footView;
    
    [self.reportButton addTarget:self action:@selector(uploadInspect:) forControlEvents:UIControlEventTouchUpInside];

    _rowNumber = 2;

}

#pragma mark - Private Mothods
- (void)uploadInspect:(UIButton *)sender
{
    
}

- (void)doBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createImagePicker:(UIButton *)sender
{
    if (sender.tag == 2201) {
        _rowNumber++;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"找不到相机" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    } else {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        [self presentViewController:picker animated:YES completion:nil];
    }
}



- (void)saveImage:(UIImage *)currentImage {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    NSString *imageName = [NSString stringWithFormat:@"imageName%d", (int)_imageNameArray.count];
    [_imageNameArray addObject:imageName];
    
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image];
    
    // 退出图片选择控制器
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.tableView reloadData];
    }];
    
}

#pragma mark - UITableView Delegate/DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _rowNumber;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        AddPictureTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kAddPicTableViewCell];
        if (!cell) {
            cell = [[AddPictureTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAddPicTableViewCell];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if (indexPath.row == _rowNumber - 1) {
        if ((_imageNameArray.count + 1) % 2 == 0) {
            InspectPicAddCell *cell=[tableView dequeueReusableCellWithIdentifier:kAddAndPicCell];
            if (!cell) {
                cell = [[InspectPicAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAddAndPicCell];
            }
            NSString *imageName = _imageNameArray[_imageNameArray.count - 1];
            NSLog(@"imageName = %@", imageName);
            NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
            UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
            //UIImage *image00 = [self cutImage:image];
            [cell.photoButton1 setImage:image forState:UIControlStateNormal];
            
            cell.photoButton2.tag = 2201;
            [cell.photoButton2 addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            
            InspectAddCell *cell=[tableView dequeueReusableCellWithIdentifier:kAddTableViewCell];
            if (!cell) {
                cell = [[InspectAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAddTableViewCell];
            }
            cell.photoButton.tag = 2200;
            [cell.photoButton addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
        
    } else {
        
        InpectPictureCell *cell=[tableView dequeueReusableCellWithIdentifier:kPicTableViewCell];
        if (!cell) {
            cell = [[InpectPictureCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kPicTableViewCell];
        }
        NSString *imageName0 = _imageNameArray[(indexPath.row - 3) * 2];
        NSString *fullPath0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName0];
        UIImage *image0 = [UIImage imageWithContentsOfFile:fullPath0];
        UIImage *image00 = [self image:image0 scaledToSize:CGSizeMake((kScreenWidth - 3 * 20) / 2, 90)];
        [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
        
        NSString *imageName1 = _imageNameArray[(indexPath.row - 3) * 2 + 1];
        NSLog(@"imageName = %@", imageName1);
        NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName1];
        UIImage *image1 = [UIImage imageWithContentsOfFile:fullPath1];
        UIImage *image11 = [self image:image1 scaledToSize:CGSizeMake((kScreenWidth - 3 * 20) / 2, 90)];

        [cell.photoButton2 setImage:image11 forState:UIControlStateNormal];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

- (UIImage *)image:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

////裁剪图片
//- (UIImage *)cutImage:(UIImage*)image
//{
//    //压缩图片
//    CGSize newSize;
//    CGImageRef imageRef = nil;
//    
//    if ((image.size.width / image.size.height) < (((kScreenWidth - 20 * 3) / 2) / 90)) {
//        newSize.width = image.size.width;
//        newSize.height = image.size.width * 90 / ((kScreenWidth - 20 * 3) / 2);
//        
//        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
//        
//    } else {
//        newSize.height = image.size.height;
//        newSize.width = image.size.height * ((kScreenWidth - 20 * 3) / 2) / 90;
//        
//        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
//        
//    }
//    
//    return [UIImage imageWithCGImage:imageRef];
//}


#pragma mark - lazy loading
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100.0;
        [_tableView registerClass:[AddPictureTableCell class] forCellReuseIdentifier:kAddPicTableViewCell];
        [_tableView registerClass:[InspectAddCell class] forCellReuseIdentifier:kAddTableViewCell];
        [_tableView registerClass:[InpectPictureCell class] forCellReuseIdentifier:kPicTableViewCell];
        [_tableView registerClass:[InspectPicAddCell class] forCellReuseIdentifier:kAddAndPicCell];
        [self.view addSubview:_tableView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableBottom = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableBottom];
    }
    return _tableView;
}

- (UIView *)footView
{
    if (!_footView) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    }
    return _footView;
}

- (UIButton *)reportButton
{
    if (!_reportButton) {
        _reportButton = [[UIButton alloc] init];
        _reportButton.translatesAutoresizingMaskIntoConstraints = NO;
        _reportButton.backgroundColor = kNavigationBarColor;
        [_reportButton setTitle:@"上报口碑" forState:UIControlStateNormal];
        [self.footView addSubview:_reportButton];
        
        NSLayoutConstraint *reportTop = [NSLayoutConstraint constraintWithItem:_reportButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.footView attribute:NSLayoutAttributeTop multiplier:1.0 constant:10];
        [self.footView addConstraint:reportTop];
        
        NSLayoutConstraint *reportLeft = [NSLayoutConstraint constraintWithItem:_reportButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.footView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
        [self.footView addConstraint:reportLeft];
        
        NSLayoutConstraint *reportWidth = [NSLayoutConstraint constraintWithItem:_reportButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:kScreenWidth - 40];
        [self.footView addConstraint:reportWidth];
        
        NSLayoutConstraint *tableHeight = [NSLayoutConstraint constraintWithItem:_reportButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40];
        [self.footView addConstraint:tableHeight];
    }
    return _reportButton;
}


@end
