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

#import "InspectSettleViewController.h"
#import "InspectSettleCell.h"
#import "InspectDetailFooterView.h"

#import "CheckPicViewController.h"

#import "HttpClient.h"
#define kInspectSettleCell @"InspectSettleCell"

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

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

@end

@implementation InspectSettleViewController
- (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.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:[InspectSettleCell class] forCellReuseIdentifier:kInspectSettleCell];

    self.tableView.tableFooterView = self.footerView;
    
    self.footerView.takePhotoView.delegate = self;
    
}

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

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

#pragma mark - TakePhoto Delegate
- (void)deletePhoto:(UIButton *)button
{
    // 从存放所有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;
    
}

- (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 - UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    // 创建一个新的控件
    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];
}

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

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

- (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    // NSString * regEx = @"<([^>]*)>";
    // html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}

- (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.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 200.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];
}

@end
