//
//  InspectNotUploadViewController.m
//  redstar
//
//  Created by admin on 15/11/24.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "InspectNotUploadViewController.h"
#import "InspectNotUpLoadCell.h"
#import "CheckPicViewController.h"
#import "InspectDetailFooterView.h"
#import <MBProgressHUD.h>
#import "CommonFunc.h"
#import "HttpClient.h"
#define kInspectNotUploadCell @"InspectNotUploadCell"

@interface InspectNotUploadViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate , TakePhotoViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) InspectDetailFooterView *footerView;
@property (nonatomic, strong) NSMutableArray *imageNameArray;


@end

@implementation InspectNotUploadViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"11111self.tableView.frame = %@, self.contentSize =  %@, self.contentOff = %@", NSStringFromCGRect(self.tableView.frame),NSStringFromCGSize(self.tableView.contentSize), NSStringFromCGPoint(self.tableView.contentOffset));

    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    customLab.textAlignment = NSTextAlignmentCenter;
    [customLab setText:[NSString stringWithFormat:@"检查点--%@(%@/%d)", self.taskModel.category, self.taskModel.lineNo, self.questionCount]];
    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 registerClass:[InspectNotUpLoadCell class] forCellReuseIdentifier:kInspectNotUploadCell];
    self.tableView.tableFooterView = self.footerView;
    self.footerView.takePhotoView.delegate = self;
    [self.footerView.reportBtn addTarget:self action:@selector(uploadTaskInfo:) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageNameArray = [NSMutableArray array];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - private Methods

- (void)uploadTaskInfo:(UIButton *)sender
{
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 0; i < _imageNameArray.count; i++) {
        NSString *imageName = _imageNameArray[i];
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
        UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        NSString *imageBase64 = [imageData base64EncodedStringWithOptions:0];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:imageBase64 forKey:@"fileContent"];
        [dict setObject:imageName forKey:@"fileName"];
        [dict setObject:@(i) forKey:@"index"];
        [imageArray addObject:dict];
    }

    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd+hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    NSString *operId = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_code"];
    NSString *operName = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_name"];
    NSLog(@"self = %@, 1= %@, 2 = %@", self.praiseUuid, self.store_uuid, self.questionUuid);
    
    NSString *url = [NSString stringWithFormat:@"%@%@%@?time=%@&operId=%@&operName=%@",kRedStarURL, kUpLoadInspectResult, self.praiseUuid, dateString, operId, operName];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"上传检查点url = %@", url);
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *parameters = @{@"questionUuid":self.questionUuid,
                                 @"storeUuid":self.store_uuid,
                                 @"remark":self.footerView.contentTextView.text,
                                 @"attachments":imageArray
                                 };
    NSLog(@"上传检查点parameters = %@", parameters);
    [httpClient uploadInspectResultWithParameters:parameters completion:^(id response, NSError *error) {
        
        NSLog(@"ressssss  =%@  errorrrrr = %@", response, error);
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];
}

// 返回上一页面
- (void)doBack:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - TakePhoto Delegate
- (void)deletePhoto:(UIButton *)button
{
    NSLog(@"button -.tag  === %ld", (long)button.superview.tag);
    // 从存放所有Image的数组里移除当前点击的Image
    [self.footerView.takePhotoView.allImages removeObject:[(UIButton *)button.superview imageForState:UIControlStateNormal]];
    // 移除显示Image的Button
    [button.superview removeFromSuperview];
    
    CGFloat btnH = 110;
    CGFloat marginY = 10;
    int count = (int)self.footerView.takePhotoView.allImages.count + 1;
    int k ;
    if (count % 2 == 0) {
        k = count / 2;
    } else {
        k = (count + 1) / 2;
    }
    self.footerView.takePhotoView.frame = CGRectMake(0, 40, kScreenWidth, k * btnH + (k + 1) * marginY);
    self.footerView.height = self.footerView.takePhotoView.frame.size.height + 220;
    
    
    NSString *imageName = _imageNameArray[button.superview.tag - 1];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:fullPath];
    if (!blHave) {
        return ;
    } else {
        BOOL blDele= [fileManager removeItemAtPath:fullPath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
    }
    
}

- (void)createImagePicker
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to find the camera" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", 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)takePhotoShowPicture:(UIButton *)btn
{
    CheckPicViewController *checkVC = [[CheckPicViewController alloc] init];
    checkVC.checkImage = btn.imageView.image;
    [self.navigationController pushViewController:checkVC animated:YES];
}

#pragma mark - 保存图片至沙盒
- (void)saveImage:(UIImage *)currentImage {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    NSString *imageName = [CommonFunc md5Data:imageData];
    [_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];
    // 创建一个新的控件
    UIButton *newButton = [self.footerView.takePhotoView createButtonWithImage:image];
    [newButton addTarget:self action:@selector(takePhotoShowPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.footerView.takePhotoView insertSubview:newButton atIndex:self.footerView.takePhotoView.subviews.count - 1];
    [self.footerView.takePhotoView.allImages addObject:image];
    
    int count = (int)self.footerView.takePhotoView.allImages.count + 1;
    int k ;
    if (count % 2 == 0) {
        k = count / 2;
    } else {
        k = (count + 1) / 2;
    }
    
    CGFloat btnH = 110;
    CGFloat marginY = 10;
    self.footerView.takePhotoView.frame = CGRectMake(0, 40, kScreenWidth, k * btnH + (k + 1) * marginY);
    self.footerView.height = self.footerView.takePhotoView.frame.size.height + 220;
    // 退出图片选择控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
    NSLog(@"222222self.tableView.frame = %@, self.contentSize =  %@, self.contentOff = %@", NSStringFromCGRect(self.tableView.frame),NSStringFromCGSize(self.tableView.contentSize), NSStringFromCGPoint(self.tableView.contentOffset));

}



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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    InspectNotUpLoadCell *cell=[tableView dequeueReusableCellWithIdentifier:kInspectNotUploadCell];
    if (!cell) {
        cell = [[InspectNotUpLoadCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kInspectNotUploadCell];
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%@", _taskModel.title];
    cell.titleDetailLabel.text = [NSString stringWithFormat:@"要求图片%d张", _taskModel.attachmentNumber];
    cell.introLabel.text = @"参考说明";
    cell.introDetailLabel.text = [NSString stringWithFormat:@"%@", _taskModel.reference];
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


// section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}


#pragma mark - lazy loading
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 300.0;
        [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;
}

- (InspectDetailFooterView *)footerView
{
    if (!_footerView) {
        _footerView = [[InspectDetailFooterView alloc] init];
    }
    return _footerView;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
