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

#import "CheckPicViewController.h"

#import "InspectTaskViewController.h"
#import "LargePictureViewController.h"

#import "InspectAddCell.h"
#import "InspectPicAddCell.h"
#import "InpectPictureCell.h"
#import "UIImage+Fit.h"

#define kPhotoTag 2221113

#define kInspectNotUploadCell @"InspectNotUploadCell"

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

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) InspectDetailFooterView *footerView;
@property (nonatomic, strong) NSMutableArray *imageNameArray;
@property (nonatomic, strong) NSLayoutConstraint *tableBottom;
@property (nonatomic, strong) NSLayoutConstraint *tableTop;
@property (nonatomic, assign) NSInteger rowNumber;
@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation InspectNotUploadViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    customLab.textAlignment = NSTextAlignmentCenter;
    [customLab setText:[NSString stringWithFormat:@"检查点--%@(%d/%d)", self.catesgory, self.reportCount, 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.reportBtn addTarget:self action:@selector(uploadTaskInfo:) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageNameArray = [NSMutableArray array];
    _rowNumber = 2;
    self.view.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:239 / 255.0];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
    
    
    
    if ([fileManager fileExistsAtPath:path]) {
        NSDirectoryEnumerator *myDirectoryEnumerator = [fileManager enumeratorAtPath:path];
        while((path = [myDirectoryEnumerator nextObject])!=nil) {
            
            if (![_imageNameArray containsObject:path]) {
                [_imageNameArray addObject:path];
            }
            
        }
        if (_imageNameArray.count % 2 == 1) {
            _rowNumber = _rowNumber + (_imageNameArray.count + 1) / 2 - 1;
        } else {
            _rowNumber = _rowNumber + _imageNameArray.count / 2 ;
        }
        [self.tableView reloadData];
    }

}


#pragma mark - private Methods

- (void)uploadTaskInfo:(UIButton *)sender
{
    int impose = _taskModel.attachmentNumber;
    if ((int)_imageNameArray.count < impose) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"要求图片%d张才能上传!", impose] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    
    if (self.footerView.contentTextView.text.length ==0 && _imageNameArray.count == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"现场照片和处理说明不能都为空!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"你确定要上传检查点的相关信息吗?"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 533292;
    [alert show];
}

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

- (void)showPicture:(UIButton *)sender
{
    LargePictureViewController *largeVC = [[LargePictureViewController alloc] init];
    largeVC.index = sender.tag - kPhotoTag;
    largeVC.allImageArray = _imageNameArray;
    largeVC.pictureSaveMode = PictureSpecialMode;
    largeVC.uuid = [NSString stringWithFormat:@"%@", _taskModel.uuid];
    [self removeDeleteButton];
    [self.navigationController pushViewController:largeVC animated:YES];
    
    
//    CheckPicViewController *checkVC = [[CheckPicViewController alloc] init];
//    NSString *imageName = _imageNameArray[sender.tag - kPhotoTag];
//    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
//    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
//    checkVC.checkImage = image;
//    [self.navigationController pushViewController:checkVC animated:YES];
}


- (void)createImagePicker:(UIButton *)sender
{
    
    if (_imageNameArray.count > 9) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"最多上传10张图片!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (sender.tag == 2201) {
        _rowNumber++;
    }
    [self removeDeleteButton];
    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];
    }

}





#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 - 保存图片至沙盒
- (void)saveImage:(UIImage *)currentImage {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.01);
    
    
    NSString *imageName = [CommonFunc md5Data:imageData];
    [_imageNameArray addObject:imageName];
    
    // 获取沙盒目录
   // NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
    NSString *imagePath = [path stringByAppendingPathComponent:imageName];
    BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    if (bo) {
        // 将图片写入文件
        [imageData writeToFile:imagePath atomically:NO];
        imageData = nil;
    } else {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:path error:nil];
    }
    

    
}

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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        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];
        cell.pictureLabel.text = @"现场照片";
        
        NSString *refrer = [NSString stringWithFormat:@"%@", _taskModel.reference];
        if (refrer == nil || refrer == NULL || [refrer isEqual:[NSNull null]] || refrer == Nil || [refrer isEqualToString:@"(null)"]) {
            cell.introDetailLabel.text = @"";
        } else {
            NSString *str = [NSString stringWithFormat:@"<style> html{ font-size: 15px; color: #444444 } </style>%@", _taskModel.reference];
            NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType ,NSForegroundColorAttributeName:kLightBlack,NSFontAttributeName:[UIFont systemFontOfSize:15.0f]} documentAttributes:nil error:nil];
            
            cell.introDetailLabel.attributedText = attrStr;
        }
        return cell;
    } else if (indexPath.row == _rowNumber - 1) {
        NSLog(@"index.row === %ld", indexPath.row);
        if ((_imageNameArray.count + 1) % 2 == 0) {
            NSString *identifier = [NSString stringWithFormat:@"InspectaddPicCell"];
            InspectPicAddCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[InspectPicAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            NSString *imageName = _imageNameArray[_imageNameArray.count - 1];
            //NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
            
            NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
            NSString *fullPath = [path stringByAppendingPathComponent:imageName];
            
            UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
            UIImage *image00 = [UIImage image:image fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];

            [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
            [cell.photoButton1 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];
            cell.photoButton1.tag = kPhotoTag + _imageNameArray.count - 1;

            
            cell.photoButton2.tag = 2201;
            [cell.photoButton2 addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            
            UILongPressGestureRecognizer *longGR1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
            [cell.photoButton1 addGestureRecognizer:longGR1];
            
            return cell;
        } else {
            
            NSString *identifier = [NSString stringWithFormat:@"InspectaddCell"];
            InspectAddCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[InspectAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            cell.photoButton.tag = 2200;
            [cell.photoButton addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
        
        
    } else {
        
        NSString *identifier = [NSString stringWithFormat:@"InspectPictureCell"];
        InpectPictureCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[InpectPictureCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        NSString *imageName0 = _imageNameArray[(indexPath.row - 1) * 2];
       // NSString *fullPath0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName0];
        NSLog(@"qqqqw==== %ld", (indexPath.row - 1) * 2 );
        NSString *path0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
        NSString *fullPath0 = [path0 stringByAppendingPathComponent:imageName0];
        UIImage *image0 = [UIImage imageWithContentsOfFile:fullPath0];
        
        UIImage *image00 = [UIImage image:image0 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
        [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
        NSLog(@"qqqq==== %ld", (indexPath.row - 1) * 2 + 1);
        NSString *imageName1 = _imageNameArray[(indexPath.row - 1) * 2 + 1];
       // NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName1];
        
        
        NSString *path1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
        NSString *fullPath1 = [path1 stringByAppendingPathComponent:imageName1];
        
        
        UIImage *image1 = [UIImage imageWithContentsOfFile:fullPath1];
        UIImage *image11 = [UIImage image:image1 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];

        [cell.photoButton2 setImage:image11 forState:UIControlStateNormal];
        
        [cell.photoButton1 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];
        cell.photoButton1.tag = kPhotoTag + (indexPath.row - 1) * 2;

        [cell.photoButton2 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];
        cell.photoButton2.tag = kPhotoTag + (indexPath.row - 1) * 2 + 1;

        // 添加长按手势
        UILongPressGestureRecognizer *longGR1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
        [cell.photoButton1 addGestureRecognizer:longGR1];
        
        UILongPressGestureRecognizer *longGR2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
        [cell.photoButton2 addGestureRecognizer:longGR2];
        
        return cell;
    }
}

- (void)longClick:(UIGestureRecognizer *)longGR {
    
    // 获取到点击的显示图片的按钮
    UIButton *showButton = (UIButton *)longGR.view;
    NSLog(@"我长按了第%ld张图片", (showButton.tag - kPhotoTag));
    
    if (_deleteButton) {
        [_deleteButton removeFromSuperview];
        _deleteButton = nil;
    }
    
    if (!_deleteButton) {
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteButton.tag = 5521 + (showButton.tag - kPhotoTag);
        [deleteButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        deleteButton.backgroundColor = [UIColor whiteColor];
        deleteButton.bounds = CGRectMake(0, 0, 20, 20);
        [deleteButton addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
        deleteButton.frame = CGRectMake(showButton.frame.size.width - deleteButton.frame.size.width, 0, deleteButton.frame.size.width, deleteButton.frame.size.height);
        [showButton addSubview:deleteButton];
        _deleteButton = deleteButton;
    }
}

// 删除图片
- (void)deletePicture:(UIButton *)button
{
    NSString *imageName = [self.imageNameArray objectAtIndex:(button.tag - 5521)];
    NSString *path0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
    NSString *paths = [path0 stringByAppendingPathComponent:imageName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:paths]) {
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:paths error:&error];
    }
    
    
    // 从存放所有Image的数组里移除当前点击的Image
    [self.imageNameArray removeObjectAtIndex:(button.tag - 5521)];
    
    if ((_imageNameArray.count + 1) % 2 == 0) {
        _rowNumber--;
        [self.tableView reloadData];
    } else {
        [self.tableView reloadData];
    }
    [button removeFromSuperview];
    button = nil;
    [self removeDeleteButton];
    
    
    
    
}

- (void)removeDeleteButton {
    if (_deleteButton) {
        [_deleteButton removeFromSuperview];
        _deleteButton = nil;
    }
}

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

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

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 39429234) {
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];
            NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
            [notification postNotificationName:kRefreshInspectPointNotification object:self];
        }
    } else if (alertView.tag == 533292) {
        if (buttonIndex == 0) {
            return;
        } else {
            NSMutableArray *imageArray = [NSMutableArray array];
            for (int i = 0; i < _imageNameArray.count; i++) {
                NSString *imageName = _imageNameArray[i];
                //NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
                
                NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
                NSString *fullPath = [path stringByAppendingPathComponent:imageName];
                
                UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.01);
                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"];
            
            NSString *url = [NSString stringWithFormat:@"%@%@%@?time=%@&operId=%@&operName=%@",kRedStarURL, kUpLoadInspectResult, self.praiseUuid, dateString, operId, operName];
            url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            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
                                         };
            [httpClient uploadInspectResultWithParameters:parameters completion:^(id response, NSError *error) {
                
                if ([response[@"success"] boolValue]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"检查点上报成功!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    alert.delegate = self;
                    alert.tag = 39429234;
                    [alert show];
                    
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",_taskModel.uuid]];
                        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
                        for (NSString *p in files) {
                            NSError *error;
                            NSString *paths = [path stringByAppendingPathComponent:p];
                            if ([[NSFileManager defaultManager] fileExistsAtPath:paths]) {
                                [[NSFileManager defaultManager] removeItemAtPath:paths error:&error];
                            }
                        }
                    });
                    
                }
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
            }];
        }
    }
}



#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;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        
        self.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];
        
        self.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] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        _footerView.contentTextView.delegate = self;
        _footerView.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:239 / 255.0];

    }
    return _footerView;
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![_footerView.contentTextView isExclusiveTouch]) {
        [self.footerView.contentTextView resignFirstResponder];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.tableTop.constant = -216;
    self.tableBottom.constant = -216;
    [UIView animateWithDuration:0.3 animations:^{
        [self.tableView layoutIfNeeded];
    }];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.tableTop.constant = 0;
    self.tableBottom.constant = 0;
    [UIView animateWithDuration:0.3 animations:^{
        [self.tableView layoutIfNeeded];
    }];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (![text isEqualToString:@""]) {
        self.footerView.placeholderLabel2.hidden = YES;
    }
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        self.footerView.placeholderLabel2.hidden = NO;
    }
    
    if ([text isEqualToString:@"\n"]) {
        [self.footerView.contentTextView resignFirstResponder];
        return NO;
    }
    
    if (range.location>=200) {
        return  NO;
    }
    else {
        return YES;
    }
    
    return 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