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

#import "AddQuestionViewController.h"
#import "OnLineTableViewCell.h"

#import "AddQuestionFooterView.h"
#import "CheckPicViewController.h"
#import "InspectAddCell.h"
#import "InspectPicAddCell.h"
#import "InpectPictureCell.h"
#import "CommonFunc.h"
#import "HttpClient.h"
#import <MBProgressHUD.h>
#import "AddQuestionTableCell.h"
#import "UIImage+Fit.h"
#import "LargePictureViewController.h"

#define kPhotoTag 3339922

#define CATEGORYLIST @"服务", @"环境企划", @"环境物业",@"价格",@"质量",@"商户信用分类",@"审批比价采购",@"送货跟单",@"指标",@"其他", nil
#define QUESTIONLIST @"15分钟退单", @"便民服务", @"基础管理",@"轻松购系统",@"全员服务",@"人员信息",@"营运物流及服务硬件", nil


#define kAddQuestionCell @"UITableViewCellIdentifier"

@interface AddQuestionViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) AddQuestionFooterView *footerView;
@property (nonatomic, strong) NSMutableArray *imageNameArray;
@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, strong) NSString *imageMD5;

@property (nonatomic, strong) UIActionSheet *categoryActionSheet;
@property (nonatomic, strong) UIActionSheet *questionActionSheet;

@property (nonatomic, strong) UIActionSheet *selectActionSheet;

@property (nonatomic ,strong) UILabel *selectLabel;
@property (nonatomic ,strong) UILabel *selectLabel1;
@property (nonatomic, assign) int rowNumber;

@property (nonatomic, strong) NSMutableDictionary *saveDict;

@property (nonatomic, strong) NSMutableArray *categoryArray;
@property (nonatomic, strong) NSMutableArray *questionArray;

@property (nonatomic, assign) NSInteger categoryNum;
@property (nonatomic, assign) NSInteger questionNum;

@property (nonatomic) BOOL isComplete;
@property (nonatomic) BOOL isLoad;
@property (nonatomic, strong) NSMutableDictionary *groupUuidDict;

@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation AddQuestionViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.categoryArray = [NSMutableArray array];
    self.questionArray = [NSMutableArray array];

    self.view.backgroundColor = kFootViewBackGroundColor;
    
    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;
    
    
    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.imageNameArray = [NSMutableArray array];

    self.titleArray = [NSArray arrayWithObjects:@"选择对应专业组", @"选择问题分类", nil];
    [self addTableView];

    
    // takePhoto代理
    [self.footerView.reportBtn addTarget:self action:@selector(upLoadQuestionPic:) forControlEvents:UIControlEventTouchUpInside];
    
    [self requestGroupTitle];
    
    _rowNumber = 4;
    _categoryNum = 0;
    _questionNum = 0;
    _isComplete = NO;
    _isLoad = NO;
}

// 请求问题专业组
- (void)requestGroupTitle
{
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:[NSString stringWithFormat:@"%@%@", kRedStarURL, kQuestionGroupURL]];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpClient getQuestionGroupWithCompletion:^(id response, NSError *error) {
        NSDictionary *dataDict = response[@"data"];
        NSArray *dataArray = dataDict[@"records"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        NSMutableArray *nameArray = [NSMutableArray array];
        for (NSDictionary *groupDict in dataArray) {
            NSString *name = [NSString stringWithFormat:@"%@", groupDict[@"name"]];
            NSString *groupUuid = [NSString stringWithFormat:@"%@", groupDict[@"uuid"]];
            [dict setObject:groupUuid forKey:name];
            [nameArray addObject:name];
        }
        _groupUuidDict = dict;
        _categoryArray = nameArray;
        _isComplete = YES;
        
        if (nameArray.count != 0) {
            NSString *nameStr = [NSString stringWithFormat:@"%@", nameArray[0]];
            [self requestCategoryWithGroupUuid:[dict objectForKey:nameStr]];
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [self.tableView reloadData];
    }];
}

- (void)requestCategoryWithGroupUuid:(NSString *)groupUuid
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",kRedStarURL, kQuestionCategoryURL, groupUuid];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    HttpClient *http = [[HttpClient alloc] initWithUrl:url];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [http getQuestionCategoryWithCompletion:^(id response, NSError *error) {
        NSDictionary *dictData = response[@"data"];
        NSArray *array = dictData[@"records"];
        NSMutableArray *categoryArray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            NSString *category = [NSString stringWithFormat:@"%@", dict[@"name"]];
            [categoryArray addObject:category];
        }
        _questionArray = categoryArray;
        _isLoad = YES;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.tableView reloadData];
    }];
}


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

#pragma mark - Private Methods

- (void)upLoadQuestionPic:(UIButton *)sender
{
    if ([_selectLabel.text isEqualToString:@"请选择"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请选择对应专业组" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    if ([_selectLabel1.text isEqualToString:@"请选择"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请选择问题分类" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要提交新问题吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 9211232;
    [alert show];
    
}

// 返回上一页面
- (void)doBack:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)showPicture:(UIButton *)sender
{
    LargePictureViewController *lager = [[LargePictureViewController alloc] init];
    lager.index = sender.tag - kPhotoTag;
    lager.pictureSaveMode = PictureLocalMode;
    lager.allImageArray = _imageNameArray;
    [self removeDeleteButton];
    [self.navigationController pushViewController:lager animated:YES];
    
//    CheckPicViewController *checkVC = [[CheckPicViewController alloc] init];
//    NSString *imageName = _imageNameArray[sender.tag - kPhotoTag];
//    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
//    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
//    checkVC.checkImage = image;
//    [self.navigationController pushViewController:checkVC animated:YES];
}

- (void)addTableView
{
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kAddQuestionCell];
    self.tableView.tableFooterView = self.footerView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)createImagePicker:(UIButton *)sender
{
    self.selectActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"直接拍照上传", @"从本地相册选择", nil];
    _selectActionSheet.delegate = self;
    _selectActionSheet.tag = 999283;
    [_selectActionSheet showInView:self.view];
    [self removeDeleteButton];
    
    if (sender.tag == 2201) {
        _rowNumber++;
    }
}



- (void)saveImage:(UIImage *)currentImage {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.01);
    
    NSString *imageName = [CommonFunc md5Data:imageData];
    [_imageNameArray addObject:imageName];
    
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)longClick:(UIGestureRecognizer *)longGR {
    
    // 获取到点击的显示图片的按钮
    UIButton *showButton = (UIButton *)longGR.view;
    NSLog(@"我长按了第%ld张图片", (showButton.tag - kPhotoTag));
    
    if (_deleteButton) {
        [_deleteButton removeFromSuperview];
        _deleteButton = nil;
    }
    
    if (!_deleteButton) {
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteButton.tag = 5521 + (showButton.tag - kPhotoTag);
        [deleteButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        deleteButton.backgroundColor = [UIColor whiteColor];
        deleteButton.bounds = CGRectMake(0, 0, 20, 20);
        [deleteButton addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
        deleteButton.frame = CGRectMake(showButton.frame.size.width - deleteButton.frame.size.width, 0, deleteButton.frame.size.width, deleteButton.frame.size.height);
        [showButton addSubview:deleteButton];
        _deleteButton = deleteButton;
    }
}

// 删除图片
- (void)deletePicture:(UIButton *)button
{
    NSLog(@"从imageName中删除了第%ld张图片",(button.tag - 5521));
    // 从存放所有Image的数组里移除当前点击的Image
    [self.imageNameArray removeObjectAtIndex:(button.tag - 5521)];
    
    if ((_imageNameArray.count + 1) % 2 == 0) {
        _rowNumber--;
        [self.tableView reloadData];
    } else {
        [self.tableView reloadData];
    }
    [button removeFromSuperview];
    button = nil;
    
    [self removeDeleteButton];
   
}

- (void)removeDeleteButton {
    if (_deleteButton) {
        [_deleteButton removeFromSuperview];
        _deleteButton = nil;
    }
}

#pragma mark - UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image];
    
    // 退出图片选择控制器
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.tableView reloadData];
    }];
    
}

#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    AddQuestionTableCell *cell = (AddQuestionTableCell *)[_tableView cellForRowAtIndexPath:indexPath];

    if (![text isEqualToString:@""]) {
        if (textView.tag == 1001) {
            cell.placeholderLabel1.hidden = YES;
        } else {
            cell.placeholderLabel2.hidden = YES;
        }
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        if (textView.tag == 1001) {
            cell.placeholderLabel1.hidden = NO;
        } else {
            cell.placeholderLabel2.hidden = NO;
        }
    }
    
    if ([text isEqualToString:@"\n"]) {
        [cell.titleTextView resignFirstResponder];
        [cell.contentTextView resignFirstResponder];
        
        if (textView.tag == 1001) {
            if (textView.text.length != 0) {
                cell.placeholderLabel1.hidden = YES;
            } else {
                cell.placeholderLabel1.hidden = NO;
            }
        } else {
            if (textView.text.length != 0) {
                cell.placeholderLabel2.hidden = YES;
            } else {
                cell.placeholderLabel2.hidden = NO;
            }
        }
        return NO;
    }
    
    if (range.location>=500) {
        return  NO;
    }
    else {
        return YES;
    }
    
    
    return YES;
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 90393) {
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];
            NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
            [notification postNotificationName:kRefreshQuestionNotification object:self];
        }
    } else if (alertView.tag == 9211232) {
        if (buttonIndex == 0) {
            return;
        } else {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
            
            AddQuestionTableCell *cell = (AddQuestionTableCell *)[_tableView cellForRowAtIndexPath:indexPath];
            
            NSString *title = [cell titleTextView].text;
            NSString *content = [cell contentTextView].text;
            
            NSDictionary *parameters;
            if (_imageNameArray.count == 0) {
                parameters = @{@"category":_selectLabel1.text,
                               @"group":_selectLabel.text,
                               @"title":content,
                               @"content":title
                               };
            } else {
                NSMutableArray *imageArray = [NSMutableArray array];
                for (int i = 0; i < _imageNameArray.count; i++) {
                    NSString *imageName = _imageNameArray[i];
                    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
                    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
                    NSData *imageData = UIImageJPEGRepresentation(image, 0.01);
                    NSString *imageBase64 = [imageData base64EncodedStringWithOptions:0];
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    [dict setObject:imageBase64 forKey:@"fileContent"];
                    [dict setObject:imageName forKey:@"fileName"];
                    [dict setObject:@(i) forKey:@"index"];
                    [imageArray addObject:dict];
                }
                
                parameters = @{@"category":_selectLabel1.text,
                               @"group":_selectLabel.text,
                               @"title":content,
                               @"content":title,
                               @"attachments":imageArray};
            }
            
            
            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, kUpLoadQuestionURL, dateString, operId, operName];
            url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            
            HttpClient *client = [[HttpClient alloc] initWithUrl:url];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [client uploadNewQuestionWithParameters:parameters completion:^(id response, NSError *error) {
                                
                if ([response[@"success"] boolValue]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新问题提报成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alert.tag = 90393;
                    [alert show];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                } else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"新问题提报失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }];
        }
    }
}



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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 2) {
        
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kAddQuestionCell];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAddQuestionCell];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"%@", _titleArray[indexPath.row]];
        cell.textLabel.font = [UIFont systemFontOfSize:16.0];
        cell.textLabel.textColor = kOnLineCellTitleColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15, 49, kScreenWidth, 1)];
        line.backgroundColor = kSeparateLineColor;
        [cell.contentView addSubview:line];
        
        NSString *cateStr = nil;
        
        if (_categoryArray.count != 0) {
            if (_isComplete) {
                cateStr = _categoryArray[_categoryNum];
            } else {
                cateStr = @"";
            }
        } else {
            cateStr = @"";
        }
        
        
        if (indexPath.row == 0) {
            if (!self.selectLabel) {
                _selectLabel = [[UILabel alloc] init];
            }
            _selectLabel.text = cateStr;
            _selectLabel.translatesAutoresizingMaskIntoConstraints = NO;
            _selectLabel.textColor = kOnLineCellDetailColor;
            _selectLabel.textAlignment = NSTextAlignmentRight;
            _selectLabel.translatesAutoresizingMaskIntoConstraints = NO;
            _selectLabel.font = [UIFont systemFontOfSize:15.0];
            [cell.contentView addSubview:_selectLabel];
            // 顶端
            NSLayoutConstraint *selectTop = [NSLayoutConstraint constraintWithItem:_selectLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectTop];
            
            // 左边
            NSLayoutConstraint *selectRight = [NSLayoutConstraint constraintWithItem:_selectLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectRight];
            
            // 高度
            NSLayoutConstraint *selectBottom = [NSLayoutConstraint constraintWithItem:_selectLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectBottom];
            
            // 高度
            NSLayoutConstraint *selectHeight = [NSLayoutConstraint constraintWithItem:_selectLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:50];
            [cell.contentView addConstraint:selectHeight];

        } else {
            if (!self.selectLabel1) {
                self.selectLabel1 = [[UILabel alloc] init];
            }
            
            if (_questionArray.count != 0) {
                if (_isLoad) {
                    _selectLabel1.text = _questionArray[_questionNum];
                } else {
                    _selectLabel1.text = @"";
                }
            } else {
                _selectLabel1.text = @"";
            }
            
            
            
            _selectLabel1.translatesAutoresizingMaskIntoConstraints = NO;
            _selectLabel1.textColor = kOnLineCellDetailColor;
            _selectLabel1.textAlignment = NSTextAlignmentRight;
            _selectLabel1.translatesAutoresizingMaskIntoConstraints = NO;
            _selectLabel1.font = [UIFont systemFontOfSize:15.0];
            [cell.contentView addSubview:_selectLabel1];
            // 顶端
            NSLayoutConstraint *selectTop = [NSLayoutConstraint constraintWithItem:_selectLabel1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectTop];
            
            // 左边
            NSLayoutConstraint *selectRight = [NSLayoutConstraint constraintWithItem:_selectLabel1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectRight];
            
            // 高度
            NSLayoutConstraint *selectBottom = [NSLayoutConstraint constraintWithItem:_selectLabel1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
            [cell.contentView addConstraint:selectBottom];
            
            // 高度
            NSLayoutConstraint *selectHeight = [NSLayoutConstraint constraintWithItem:_selectLabel1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:50];
            [cell.contentView addConstraint:selectHeight];

        }
        return cell;
    } else if (indexPath.row == 2){
        AddQuestionTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"kAddQuestionCell"];
        if (!cell) {
            cell = [[AddQuestionTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"kAddQuestionCell"];
        }
        cell.titleTextView.delegate = self;
        cell.contentTextView.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    } else if (indexPath.row == _rowNumber - 1) {
        if ((_imageNameArray.count + 1) % 2 == 0) {
            NSString *identifier = [NSString stringWithFormat:@"InspectaddPicCell"];
            InspectPicAddCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[InspectPicAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            NSString *imageName = _imageNameArray[_imageNameArray.count - 1];
            NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
            UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
            UIImage *image00 = [UIImage image:image fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
            cell.photoButton1.tag = kPhotoTag + _imageNameArray.count - 1;
            [cell.photoButton1 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];

            [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
            
            cell.photoButton2.tag = 2201;
            [cell.photoButton2 addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            // 添加长按手势
            UILongPressGestureRecognizer *longGR1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
            [cell.photoButton1 addGestureRecognizer:longGR1];
            
            return cell;
        } else {
            
            NSString *identifier = [NSString stringWithFormat:@"InspectaddCell"];
            InspectAddCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[InspectAddCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            cell.photoButton.tag = 2200;
            [cell.photoButton addTarget:self action:@selector(createImagePicker:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
        
        
    } else {
        
        NSString *identifier = [NSString stringWithFormat:@"InspectPictureCell"];
        InpectPictureCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[InpectPictureCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        NSString *imageName0 = _imageNameArray[(indexPath.row - 3) * 2];
        NSString *fullPath0 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName0];
        UIImage *image0 = [UIImage imageWithContentsOfFile:fullPath0];
        UIImage *image00 = [UIImage image:image0 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
        [cell.photoButton1 setImage:image00 forState:UIControlStateNormal];
        
        NSString *imageName1 = _imageNameArray[(indexPath.row - 3) * 2 + 1];
        NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName1];
        UIImage *image1 = [UIImage imageWithContentsOfFile:fullPath1];
        UIImage *image11 = [UIImage image:image1 fillSize:CGSizeMake((kScreenWidth - 60) / 2, 90)];
        [cell.photoButton2 setImage:image11 forState:UIControlStateNormal];
        
        [cell.photoButton1 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];
        cell.photoButton1.tag = kPhotoTag + (indexPath.row - 3) * 2;
        
        [cell.photoButton2 addTarget:self action:@selector(showPicture:) forControlEvents:UIControlEventTouchUpInside];
        cell.photoButton2.tag = kPhotoTag + (indexPath.row - 3) * 2 + 1;
        
        // 添加长按手势
        UILongPressGestureRecognizer *longGR1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
        [cell.photoButton1 addGestureRecognizer:longGR1];
        
        UILongPressGestureRecognizer *longGR2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
        [cell.photoButton2 addGestureRecognizer:longGR2];

        return cell;
    }

    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        self.categoryActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
        
        for (NSString *groupName in _categoryArray) {
            [_categoryActionSheet addButtonWithTitle:groupName];
        }
        
        _categoryActionSheet.delegate = self;
        [_categoryActionSheet showInView:self.view];

    } else if (indexPath.row == 1) {
        self.questionActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    
        for (NSString *selectStr in _questionArray) {
            [_questionActionSheet addButtonWithTitle:selectStr];
        }
        
        _questionActionSheet.delegate = self;
        [_questionActionSheet showInView:self.view];
    } else {
        return;
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 999283) {
        if (buttonIndex == 0) {
            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];
            }
        } else if (buttonIndex == 1){
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            //设置选择后的图片可被编辑
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    
    
    if (actionSheet == _categoryActionSheet) {
        
        if ((buttonIndex -1) < _categoryArray.count) {
            _selectLabel.text = [_categoryArray objectAtIndex:(buttonIndex -1)];
            _categoryNum = (buttonIndex -1);
            NSString *groupUuid = [_groupUuidDict objectForKey:_selectLabel.text];
            _isLoad = NO;
            [self requestCategoryWithGroupUuid:groupUuid];
            _questionNum = 0;
            [self.tableView reloadData];
        }
    } else if (actionSheet == _questionActionSheet){
        
        if ((buttonIndex -1) < _questionArray.count) {
            _selectLabel1.text = [_questionArray objectAtIndex:(buttonIndex -1)];
            _questionNum = buttonIndex - 1;
        }
    }
}


#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 = 100.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;
}

- (AddQuestionFooterView *)footerView
{
    if (!_footerView) {
        _footerView = [[AddQuestionFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 65)];
    }
    return _footerView;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.tableView endEditing:YES];
}




@end
