//
//  TaskCheckViewController.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-4.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "NewTaskUploadViewController.h"
#import "TaskUploadViewController.h"
#import "ImageBrowserViewController.h"
#import "UIScrollView+Customized.h"
#import "TaskListView.h"
#import "DBDaoMgr.h"

@interface TaskUploadHeader : UIView
@property (nonatomic, strong) UILabel *lblNowExample;
@property (nonatomic, strong) UILabel *lblNowBeizhu;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *lblPlaceHonder;

@property (nonatomic, strong) UILabel *lblImageNum;
@property (nonatomic, strong) UILabel *lblImageNumPre;

@property (nonatomic, strong) UIButton *btnMin;

@property (nonatomic, strong) UIButton *btnMax;

@property (nonatomic, strong) UILabel * lblUseCustomNum;
@end

@interface NewTaskUploadViewController () <ImageBrowserDelegate, UITextViewDelegate,
UIAlertViewDelegate, UITextFieldDelegate, UIActionSheetDelegate>
{
    UIView *viewExample;
    NSLayoutConstraint *layoutCtScrollBottm;
    BOOL hasDataChanged;
    
    int picNum;

}
@property (copy,nonatomic)NSString *hasSaved;
@property (nonatomic, strong) NSDictionary *dictCheckInfo;


@property (nonatomic, strong) UILabel *lblBeizhu;
@property (nonatomic, strong) UILabel *lblBeizhuMessage;
@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, strong) TaskUploadHeader *headerView;

@property (nonatomic, strong) UILabel *lblExample;

@property (nonatomic, strong) ImageBrowserViewController *vcImageBExample;


@property (nonatomic, strong) ImageBrowserViewController *vcImageBReal;

@property (nonatomic, strong) UIButton *btnTakePics;
@property (nonatomic, strong) UIButton *btnHistory;

@property (nonatomic, strong) ImageBrowserViewController *vcImageBCheck;

@property (nonatomic, strong) UIScrollView *scrollVContainer;

@property (nonatomic, strong) NSArray *arrDeleteImages;
@end

@implementation NewTaskUploadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    self.title = @"上报检查点";
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    
    
    [btnBack setBackgroundImage:[UIImage imageNamed:@"NavBar/btn_nav_back.png"] forState:UIControlStateNormal];
    [btnBack sizeToFit];
    [btnBack addTarget:self action:@selector(btnBack) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navigationController navbarLeftItemCustomized:@[btnBack] onwer:self.navigationItem];
    
    
    viewExample = [UIView newAutoLayoutView];
    viewExample.backgroundColor = [UIColor whiteColor];
    
    [viewExample addSubview:self.vcImageBExample.view];
    [self addChildViewController:_vcImageBExample];
    [self.scrollVContainer addSubview:viewExample];
    
    [self.scrollVContainer autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeBottom];
    //[UIApplication showToastViewMessage:self.isUserCustom];
     [self setViewLayoutConstraint];  
}

- (void)btnBack
{
    if (hasDataChanged && ![self.hasSaved isEqualToString:@"上传成功！"] &&![self.hasSaved isEqualToString:@"处理图片出错！"] ) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"数据未上传，是否放弃已编辑的数据" delegate:self tag:100 cancelButtonTitle:@"放弃并返回" otherButtonTitles:@"继续编辑", nil];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
//
//    for (UIViewController *controller in self.navigationController.viewControllers) {
//        if ([controller isKindOfClass:NSClassFromString(@"TaskCheckViewController")]) {
//            [self.navigationController popToViewController:controller animated:YES];
//        }
//    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)setViewLayoutConstraint
{
    self.headerView.textView.delegate = self;
    
    [viewExample autoPinEdgeToSuperviewEdge:ALEdgeTop];
    [viewExample autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [viewExample autoPinEdgeToSuperviewEdge:ALEdgeRight];
//    [viewExample autoSetDimension:ALDimensionHeight toSize:320];
    
    [self.lblExample autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(5 , 10, 0,100) excludingEdge:ALEdgeBottom];
    
    [self.lblExample autoSetDimension:ALDimensionHeight toSize:30];
    
    [self.vcImageBExample.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblExample withOffset:0];
    
    [self.vcImageBExample.view autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [self.vcImageBExample.view autoPinEdgeToSuperviewEdge:ALEdgeRight];
    [self.vcImageBExample.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblExample withOffset:5];
    
    [self.lblBeizhu autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
    [self.lblBeizhu autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
    [self.lblBeizhu autoSetDimension:ALDimensionHeight toSize:30];
    [self.lblBeizhu autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.vcImageBExample.view];
    
    [self.lblBeizhuMessage autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
    [self.lblBeizhuMessage autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
    [self.lblBeizhuMessage autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblBeizhu];
    
    [self.lineView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:7];
    [self.lineView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:7];
    [self.lineView autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    [self.lineView autoSetDimension:ALDimensionHeight toSize:1];
    
    
    [self.scrollVContainer autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 50, 0)];
    
    
    [self.vcImageBReal.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.headerView withOffset:4];
    [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    
    [self.btnTakePics autoSetDimensionsToSize:CGSizeMake(130, 30)];
    [self.btnTakePics autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:20];
    [self.btnTakePics autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:10];
    
    [self.btnHistory autoSetDimensionsToSize:CGSizeMake(130, 30)];
    [self.btnHistory autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:20];
    [self.btnHistory autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:10];
    
    _vcImageBExample.selectedImages = _oldImages;
    int count = (int)_oldImages.count;
    int row = count/2+(count%2?1:0);
    
    CGFloat height = row * (_vcImageBExample.itemSize.height+_vcImageBExample.edgeInset.top+ _vcImageBExample.edgeInset.bottom);
    [self.vcImageBExample.view autoSetDimension:ALDimensionHeight toSize:height];
    
    
    NSString *beizhu = _oldBeizhu;
    CGFloat h = [beizhu boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.frame)-30, CGFLOAT_MAX)
                                     options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}
                                     context:nil].size.height;
    self.lblBeizhuMessage.text = beizhu;
    self.headerView.lblImageNum.text = [NSString stringWithFormat:@"%@张",self.PicNumNeed];
    [viewExample autoSetDimensionsToSize:CGSizeMake(320, h+height+75)];
    [_vcImageBExample reloadImageDatas];
    
    
    picNum  = [self.PicNumNeed integerValue];
    self.headerView.lblUseCustomNum.text = [NSString stringWithFormat:@"%@张",self.PicNumNeed];
    [self.headerView.btnMin addTarget:self action:@selector(btnMinClick) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.btnMax addTarget:self action:@selector(btnMaxClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.headerView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:viewExample];
    [self.headerView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [self.headerView autoSetDimension:ALDimensionWidth toSize:320];
    [self.headerView autoSetDimension:ALDimensionHeight toSize:170];
    
//    _vcImageBReal.selectedImages = _arrImages;
//    int count1 = (int)_arrImages.count+1;
//    int row1 = count1/2+(count1%2?1:0);
//    CGFloat height1 = row1 * (_vcImageBExample.itemSize.height+_vcImageBExample.edgeInset.top+ _vcImageBExample.edgeInset.bottom);
    [_vcImageBReal.view autoSetDimensionsToSize:CGSizeMake(320, 700)];
    [_vcImageBReal reloadImageDatas];
    
    [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20 relation:NSLayoutRelationGreaterThanOrEqual];
}

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

-(void)btnMinClick
{
    picNum--;
    if (picNum <= 0) {
        picNum = 0;
    }
    self.PicNumNeed = [NSString stringWithFormat:@"%d",picNum];
    self.headerView.lblUseCustomNum.text = [NSString stringWithFormat:@"%d张",picNum];
}

-(void)btnMaxClick
{
    picNum++;
    self.PicNumNeed = [NSString stringWithFormat:@"%d",picNum];
    self.headerView.lblUseCustomNum.text = [NSString stringWithFormat:@"%d张",picNum];
}

- (void)requestDatas
{
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryCheckPointDetailsEX";
    NSDictionary *dicParam = @{@"checkPointRecordId":self.checkPointRecordId};
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

-(void)btnDelete
{
    if(self.arrImages.count>0)
    {
        
        
        if ([_btnHistory.titleLabel.text isEqualToString:@"取消"]) {
            self.vcImageBReal.editing = NO;
            [self.vcImageBReal.collectionView reloadData];
            [_btnHistory setBackgroundImage:[UIImage imageWithColor:RGBColor(53, 181, 242, 1)] forState:UIControlStateNormal];
            [_btnHistory setTitle:@"删除图片" forState:UIControlStateNormal];
            [_btnHistory setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _btnHistory.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
            _btnHistory.layer.borderWidth = 0;
            [self.vcImageBReal.collectionView reloadData];
            // [self handleCheckPoint];
            
        }
        else
        {
            self.vcImageBReal.editing = YES;
            [_btnHistory setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [_btnHistory setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
            [_btnHistory setTitle:@"取消" forState:UIControlStateNormal];
            _btnHistory.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
            _btnHistory.layer.borderWidth = 0;
            [self.vcImageBReal.collectionView reloadData];
        }
        
        
    }
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    
    if ([operation.userInfo[@"interface"] isEqualToString:@"handleCheckPointEX"]) {
        
        [self uploadCheckPointPicture];
        
        
    }else if ([operation.userInfo[@"interface"] isEqualToString:@"uploadCheckPointPictureEX"]) {
        NSMutableArray *arrImageIds = [NSMutableArray array];
        for (ImageBrowserObj *imageObj in self.arrImages) {
            [arrImageIds addObject:@{@"id":imageObj.imageId?:@""}];
        }
        [DBDaoMgr updateImagesTagUploaded:arrImageIds];
        [DBDaoMgr updateCheckPointInfosTagUploaded:@[@{@"id":[NSString stringWithFormat:@"%@%@", _dictCheckInfo[@"checkPointId"],
                                                              _dictCheckInfo[@"type"]]}]];
        self.hasSaved=@"上传成功！";
        [UIApplication showToastViewMessage:self.hasSaved];
        
        
        if (self.arrDeleteImages.count > 0) {
            [self deleteCheckPointPicture];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kShouldReQueryCountInit object:nil];
        [UIApplication saveObject:@YES type:Number key:kShouldRequestDataWhenBack];
        
        
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:NSClassFromString(@"TaskPointViewController")]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }
    
//    if ([operation.userInfo[@"interface"] isEqualToString:@"queryCheckPointDetailsEX"]) {
    
//        [self setViewLayoutConstraint];
        
//        [self.scrollVContainer autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 50, 0)];
//
//        
//        [self.vcImageBReal.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.headerView withOffset:4];
//        [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
//        [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
//        
//        [self.btnTakePics autoSetDimensionsToSize:CGSizeMake(130, 30)];
//        [self.btnTakePics autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:20];
//        [self.btnTakePics autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:10];
//        
//        [self.btnHistory autoSetDimensionsToSize:CGSizeMake(130, 30)];
//        [self.btnHistory autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:20];
//        [self.btnHistory autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:10];
//        
//        _vcImageBExample.selectedImages = _arrImages;
//        int count = (int)_arrImages.count;
//        int row = count/2+(count%2?1:0);
//        
//        CGFloat height = row * (_vcImageBExample.itemSize.height+_vcImageBExample.edgeInset.top+ _vcImageBExample.edgeInset.bottom);
//        [self.vcImageBExample.view autoSetDimension:ALDimensionHeight toSize:height];
//        
//        
//        NSString *beizhu = @"阿拉斯加的阿拉斯加的阿拉斯加的阿拉斯加的阿拉斯加的阿拉斯加的阿拉斯加的阿拉斯加的";
//        CGFloat h = [beizhu boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.frame)-30, CGFLOAT_MAX)
//                                            options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
//                                         attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}
//                                            context:nil].size.height;
//        self.lblBeizhuMessage.text = beizhu;
//        [viewExample autoSetDimensionsToSize:CGSizeMake(320, h+height+75)];
//        [_vcImageBExample reloadImageDatas];
//        
//        [self.headerView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:viewExample];
//        [self.headerView autoPinEdgeToSuperviewEdge:ALEdgeLeft];
//        [self.headerView autoSetDimension:ALDimensionWidth toSize:320];
//        [self.headerView autoSetDimension:ALDimensionHeight toSize:170];
//        
//        _vcImageBReal.selectedImages = _arrImages;
//        int count1 = (int)_arrImages.count+1;
//        int row1 = count1/2+(count1%2?1:0);
//        CGFloat height1 = row1 * (_vcImageBExample.itemSize.height+_vcImageBExample.edgeInset.top+ _vcImageBExample.edgeInset.bottom);
//        [_vcImageBReal.view autoSetDimensionsToSize:CGSizeMake(320, height1-50)];
//        [_vcImageBReal reloadImageDatas];
//        
//        [self.vcImageBReal.view autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20 relation:NSLayoutRelationGreaterThanOrEqual];
//    }
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    [self.scrollVContainer autoPinEdgeToSuperviewEdge:ALEdgeBottom];
}

- (void)btnUpload:(UIButton *)sender
{
    [self handleCheckPoint];
}
- (void)handleCheckPoint
{
    if (![self checkInputValid]) {
        return;
    }
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface=@"handleCheckPointEX";
    NSDictionary *dicParam = @{@"checkPointRecordId":self.checkPointRecordId,
                               @"remark":self.headerView.textView.text,
                               @"amount":self.PicNumNeed,
                               @"location":[DataMgr getInstance].locationName?:@""};
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
    
}

- (void)uploadCheckPointPicture
{
    if ([self saveImageToDbAndCachePath])
    {
        if([self.picRequireMode isEqualToString:@"2"] || [self.picRequireMode isEqualToString:@"3"])
        {
            
            if(self.arrImages.count<[self.PicNumNeed integerValue])
            {
                NSString *message=[NSString stringWithFormat:@"上报数量不达标，要求不少于%@张！",self.PicNumNeed];
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"返回修改" otherButtonTitles:@"继续提交", nil];
                alert.tag=2046;
                [alert show];
            }
            else
            {
                NSMutableArray *arrFiles = [NSMutableArray array];
                for (ImageBrowserObj *imageObj in self.arrImages) {
                    if (imageObj.sourceType != ImageSourceTypeWebURL) {
                        NSDictionary *dictImage = @{kFileKeyName:imageObj.imageName, kFilePath:imageObj.imagePath};
                        [arrFiles addObject:dictImage];
                    }
                    
                }
                NSString *interface=@"uploadCheckPointPictureEX";
                NSDictionary *dicParam =@{@"checkPointRecordId":self.checkPointRecordId,@"type":@"2"};
                AFHTTPRequestOperation *operation = [self.networkMgr
                                                     operationUploadWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                     params:dicParam
                                                     dataType:BRNetMgrDataTypeJSON
                                                     fileType:BRNetMgrFileTypeJpeg
                                                     files:arrFiles];
                [self.networkMgr startOperation:operation];
            }
        }
        else
        {
            
            NSMutableArray *arrFiles = [NSMutableArray array];
            
            
            for (ImageBrowserObj *imageObj in self.arrImages) {
                if (imageObj.sourceType != ImageSourceTypeWebURL) {
                    NSDictionary *dictImage = @{kFileKeyName:imageObj.imageName, kFilePath:imageObj.imagePath};
                    [arrFiles addObject:dictImage];
                }
                
            }
            NSString *interface=@"uploadCheckPointPictureEX";
            NSDictionary *dicParam =@{@"checkPointRecordId":self.checkPointRecordId,@"type":@"2"};
            AFHTTPRequestOperation *operation = [self.networkMgr
                                                 operationUploadWithURL:kBaseEXURL(interface)
                                                 interface:interface
                                                 params:dicParam
                                                 dataType:BRNetMgrDataTypeJSON
                                                 fileType:BRNetMgrFileTypeJpeg
                                                 files:arrFiles];
            [self.networkMgr startOperation:operation];
        }
    }
    else
    {
        self.hasSaved=@"处理图片出错！";
        [UIApplication showToastViewMessage:self.hasSaved];
    }
    
}

- (void)deleteCheckPointPicture
{
    [UIApplication showLoadingView:kTextShowInProgress];
    
    NSString *interface=@"deleteCheckPointPictureEX";
    NSMutableString *picIdsStr = [NSMutableString string];
    BOOL first = YES;
    for (NSString *imageId in self.arrDeleteImages) {
        if (first) {
            [picIdsStr appendString:imageId];
            first = NO;
        }else {
            [picIdsStr appendFormat:@",%@",imageId];
        }
    }
    
    NSDictionary *dicParam = @{@"picIdsStr":picIdsStr?:@"",@"checkPointRecordId":self.checkPointRecordId?:@""};
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

- (BOOL)saveImageToDbAndCachePath
{
    NSString *type = nil;
    if ([[DataMgr getInstance].roleId isEqualToString:@"2"]) {
        type = @"2";
    }else {
        type = @"3";
    }
    
    NSMutableArray *arrImages = [NSMutableArray array];
    for (ImageBrowserObj *imageObj in self.arrImages) {
        
        if (imageObj.sourceType == ImageSourceTypeWebURL) {
            continue;
        }
        if (imageObj.imageSavedData) {
            [imageObj.imageSavedData writeToFile:imageObj.imagePath atomically:YES];
        }
        NSString *imagePath = [NSString stringWithFormat:@"%@/%@", kImageCachePath, imageObj.imageName];
        [arrImages addObject:@{@"id":imageObj.imageId, @"type":type, @"checkPointId":self.checkPointRecordId?:@"",
                               @"imageURL":@"",@"imagePath":imagePath}];
    }
    BOOL isInsertImageSuccess = [DBDaoMgr insertImages:arrImages];
    
    self.dictCheckInfo = @{@"checkPointId":self.checkPointRecordId?:@"",
                           @"type":type,
                           @"remark":self.headerView.textView.text,
                           @"amount":@"",
                           @"location":[DataMgr getInstance].locationName?:@""};
    //BOOL isInsertCheckPointSuccess = [DBDaoMgr insertCheckPointInfos:@[_dictCheckInfo]];
    //return (isInsertImageSuccess && isInsertCheckPointSuccess);
    return YES;
}
- (BOOL)checkInputValid
{
    if (self.headerView.textView.text.length == 0 ) {
        [UIApplication showToastViewMessage:@"请填写备注信息！"];
        
        return NO;
    }
    [self.view endEditing:YES];
    return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        self.headerView.lblPlaceHonder.hidden = NO;
    }else {
        self.headerView.lblPlaceHonder.hidden = YES;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        self.headerView.lblPlaceHonder.hidden = NO;
    }else {
        self.headerView.lblPlaceHonder.hidden = YES;
    }
    
    hasDataChanged = YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark =============  ImageBrowserViewController Delegate  =============


- (void)imageBrowser:(ImageBrowserViewController *)imageBrowser didSelectImages:(NSArray *)images
{
    self.arrImages = [NSMutableArray arrayWithArray:images];
    if([self.picRequireMode isEqualToString:@"3"])
        hasDataChanged = YES;
}

- (void)imageBrowserDidClickAddPicsButton:(ImageBrowserViewController *)imageBrowser
{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"从手机相册选择", nil];
    [sheet showInView:self.view];
    
    
    
    // [self.vcImageBrowser addImageWithImageBrowserPhotoSource:ImageBrowserPhotoSourceCamera];
}

- (void)imageBrowser:(ImageBrowserViewController *)imageBrowser didDeleteImages:(NSArray *)images
{
    self.arrDeleteImages = images;
    
    hasDataChanged = YES;
    
    NSArray * array = [NSArray arrayWithArray: self.arrImages];
    for(NSString* deleteImage in self.arrDeleteImages)
    {
        for(ImageBrowserObj* upImage in array)
        {
            if([deleteImage isEqual:upImage.imageId ])
            {
                [self.arrImages removeObject:upImage];
                break;
            }
        }
    }

    
    //    if([self.picRequireMode isEqualToString:@"1"])
    //    {
    //        self.lblNum.text=[NSString stringWithFormat:@"%lu/0",(unsigned long)self.arrImages.count];
    //
    //
    //    }
    //    else
    //        if([self.picRequireMode isEqualToString:@"2"])
    //        {
    //            self.lblNum.text=[NSString stringWithFormat:@"%lu/%@",(unsigned long)self.arrImages.count,self.PicNumNeed];
    //            
    //            
    //            
    //        }
    //        else
    //        {
    //            
    //        }
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.vcImageBReal addImageWithImageBrowserPhotoSource:ImageBrowserPhotoSourceCamera];
        
    }else if (buttonIndex == 1) {
        [self.vcImageBReal addImageWithImageBrowserPhotoSource:ImageBrowserPhotoSourceAsset];
    }else {
        
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100) {
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else
    {
        
    }
    
    
    if(alertView.tag==2046)
    {
        if(buttonIndex==1)
        {
            NSMutableArray *arrFiles = [NSMutableArray array];
            for (ImageBrowserObj *imageObj in self.arrImages) {
                if (imageObj.sourceType != ImageSourceTypeWebURL) {
                    NSDictionary *dictImage = @{kFileKeyName:imageObj.imageName, kFilePath:imageObj.imagePath};
                    [arrFiles addObject:dictImage];
                }
                
            }
            NSString *interface=@"uploadCheckPointPictureEX";
            NSDictionary *dicParam =@{@"checkPointRecordId":self.checkPointRecordId,@"type":@"2"};
            AFHTTPRequestOperation *operation = [self.networkMgr
                                                 operationUploadWithURL:kBaseEXURL(interface)
                                                 interface:interface
                                                 params:dicParam
                                                 dataType:BRNetMgrDataTypeJSON
                                                 fileType:BRNetMgrFileTypeJpeg
                                                 files:arrFiles];
            [self.networkMgr startOperation:operation];
        }
    }
    
    
}


#pragma mark =============  Propertise LazyLoad  =============

- (UIScrollView *)scrollVContainer
{
    if (!_scrollVContainer) {
        self.scrollVContainer = [UIScrollView newAutoLayoutView];
        _scrollVContainer.showsHorizontalScrollIndicator = NO;
        _scrollVContainer.showsVerticalScrollIndicator = YES;
        _scrollVContainer.backgroundColor = [UIColor clearColor];
        
        [self.view addSubview:_scrollVContainer];
    }
    return _scrollVContainer;
}

- (UILabel *)lblExample
{
    if (!_lblExample) {
        self.lblExample = [UILabel newAutoLayoutView];
        _lblExample.text = @"上次提交的照片:";
        _lblExample.textColor = RGBColor(153, 153, 153, 1);
        _lblExample.backgroundColor = [UIColor clearColor];
        _lblExample.textAlignment = NSTextAlignmentLeft;
        _lblExample.font=[UIFont systemFontOfSize:14];
        
        
        [viewExample addSubview:_lblExample];
        
    }
    return _lblExample;
}

- (UILabel *)lblBeizhu
{
    if (!_lblBeizhu) {
        self.lblBeizhu = [UILabel newAutoLayoutView];
        _lblBeizhu.text = @"备注:";
        _lblBeizhu.textColor = RGBColor(153, 153, 153, 1);
        _lblBeizhu.backgroundColor = [UIColor clearColor];
        _lblBeizhu.textAlignment = NSTextAlignmentLeft;
        _lblBeizhu.font=[UIFont systemFontOfSize:14];
        
        
        [viewExample addSubview:_lblBeizhu];
        
    }
    return _lblBeizhu;
}

- (UILabel *)lblBeizhuMessage
{
    if (!_lblBeizhuMessage) {
        self.lblBeizhuMessage = [UILabel newAutoLayoutView];
        _lblBeizhuMessage.text = @"备注:";
        _lblBeizhuMessage.textColor = RGBColor(153, 153, 153, 1);
        _lblBeizhuMessage.backgroundColor = [UIColor clearColor];
        _lblBeizhuMessage.textAlignment = NSTextAlignmentLeft;
        _lblBeizhuMessage.font=[UIFont systemFontOfSize:13];
        _lblBeizhuMessage.numberOfLines = 0;
        
        [viewExample addSubview:_lblBeizhuMessage];
        
    }
    return _lblBeizhuMessage;
}
- (UIView *)lineView
{
    if (!_lineView) {
        self.lineView = [[UIView alloc] init];
        _lineView.backgroundColor = RGBColor(240, 240, 240, 1);
        [viewExample addSubview:_lineView];
    }
    return _lineView;
}


- (TaskUploadHeader *)headerView
{
    if (!_headerView) {
        self.headerView = [[TaskUploadHeader alloc] initWithFrame:CGRectZero];
        _headerView.translatesAutoresizingMaskIntoConstraints = NO;
        _headerView.backgroundColor = [UIColor clearColor];
        [self.scrollVContainer addSubview:_headerView];
    }
    return _headerView;
}


- (ImageBrowserViewController *)vcImageBExample
{
    if (!_vcImageBExample) {
        self.vcImageBExample = [[ImageBrowserViewController alloc] initWithNibName:nil bundle:nil];
        _vcImageBExample.showAddPicsButton = NO;
        _vcImageBExample.delegate = self;
        _vcImageBExample.collectionView.scrollEnabled = NO;
        _vcImageBExample.vcImagePickerPrensentFrom = self.navigationController;
    }
    return _vcImageBExample;
}
- (ImageBrowserViewController *)vcImageBReal
{
    if (!_vcImageBReal) {
        self.vcImageBReal = [[ImageBrowserViewController alloc] initWithNibName:nil bundle:nil];
        _vcImageBReal.delegate = self;
        _vcImageBReal.canBeDelete = YES;
        _vcImageBReal.photoSource = ImageBrowserPhotoSourceAsset;
        _vcImageBReal.itemSize = CGSizeMake(130, 110);
        _vcImageBReal.vcImagePickerPrensentFrom = self.navigationController;
        [self addChildViewController:_vcImageBReal];
        [self.scrollVContainer addSubview:_vcImageBReal.view];
    }
    return _vcImageBReal;
}
- (ImageBrowserViewController *)vcImageBCheck
{
    if (!_vcImageBCheck) {
        self.vcImageBCheck = [[ImageBrowserViewController alloc] initWithNibName:nil bundle:nil];
        _vcImageBCheck.delegate = self;
        _vcImageBCheck.showAddPicsButton = YES;
        
        _vcImageBCheck.collectionView.scrollEnabled = NO;
        _vcImageBCheck.vcImagePickerPrensentFrom = self.navigationController;
        [self addChildViewController:_vcImageBCheck];
        [self.scrollVContainer addSubview:_vcImageBCheck.view];
    }
    return _vcImageBCheck;
}

- (UIButton *)btnTakePics
{
    if (!_btnTakePics) {
        self.btnTakePics = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnTakePics.translatesAutoresizingMaskIntoConstraints = NO;
        _btnTakePics.layer.cornerRadius = 5;
        _btnTakePics.clipsToBounds = YES;
        [_btnTakePics setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha:1]] forState:UIControlStateNormal];
        _btnTakePics.titleLabel.font=[UIFont systemFontOfSize:14];
        
        [_btnTakePics setTitle:@"上报" forState:UIControlStateNormal];
        [_btnTakePics setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btnTakePics addTarget:self action:@selector(btnUpload:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btnTakePics];
    }
    return _btnTakePics;
}
- (UIButton *)btnHistory
{
    if (!_btnHistory) {
        self.btnHistory = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnHistory.translatesAutoresizingMaskIntoConstraints = NO;
        _btnHistory.layer.cornerRadius = 5;
        _btnHistory.clipsToBounds = YES;
        [_btnHistory setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha:1]] forState:UIControlStateNormal];
        [_btnHistory setTitle:@"删除图片" forState:UIControlStateNormal];
        [_btnHistory setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btnHistory.titleLabel.font=[UIFont systemFontOfSize:14];
        
        [_btnHistory addTarget:self action:@selector(btnDelete) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btnHistory];
    }
    return _btnHistory;
}
@end

@implementation TaskUploadHeader

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.lblNowExample];
        [self addSubview:self.lblNowBeizhu];
        [self addSubview:self.textView];
        [self addSubview:self.lblPlaceHonder];
        [self addSubview:self.lblImageNumPre];
        [self addSubview:self.lblImageNum];
//        [self addSubview:self.btnMin];
//        [self addSubview:self.lblUseCustomNum];
//        [self addSubview:self.btnMax];
        
        [self.lblNowExample autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(10, 10, 0, 10) excludingEdge:ALEdgeBottom];
        [self.lblNowExample autoSetDimension:ALDimensionHeight toSize:25];
        
        [self.lblNowBeizhu autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
        [self.lblNowBeizhu autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblNowExample withOffset:10];
        [self.lblNowBeizhu autoSetDimension:ALDimensionHeight toSize:25];
        
        [self.textView autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblNowBeizhu withOffset:5];
        [self.textView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
        [self.textView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblNowExample withOffset:5];
        [self.textView autoSetDimension:ALDimensionHeight toSize:75];
        
        [self.lblPlaceHonder autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.textView withOffset:5];
        [self.lblPlaceHonder autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.textView withOffset:5];
        
        [self.lblImageNumPre autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblNowBeizhu];
        [self.lblImageNumPre autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textView withOffset:10];
        [self.lblImageNumPre autoSetDimension:ALDimensionHeight toSize:25];
        
        [self.lblImageNum autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblImageNumPre withOffset:5];
        [self.lblImageNum autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblImageNumPre];
        [self.lblImageNum autoSetDimension:ALDimensionHeight toSize:25];
        
//        [self.btnMin autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblImageNumPre withOffset:5];
//        [self.btnMin autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblImageNumPre];
//        [self.btnMin autoSetDimensionsToSize:CGSizeMake(35, 35)];
//        
//        [self.lblUseCustomNum autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.btnMin withOffset:5];
//        [self.lblUseCustomNum autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblImageNumPre];
//        [self.lblUseCustomNum autoSetDimension:ALDimensionHeight toSize:25];
//        
//        [self.btnMax autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblUseCustomNum withOffset:5];
//        [self.btnMax autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblImageNumPre];
//        [self.btnMax autoSetDimensionsToSize:CGSizeMake(35, 35)];
    }
    return self;
}
- (UILabel *)lblNowExample
{
    if (!_lblNowExample) {
        self.lblNowExample = [UILabel newAutoLayoutView];
        _lblNowExample.text = @"本次提交的照片:";
        _lblNowExample.textColor = RGBColor(153, 153, 153, 1);
        _lblNowExample.backgroundColor = [UIColor clearColor];
        _lblNowExample.textAlignment = NSTextAlignmentLeft;
        _lblNowExample.font=[UIFont systemFontOfSize:14];
    }
    return _lblNowExample;
}

- (UILabel *)lblNowBeizhu
{
    if (!_lblNowBeizhu) {
        self.lblNowBeizhu = [UILabel newAutoLayoutView];
        _lblNowBeizhu.text = @"备注:";
        _lblNowBeizhu.textColor = RGBColor(62, 182, 239, 1);
        _lblNowBeizhu.backgroundColor = [UIColor clearColor];
        _lblNowBeizhu.textAlignment = NSTextAlignmentLeft;
        _lblNowBeizhu.font=[UIFont systemFontOfSize:14];

    }
    return _lblNowBeizhu;
}

-(UITextView*)textView
{
    if (!_textView) {
        self.textView = [[UITextView alloc] init];
        _textView.layer.cornerRadius = 3;
        _textView.layer.borderWidth = 1;
        _textView.layer.borderColor = RGBColor(215, 215, 215, 1).CGColor;
    }
    return _textView;
}

- (UILabel *)lblPlaceHonder
{
    if (!_lblPlaceHonder) {
        self.lblPlaceHonder = [UILabel newAutoLayoutView];
        _lblPlaceHonder.text = @"此处填写备注信息";
        _lblPlaceHonder.textColor = RGBColor(153, 153, 153, 1);
        _lblPlaceHonder.backgroundColor = [UIColor clearColor];
        _lblPlaceHonder.textAlignment = NSTextAlignmentLeft;
        _lblPlaceHonder.font=[UIFont systemFontOfSize:13];
        
    }
    return _lblPlaceHonder;
}

- (UILabel *)lblImageNumPre
{
    if (!_lblImageNumPre) {
        self.lblImageNumPre = [UILabel newAutoLayoutView];
        _lblImageNumPre.text = @"图片要求:";
        _lblImageNumPre.textColor = RGBColor(62, 182, 239, 1);
        _lblImageNumPre.backgroundColor = [UIColor clearColor];
        _lblImageNumPre.textAlignment = NSTextAlignmentLeft;
        _lblImageNumPre.font=[UIFont systemFontOfSize:14];
        
    }
    return _lblImageNumPre;
}

- (UILabel *)lblImageNum
{
    if (!_lblImageNum) {
        self.lblImageNum = [UILabel newAutoLayoutView];
        _lblImageNum.text = @"3张";
        _lblImageNum.textColor = RGBColor(153, 153, 153, 1);
        _lblImageNum.backgroundColor = [UIColor clearColor];
        _lblImageNum.textAlignment = NSTextAlignmentLeft;
        _lblImageNum.font=[UIFont systemFontOfSize:14];
    }
    return _lblImageNum;
}

- (UIButton *)btnMin
{
    if (!_btnMin) {
        self.btnMin = [UIButton newAutoLayoutView];
        [_btnMin setBackgroundImage:[UIImage imageNamed:@"Task/icon_minus_off.png"] forState:UIControlStateNormal];
    }
    return _btnMin;
}
- (UILabel *)lblUseCustomNum
{
    if (!_lblUseCustomNum) {
        self.lblUseCustomNum = [UILabel newAutoLayoutView];
        _lblUseCustomNum.text = @"3张";
        _lblUseCustomNum.textColor = RGBColor(153, 153, 153, 1);
        _lblUseCustomNum.backgroundColor = [UIColor clearColor];
        _lblUseCustomNum.textAlignment = NSTextAlignmentLeft;
        _lblUseCustomNum.font=[UIFont systemFontOfSize:14];
    }
    return _lblUseCustomNum;
}
- (UIButton *)btnMax
{
    if (!_btnMax) {
        self.btnMax = [UIButton newAutoLayoutView];
        [_btnMax setBackgroundImage:[UIImage imageNamed:@"Task/icon_plus_off.png"] forState:UIControlStateNormal];
        
    }
    return _btnMax;
}
@end



