//
//  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 "CommonFunc.h"
#import "HttpClient.h"
#import <MBProgressHUD.h>

#define CATEGORYLIST @"服务", @"环境企划", @"环境物业", nil
#define QUESTIONLIST @"15分钟退单", @"便民服务", @"基础管理",@"轻松购系统",@"全员服务",@"人员信息",@"营运物流及服务硬件", nil


#define kAddQuestionCell @"UITableViewCellIdentifier"

@interface AddQuestionViewController () <UITableViewDelegate, UITableViewDataSource, TakePhotoViewDelegate, 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) UILabel *selectLabel;
@property (nonatomic ,strong) UILabel *selectLabel1;


@end

@implementation AddQuestionViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    
    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.takePhotoView.delegate = self;
    [self.footerView.reportBtn addTarget:self action:@selector(upLoadQuestionPic:) forControlEvents:UIControlEventTouchUpInside];
}

- (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;
    }
    
    
    
    NSDictionary *parameters;
    if (_imageNameArray.count == 0) {
        parameters = @{@"category":_selectLabel.text,
                       @"group":_selectLabel1.text,
                       @"title":self.footerView.contentTextView.text,
                       @"content":self.footerView.titleTextView.text
                       };
    } 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.5);
            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":_selectLabel.text,
                       @"group":_selectLabel1.text,
                       @"title":self.footerView.contentTextView.text,
                       @"content":self.footerView.titleTextView.text,
                       @"attachments":imageArray};
    }
    
    NSLog(@"par = %@", parameters);
    
    
    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) {
        NSLog(@"上传新问题 response= %@， error = %@", response, error);
        if (response[@"success"]) {
            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];
        }
    }];
    
}

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


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



#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 && alertView.tag == 90393) {
        [self.navigationController popViewControllerAnimated:YES];
        NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
        [notification postNotificationName:kRefreshQuestionNotification object:self];
    }
}


#pragma mark - TakePhoto Delegate
- (void)deletePhoto:(UIButton *)button
{
    // 从存放所有Image的数组里移除当前点击的Image
    [self.footerView.takePhotoView.allImages removeObject:[(UIButton *)button.superview imageForState:UIControlStateNormal]];
    // 移除显示Image的Button
    [button.superview removeFromSuperview];
    
    CGFloat btnH = 110;
    CGFloat marginY = 10;
    int count = (int)self.footerView.takePhotoView.allImages.count + 1;
    int k ;
    if (count % 2 == 0) {
        k = count / 2;
    } else {
        k = (count + 1) / 2;
    }
    self.footerView.takePhotoView.frame = CGRectMake(0, 170, kScreenWidth, k * btnH + (k + 1) * marginY);
    self.footerView.height = self.footerView.takePhotoView.frame.size.height + 220;
    
    NSString *imageName = _imageNameArray[button.superview.tag - 1];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:fullPath];
    if (!blHave) {
        return ;
    } else {
        BOOL blDele= [fileManager removeItemAtPath:fullPath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
    }
    
}

- (void)createImagePicker
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to find the camera" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
    } else {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)takePhotoShowPicture:(UIButton *)btn
{
    CheckPicViewController *checkVC = [[CheckPicViewController alloc] init];
    checkVC.checkImage = btn.imageView.image;
    [self.navigationController pushViewController:checkVC animated:YES];
}

#pragma mark - 保存图片至沙盒
- (void)saveImage:(UIImage *)currentImage {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    NSString *imageName = [CommonFunc md5Data:imageData];
    [_imageNameArray addObject:imageName];
    
    
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}
#pragma mark - UIImagePickerController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image];
    // 创建一个新的控件
    UIButton *newButton = [self.footerView.takePhotoView createButtonWithImage:image];
    [newButton addTarget:self action:@selector(takePhotoShowPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.footerView.takePhotoView insertSubview:newButton atIndex:self.footerView.takePhotoView.subviews.count - 1];
    [self.footerView.takePhotoView.allImages addObject:image];
    
    int count = (int)self.footerView.takePhotoView.allImages.count + 1;
    int k ;
    if (count % 2 == 0) {
        k = count / 2;
    } else {
        k = (count + 1) / 2;
    }
    
    CGFloat btnH = 110;
    CGFloat marginY = 10;
    self.footerView.takePhotoView.frame = CGRectMake(0, 170, kScreenWidth, k * btnH + (k + 1) * marginY);
    self.footerView.height = self.footerView.takePhotoView.frame.size.height + 220;
    // 退出图片选择控制器
    [picker dismissViewControllerAnimated:YES completion:nil];

}

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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    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;
    
    if (indexPath.row == 0) {
        self.selectLabel = [[UILabel alloc] init];
        _selectLabel.text = @"请选择";
        _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];
    } else {
        self.selectLabel1 = [[UILabel alloc] init];
        _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];
    }
    
    

    return cell;
    
    
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

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

    } else {
        self.questionActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:QUESTIONLIST];
        _questionActionSheet.delegate = self;
        [_questionActionSheet showInView:self.view];
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet == _categoryActionSheet) {
        
        if (buttonIndex < [NSArray arrayWithObjects:CATEGORYLIST].count) {
            _selectLabel.text = [[NSArray arrayWithObjects:CATEGORYLIST] objectAtIndex:buttonIndex];
        }
    } else {
        if (buttonIndex < [NSArray arrayWithObjects:QUESTIONLIST].count) {
            _selectLabel1.text = [[NSArray arrayWithObjects:QUESTIONLIST] objectAtIndex:buttonIndex];
        }
    }
}


#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;
        [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) {
        if (kScreenHeight == 480) {
            _footerView = [[AddQuestionFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 400)];
        } else {
            _footerView = [[AddQuestionFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, (kScreenHeight - 100 - 64))];
        }
        _footerView.titleTextView.delegate = self;
        _footerView.contentTextView.delegate = self;
    }
    return _footerView;
}

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

#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (![text isEqualToString:@""]) {
        if (textView.tag == 1001) {
            self.footerView.placeholderLabel1.hidden = YES;
        } else {
            self.footerView.placeholderLabel2.hidden = YES;
        }
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        if (textView.tag == 1001) {
            self.footerView.placeholderLabel1.hidden = NO;
        } else {
            self.footerView.placeholderLabel2.hidden = NO;
        }
    }
    
    if ([text isEqualToString:@"\n"]) {
        [self.footerView.titleTextView resignFirstResponder];
        [self.footerView.contentTextView resignFirstResponder];
        
        if (textView.text.length != 0) {
            self.footerView.placeholderLabel1.hidden = YES;
            self.footerView.placeholderLabel2.hidden = YES;
        } else {
            self.footerView.placeholderLabel1.hidden = NO;
            self.footerView.placeholderLabel2.hidden = NO;
        }
        return NO;
    }
    
    
    return YES;
}


@end
