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

#import "TaskUploadViewController.h"
#import "UITextField+EdgeInset.h"
#import "DBDaoMgr.h"
#import "BaseTextField.h"
#import "UIScrollView+Customized.h"

@interface TaskUploadViewController () < ImageBrowserDelegate, UITextViewDelegate,
UIAlertViewDelegate, UITextFieldDelegate, UIActionSheetDelegate >
{
    BOOL hasDataChanged;


}

@property (copy,nonatomic)NSString *hasSaved;


@property (weak, nonatomic) IBOutlet UIView *viewDesc;

@property (nonatomic, strong) IBOutlet UIView *viewCheck;
@property (nonatomic, strong) IBOutlet UILabel *lblCheckRemarkPre;
@property (nonatomic, strong) IBOutlet UILabel *lblCheckRemarkPlaceholder;
@property (nonatomic, strong) IBOutlet UITextView *textVCheckRemark;
@property (weak, nonatomic) IBOutlet UILabel *picNeedPre;

@property (strong, nonatomic) IBOutlet UILabel *lblNum;

@property (nonatomic, strong) ImageBrowserViewController *vcImageBrowser;
@property (nonatomic, strong) UIButton *btnDelete;
@property (nonatomic, strong) UIButton *btnUpload;


@property (nonatomic, strong) NSDictionary *dictCheckInfo;

@property (nonatomic, strong) NSArray *arrDeleteImages;

@property (strong, nonatomic) IBOutlet UILabel *taskName;

@property (strong, nonatomic) IBOutlet UILabel *taskLocation;
@property (strong, nonatomic) IBOutlet UILabel *checkLocation;

@property (strong, nonatomic) IBOutlet UILabel *belongArea;


@property (weak, nonatomic) IBOutlet UIView *picSelectedView;

@property (strong,nonatomic)UIButton *btnAdd;
@property (strong,nonatomic)UIButton *btnMinus;
@property (strong,nonatomic)UILabel *lblAutoDesc;
@property (strong,nonatomic)UILabel *picSelectedNum;

@end

@implementation TaskUploadViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    [self.viewCheck addSubview:_picSelectedView];

    
    [_picSelectedView addSubview:self.btnMinus];

    [_picSelectedView addSubview:self.btnAdd];
    [_picSelectedView addSubview:self.picSelectedNum];
    [_picSelectedView addSubview:self.lblAutoDesc];
  
    [self.btnAdd autoPinEdgeToSuperviewEdge:ALEdgeRight];
    [self.btnAdd autoPinEdgeToSuperviewEdge:ALEdgeTop];
    
    [self.btnMinus autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [self.btnMinus autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    [self.picSelectedNum autoSetDimension:ALDimensionHeight toSize:40];
    [self.picSelectedNum autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    [self.picSelectedNum autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.btnMinus withOffset:0];
    [self.picSelectedNum autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:self.btnAdd withOffset:0];

    [self.lblAutoDesc autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.btnMinus withOffset:0];
    [self.lblAutoDesc autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.btnAdd withOffset:0];
    [self.lblAutoDesc autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.picSelectedNum withOffset:0];
    
    
    
    NSString *areaName = nil;
    switch ([self.dictTaskCheckInfo[@"type"] intValue]) {
        case 1: areaName = @"外广场"; break;
        case 2: areaName = @"商场大堂"; break;
        case 3: areaName = @"中庭"; break;
        case 4: areaName = @"过道"; break;
        case 5: areaName = @"其他"; break;
        default:
            break;
    }

    self.lblNum.layer.borderColor = RGBColor(215, 215, 215, 1).CGColor;
    self.lblNum.textColor=RGBColor(244, 160, 0, 1);
    
    
    if([self.picRequireMode isEqualToString:@"2"])
        {
//          self.lblNum.text=[NSString stringWithFormat: @"%ld/%@",self.arrImages.count,self.PicNumNeed];
            self.picNeedPre.text=@"图片要求：";
        self.lblNum.text=[NSString stringWithFormat: @"%@ 张",self.PicNumNeed];
            _picSelectedView.hidden=YES;
            
        }
    else
        if([self.picRequireMode isEqualToString:@"1"])
    {
//        self.picNeedPre.text=@"图片要求：";
//        self.lblNum.text=[NSString stringWithFormat:@"0 张" ];
        self.picNeedPre.hidden=YES;
        self.lblNum.hidden=YES;
        _picSelectedView.hidden=YES;
        [self.viewCheck autoSetDimension:ALDimensionHeight toSize:100];
        
    }
    else
    {
        self.lblNum.hidden=YES;
        _picSelectedView.hidden=NO;
       // self.picSelectedNum.text=[ NSString stringWithFormat:@"%lu", (unsigned long)self.arrImages.count];
        self.picNeedPre.text=@"实际数量：";
        self.picSelectedNum.text=[NSString stringWithFormat:@"%@",self.PicNumNeed];

    }
    

    
    self.lblNum.font=[UIFont systemFontOfSize:18];
    _textVCheckRemark.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
#if kIOSVersion7Later
    _textVCheckRemark.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
#endif
    _textVCheckRemark.layer.borderWidth = 1;
    _textVCheckRemark.layer.borderColor = RGBColor(215, 215, 215, 1).CGColor;
    [self registObserverOfTextInputView];
    
    
    
    self.title = @"上报检查点";
    [self.btnUpload setTitle:@"上 报" forState:UIControlStateNormal];

    if (self.isEditMode) {

        
        self.vcImageBrowser.selectedImages = self.arrImages;
        [self.vcImageBrowser reloadImageDatas];
       
        
    }
//    else
//    {
//     
//        NSArray *arrDBImages = [DBDaoMgr fetchImagesByType:type checkPointId:self.checkPointRecordId];
//       
//        NSArray *arrCheckInfos = [DBDaoMgr fetchCheckPointInfoByType:type checkPointId:self.checkPointRecordId];
//        
//      
//        
//        if (arrCheckInfos.count > 0) {
//            self.dictCheckInfo = arrCheckInfos[0];
////            self.textFQuantity.text = _dictCheckInfo[@"amount"];
//            self.textVCheckRemark.text = _dictCheckInfo[@"remark"];
//            if (self.textVCheckRemark.text.length > 0) {
//                self.lblCheckRemarkPlaceholder.hidden = YES;
//            }
//            
//        }
//        
//        NSMutableArray *arrBrowserObjs = [NSMutableArray array];
//        for (NSDictionary *dictImage in arrDBImages) {
//            ImageBrowserObj *detailObj = [[ImageBrowserObj alloc] init];
//            detailObj.imageId = dictImage[@"id"];
//            detailObj.sourceType = ImageSourceTypeFilePath;
//            detailObj.imagePath = dictImage[@"imagePath"];
//            detailObj.imageName = [NSString stringWithFormat:@"%@.jpg", dictImage[@"id"]];
//            [arrBrowserObjs addObject:detailObj];
//        }
//        
//        self.vcImageBrowser.selectedImages = arrBrowserObjs;
//        self.arrImages = arrBrowserObjs;
//        
//        [self.vcImageBrowser reloadImageDatas];
//        
//        
//      
//        
//    }
    self.textVCheckRemark.text=self.picRemark;
    
    self.lblCheckRemarkPlaceholder.hidden = self.textVCheckRemark.text.length > 0?YES:NO;
    
    [self setViewLayoutConstraint];
    
}
- (void)setViewLayoutConstraint
{
    [self.viewDesc autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeBottom];
    [self.viewDesc autoSetDimension:ALDimensionHeight toSize:0];

    
    [self.viewCheck autoPinEdgeToSuperviewEdge:ALEdgeLeft];
    [self.viewCheck autoPinEdgeToSuperviewEdge:ALEdgeRight];
    [self.viewCheck autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.viewDesc];
    [self.viewCheck autoSetDimension:ALDimensionHeight toSize:150];

    
    
    [self.vcImageBrowser.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.viewCheck withOffset:10];
   
    [self.vcImageBrowser.view autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [self.vcImageBrowser.view autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    
    
    [self.btnDelete autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.vcImageBrowser.view withOffset:30 relation:NSLayoutRelationLessThanOrEqual];
    [self.btnDelete autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.vcImageBrowser.view withOffset:10 relation:NSLayoutRelationGreaterThanOrEqual];
    [self.btnDelete autoSetDimensionsToSize:CGSizeMake(140, 30)];
    [self.btnDelete autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
    
    [self.btnUpload autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.btnDelete];
    [self.btnUpload autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.btnDelete];
    [self.btnUpload autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.btnDelete];
    [self.btnUpload autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
    [self.btnUpload autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20];
 
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

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

- (BOOL)checkInputValid
{
    if (self.textVCheckRemark.text.length == 0 ) {
        [UIApplication showToastViewMessage:@"请填写备注信息！"];
        
        return NO;
    }
    
//    if([self.arrImages count]==0 )
//    {
//        if([self.picRequireMode isEqualToString:@"1"])
//        {
//            return YES;
//            
//        }
//        
//        else if([self.picRequireMode isEqualToString:@"2"]  || [self.picRequireMode isEqualToString:@"3"])
//        {
//        [UIApplication showToastViewMessage:@"请选择上传图片！"];
//            return NO;
//        }
//        
//    }
    
    [self.view endEditing:YES];
    return YES;
}

- (void)handleCheckPoint
{
    if (![self checkInputValid]) {
        return;
    }
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface=@"handleCheckPointEX";
    NSDictionary *dicParam = @{@"checkPointRecordId":self.checkPointRecordId,
                               @"remark":_textVCheckRemark.text,
                               @"amount":self.picSelectedNum.text,
                               @"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":_textVCheckRemark.text,
                           @"amount":self.picSelectedNum.text,
                           @"location":[DataMgr getInstance].locationName?:@""};
    //BOOL isInsertCheckPointSuccess = [DBDaoMgr insertCheckPointInfos:@[_dictCheckInfo]];
    //return (isInsertImageSuccess && isInsertCheckPointSuccess);
    return YES;
}

- (void)popViewControllerWithAnimated
{
    [self.navigationController popViewControllerAnimated:YES];
}


#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];
            }
        }
    }
//        else if ([operation.userInfo[@"interface"] isEqualToString:@"deleteCheckPointPictureEX"]) {
////        [UIApplication showToastViewMessage:@"删除图片成功！"];
//        NSString *message = [[DataMgr getInstance].roleId isEqualToString:@"2"]?@"上传上报数据成功！":@"上传检查数据成功！";
//        [UIApplication showToastViewMessage:message];
//        
//        [self performSelector:@selector(popViewControllerWithAnimated) withObject:nil afterDelay:0.5];
//    }
    
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}

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

- (void)btnDeleteClick:(id)sender
{

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


/*
- (void)btnSaveClick:(id)sender
{
    if (![self checkInputValid]) {
        return;
    }
    
//    if (self.arrImages.count == 0) {
//        [UIApplication showToastViewMessage:@"请选择图片！"];
//        return;
//    }
    
    if ([self saveImageToDbAndCachePath]) {
        hasDataChanged = NO;
        [UIApplication showToastViewMessage:@"保存成功！"];
        
        [self performSelector:@selector(popViewControllerWithAnimated) withObject:nil afterDelay:0.5];
    }else {
        hasDataChanged = YES;
        [UIApplication showToastViewMessage:@"保存失败，请重试"];
    }
    
}
*/

- (void)btnUploadClick:(id)sender
{    
    [self handleCheckPoint];
}

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

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        self.lblCheckRemarkPlaceholder.hidden = NO;
    }else {
        self.lblCheckRemarkPlaceholder.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"])
//    {
//        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
   // {
      //  self.picSelectedNum.text=[NSString stringWithFormat:@"%@",self.PicNumNeed];
        
        
   // }
       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.vcImageBrowser addImageWithImageBrowserPhotoSource:ImageBrowserPhotoSourceCamera];
        
    }else if (buttonIndex == 1) {
        [self.vcImageBrowser 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];
        }
    }
    
    
}

- (ImageBrowserViewController *)vcImageBrowser
{
    if (!_vcImageBrowser) {
        self.vcImageBrowser = [[ImageBrowserViewController alloc] initWithNibName:nil bundle:nil];
        _vcImageBrowser.delegate = self;
        _vcImageBrowser.canBeDelete = YES;
        _vcImageBrowser.photoSource = ImageBrowserPhotoSourceAsset;
        _vcImageBrowser.itemSize = CGSizeMake(130, 110);
        _vcImageBrowser.vcImagePickerPrensentFrom = self.navigationController;
        [self addChildViewController:_vcImageBrowser];
        [self.view addSubview:_vcImageBrowser.view];
    }
    return _vcImageBrowser;
}

- (UIButton *)btnDelete
{
    if (!_btnDelete) {
        self.btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnDelete.translatesAutoresizingMaskIntoConstraints = NO;
      

        [_btnDelete setBackgroundImage:[UIImage imageWithColor:RGBColor(53, 181, 242, 1)] forState:UIControlStateNormal];
       
        [_btnDelete setTitle:@"删除图片" forState:UIControlStateNormal];
        [_btnDelete setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btnDelete.layer.cornerRadius= 5;
        
        _btnDelete.layer.masksToBounds= YES;
        [_btnDelete addTarget:self action:@selector(btnDeleteClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btnDelete];
    }
    return _btnDelete;
}

- (UIButton *)btnUpload
{
    if (!_btnUpload) {
        self.btnUpload = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnUpload.translatesAutoresizingMaskIntoConstraints = NO;
        _btnUpload.layer.cornerRadius= 5;
        
        _btnUpload.layer.masksToBounds= YES;

    [_btnUpload setBackgroundImage:[UIImage imageWithColor:RGBColor(53, 181, 242, 1)] forState:UIControlStateNormal];
        [_btnUpload setTitle:@"上 报" forState:UIControlStateNormal];
        [_btnUpload setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btnUpload addTarget:self action:@selector(btnUploadClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btnUpload];
    }
    return _btnUpload;
}
#pragma =====================自定义按钮=================

-(UIButton *)btnAdd
{
    if(!_btnAdd)
    {
        self.btnAdd=[UIButton newAutoLayoutView];
        _btnAdd.layer.borderWidth=0;
        
        [self.btnAdd setBackgroundImage:[UIImage imageNamed:@"Task/icon_plus_off.png"] forState:UIControlStateNormal];
   
       [self.btnAdd addTarget:self action:@selector(plusAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnAdd;
}

-(UIButton *)btnMinus
{
    if(!_btnMinus)
    {
        self.btnMinus=[UIButton newAutoLayoutView];
        _btnMinus.layer.borderWidth=0;
        
        [self.btnMinus setBackgroundImage:[UIImage imageNamed:@"Task/icon_minus_off.png"] forState:UIControlStateNormal];
    
        
        [self.btnMinus addTarget:self action:@selector(minusAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnMinus;
}
-(UILabel *)picSelectedNum
{
    if(!_picSelectedNum)
    {
        self.picSelectedNum=[UILabel newAutoLayoutView];
        _picSelectedNum.textAlignment=NSTextAlignmentCenter;
        _picSelectedNum.textColor=[UIColor blackColor];
        _picSelectedNum.backgroundColor=[UIColor clearColor];
        _picSelectedNum.text=@"0";
        [_picSelectedNum setFont:[UIFont systemFontOfSize:16]];
      
        
    }
    return _picSelectedNum;
    
}
-(UILabel *)lblAutoDesc
{
    if(!_lblAutoDesc)
    {
        self.lblAutoDesc=[UILabel newAutoLayoutView];
        _lblAutoDesc.textAlignment=NSTextAlignmentLeft;
        _lblAutoDesc.textColor=[UIColor blackColor];
        _lblAutoDesc.numberOfLines = 2;
        _lblAutoDesc.backgroundColor=[UIColor clearColor];
        _lblAutoDesc.text=@"请输入本检点在本商场实际环境下需要的图片数量.";
        [_lblAutoDesc setFont:[UIFont systemFontOfSize:11]];
        
        
    }
    return _lblAutoDesc;
    
}
-(void)minusAction
{
    long int temp=[self.picSelectedNum.text integerValue];
    
    if(temp>0)
    {
        temp--;
        self.picSelectedNum.text=[NSString stringWithFormat:@"%ld",temp];
        self.PicNumNeed = self.picSelectedNum.text;
    }
    
    
}
-(void)plusAction
{
    long int temp=[self.picSelectedNum.text integerValue];
    
        temp++;
        self.picSelectedNum.text=[NSString stringWithFormat:@"%ld",temp];
        self.PicNumNeed = self.picSelectedNum.text;
}

@end
