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

#import "LookOnLineDetailViewController.h"
#import "LookOnLineDetailView.h"
#import "LookOnLineFootView.h"
#import "HttpClient.h"

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


#define kLookOnLineDetailCell @"LookOnLineDetailCell"

@interface LookOnLineDetailViewController () <UIAlertViewDelegate,UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) LookOnLineDetailView *headerView;
@property (nonatomic, strong) LookOnLineFootView *footView;

@property (nonatomic, strong) NSMutableArray *imageNameArray;

@property (nonatomic, assign) int rowNumber;

@end

@implementation LookOnLineDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNav];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.imageNameArray = [NSMutableArray array];
    
    [self requestOnLineDetail];
    _rowNumber = 1;
}

#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)requestOnLineDetail
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@?fetch_parts=stores", kRedStarURL, kSportcheckDetailURL,self.uuid];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    HttpClient *httpClient= [[HttpClient alloc] initWithUrl:url];
   
    [httpClient getSportCheckDetailWithCompletion:^(id response, NSError *error) {
        NSLog(@"5.4 抽查明细   response = %@, error = %@", response, error);
    }];

}

- (void)reportRestult:(UIButton *)sender
{
    // 提示框
    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)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 - 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,@"checkId", dateString, operId, operName];
            url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            NSLog(@"上报抽检结果 url = %@", url);
            HttpClient *httpClient= [[HttpClient alloc] initWithUrl:url];
            
            NSDictionary *parameters = @{
                                         @"storeUuid":@"",
                                         @"processNote":self.footView.contentTextView.text,
                                         @"attachments":@[],
                                         };
            
            [httpClient reportCheckResultWithParameters:parameters completion:^(id response, NSError *error) {
                NSLog(@"上报抽检结果 response = %@", response);
                NSLog(@"上报抽检结果 error = %@", error);
            }];
        }
    }
}

#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;
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    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];
            [cell.photoButton1 setImage:image forState:UIControlStateNormal];
            cell.photoButton2.tag = 22011;
            [cell.photoButton2 addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            
            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];
            
            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];
        [cell.photoButton1 setImage:image0 forState:UIControlStateNormal];
        
        NSString *imageName1 = _imageNameArray[(indexPath.row) * 2 + 1];
        NSLog(@"imageName = %@", imageName1);
        NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName1];
        UIImage *image1 = [UIImage imageWithContentsOfFile:fullPath1];
        [cell.photoButton2 setImage:image1 forState:UIControlStateNormal];
        return cell;
    }

}



#pragma mark - lazy loading
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableHeaderView = self.headerView;
        _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];
        
        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;
}

- (LookOnLineDetailView *)headerView
{
    if (!_headerView) {
        _headerView = [[LookOnLineDetailView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 295)];
        _headerView.titleLabel.text = @"2015年十一促销临时抽查";
    }
    return _headerView;
}

- (LookOnLineFootView *)footView
{
    if (!_footView) {
        _footView = [[LookOnLineFootView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        _footView.backgroundColor = [UIColor clearColor];
        [_footView.resultButton addTarget:self action:@selector(reportRestult:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footView;
}
@end
