//
//  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 "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) int rowNumber;

@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)", self.catesgory, 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.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];

}


#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;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"你确定要上传检查点的相关信息吗？"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 533292;
    [alert show];
}

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

- (void)showPicture:(UIButton *)sender
{
    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 (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];
    }
}





#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.5);
    
    
    NSString *imageName = [CommonFunc md5Data:imageData];
    [_imageNameArray addObject:imageName];
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    imageData = 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) {
        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];
            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];
            
            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];
        UIImage *image0 = [UIImage imageWithContentsOfFile:fullPath0];
        UIImage *image00 = [UIImage image:image0 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
        [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
        
        NSString *imageName1 = _imageNameArray[(indexPath.row - 1) * 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 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;


        return cell;
    }
}



// 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];
                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"];
            
            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
                                         };
            [httpClient uploadInspectResultWithParameters:parameters completion:^(id response, NSError *error) {
                
                NSLog(@"上传检查点  respose  =%@  error = %@", response, error);
                if (response[@"success"]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"检查点上报成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    alert.delegate = self;
                    alert.tag = 39429234;
                    [alert show];
                }
                [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
