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

#import "LookOnLineDetailViewController.h"
#import "LookOnLineFootView.h"
#import "HttpClient.h"
#import "CommonFunc.h"
#import "OnLineDetailModel.h"
#import "UIImage+Fit.h"

#import "InspectAddCell.h"
#define kOnLineInspectAddCell @"onLineInspectAddCell"
#import "InspectPicAddCell.h"
#define kOnLineInspectPicAddCell @"onLineInspectPicAddCell"
#import "InpectPictureCell.h"
#define kOnLineInpectPictureCell @"onLineInpectPictureCell"
#import "LargePictureViewController.h"

#import "LookOnLineDetailCell.h"
#define kLookOnLineDetailCell @"LookOnLineDetailCell"

@interface LookOnLineDetailViewController () <UIAlertViewDelegate,UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) LookOnLineFootView *footView;
@property (nonatomic, strong) UIActionSheet *selectActionSheet;

@property (nonatomic, strong) NSMutableArray *imageNameArray;
@property (nonatomic, assign) int rowNumber;
@property (nonatomic, strong) NSLayoutConstraint *tableBottom;
@property (nonatomic, strong) NSLayoutConstraint *tableTop;

@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation LookOnLineDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNav];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.imageNameArray = [NSMutableArray array];
    
    _rowNumber = 1;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - Private Mothods
- (void)setNav
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    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;
    
    
    
    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;
}


- (void)reportRestult:(UIButton *)sender
{

    if (self.footView.contentTextView.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"处理说明不能为空！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    } else {
        // 提示框
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要上报当前任务处理结果吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 314331;
        alert.delegate = self;
        [alert show];
    }
}

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

//- (void)createImagePicker:(UIButton *)sender
//{
//    if (sender.tag == 22011) {
//        _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)createImagePicker:(UIButton *)sender
{
    self.selectActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"直接拍照上传", @"从本地相册选择", nil];
    _selectActionSheet.delegate = self;
    _selectActionSheet.tag = 999283;
    [_selectActionSheet showInView:self.view];
    
    
    if (sender.tag == 22011) {
        _rowNumber++;
    }
}



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

- (void)showLookOnLinePic:(UIButton *)sender
{
    LargePictureViewController *lager = [[LargePictureViewController alloc] init];
    lager.index = sender.tag - 1118;
    lager.pictureSaveMode = PictureLocalMode;
    lager.allImageArray = _imageNameArray;
    
    [self removeDeleteButton];

    
    [self.navigationController pushViewController:lager animated:YES];

}


#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 999283) {
        if (buttonIndex == 0) {
            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];
            }
        } else if (buttonIndex == 1){
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            //设置选择后的图片可被编辑
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
}


#pragma mark - TableView Delegate/DateSource
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 314331) {
        if (buttonIndex == 1) {
            
            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, kReportCheckResultURL,_lookOnLine.uuid, dateString, operId, operName];
            url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            HttpClient *httpClient= [[HttpClient alloc] initWithUrl:url];
            
            
            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.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];
            }
            
            NSDictionary *parameters = @{
                                         @"storeUuid":_lookOnLine.store_uuid,
                                         @"processNote":self.footView.contentTextView.text,
                                         @"attachments":imageArray,
                                         };
            
            [httpClient reportCheckResultWithParameters:parameters completion:^(id response, NSError *error) {
                
                if ([response[@"success"] boolValue]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上报成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    alert.tag = 314332;
                    alert.delegate = self;
                    [alert show];
                    
                    if (_delegate && [_delegate respondsToSelector:@selector(reloadCurrentList)]) {
                        [_delegate reloadCurrentList];
                    }
                    
                } else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上报失败！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    [alert show];
                }
            }];
        }
    }
    
    
    if (alertView.tag == 314332) {
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#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)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return _rowNumber;
    }
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        LookOnLineDetailCell *cell=[tableView dequeueReusableCellWithIdentifier:kLookOnLineDetailCell];
        if (!cell) {
            cell = [[LookOnLineDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kLookOnLineDetailCell];
        }
        cell.lookOnLine = _lookOnLine;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else {
        if (indexPath.row == _rowNumber - 1) {
            if ((_imageNameArray.count + 1) % 2 == 0) {
                InspectPicAddCell *cell=[tableView dequeueReusableCellWithIdentifier:kOnLineInspectPicAddCell];
                if (!cell) {
                    cell = [[InspectPicAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kOnLineInspectPicAddCell];
                }
                NSString *imageName = _imageNameArray[_imageNameArray.count - 1];
                NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 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.tag = 1118 + _imageNameArray.count - 1;
                [cell.photoButton1 addTarget:self action:@selector(showLookOnLinePic:) forControlEvents:UIControlEventTouchUpInside];
                cell.photoButton2.tag = 22011;
                [cell.photoButton2 addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                // 添加长按手势
                UILongPressGestureRecognizer *longGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
                [cell.photoButton1 addGestureRecognizer:longGR];

                return cell;
            } else {
                InspectAddCell *cell=[tableView dequeueReusableCellWithIdentifier:kOnLineInspectAddCell];
                if (!cell) {
                    cell = [[InspectAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kOnLineInspectAddCell];
                }

                cell.photoButton.tag = 22001;
                [cell.photoButton addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
            
        } else {
            
            InpectPictureCell *cell=[tableView dequeueReusableCellWithIdentifier:kOnLineInpectPictureCell];
            if (!cell) {
                cell = [[InpectPictureCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kOnLineInpectPictureCell];
            }
            NSString *imageName0 = _imageNameArray[(indexPath.row ) * 2];
            NSString *fullPath0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName0];
            UIImage *image0 = [UIImage imageWithContentsOfFile:fullPath0];
            UIImage *image00 = [UIImage image:image0 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
            [cell.photoButton1 addTarget:self action:@selector(showLookOnLinePic:) forControlEvents:UIControlEventTouchUpInside];
            cell.photoButton1.tag = 1118 + (indexPath.row ) * 2;
            [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
            
            
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSString *imageName1 = _imageNameArray[(indexPath.row) * 2 + 1];
            NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName1];
            UIImage *image1 = [UIImage imageWithContentsOfFile:fullPath1];
            UIImage *image11 = [UIImage image:image1 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
            [cell.photoButton2 addTarget:self action:@selector(showLookOnLinePic:) forControlEvents:UIControlEventTouchUpInside];
            cell.photoButton2.tag = 1118 + (indexPath.row ) * 2 + 1;
            [cell.photoButton2 setImage:image11 forState:UIControlStateNormal];
            
            
            // 添加长按手势
            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 - 1118));
    
    if (_deleteButton) {
        [_deleteButton removeFromSuperview];
        _deleteButton = nil;
    }
    
    if (!_deleteButton) {
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteButton.tag = 5521 + (showButton.tag - 1118);
        [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
{
    NSLog(@"从imageName中删除了第%ld张图片",(button.tag - 5521));
    // 从存放所有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;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
- (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.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableFooterView = self.footView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100.0;
        
        [_tableView registerClass:[InspectAddCell class] forCellReuseIdentifier:kOnLineInspectAddCell];
        [_tableView registerClass:[InspectPicAddCell class] forCellReuseIdentifier:kOnLineInspectPicAddCell];
        [_tableView registerClass:[InpectPictureCell class] forCellReuseIdentifier:kOnLineInpectPictureCell];
        
        [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 *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];
        
//        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;
}

- (LookOnLineFootView *)footView
{
    if (!_footView) {
        _footView = [[LookOnLineFootView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        _footView.contentTextView.delegate = self;
        _footView.backgroundColor = [UIColor whiteColor];
        [_footView.resultButton setTitle:@"上报结果" forState:UIControlStateNormal];
        [_footView.resultButton addTarget:self action:@selector(reportRestult:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footView;
}


- (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.footView.placeholderLabel2.hidden = YES;
    }
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        self.footView.placeholderLabel2.hidden = NO;
    }
    
    if ([text isEqualToString:@"\n"]) {
        [self.footView.contentTextView resignFirstResponder];
        
        
        if (![text isEqualToString:@""]) {
            self.footView.placeholderLabel2.hidden = YES;
        }
        if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
            self.footView.placeholderLabel2.hidden = NO;
        }
        
        return NO;
    }
    
    if (range.location>=500) {
        return  NO;
    }
    else {
        return YES;
    }
    
    return YES;
}

@end
