//
//  OnLineResultViewController.m
//  redstar
//
//  Created by admin on 15/12/9.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "OnLineResultViewController.h"
#import "OnLineResultDetailCell.h"
#import "OnLineResultFootView.h"
#import "LargePictureViewController.h"

#import "CommentWithStarView.h"
#import "StoreDetailModel.h"
#import "HttpClient.h"

#define kOnLineResultDetailCell @"lookOnLineResultDetailCell"

@interface OnLineResultViewController () <UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, UIAlertViewDelegate, OnLineResultFootViewDelegate, OnLineResultDetailCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) OnLineResultFootView *footView;

@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, strong) CommentWithStarView *commentView;

@property (nonatomic,strong) NSMutableArray *allImageURL;
@property (nonatomic,strong) NSMutableArray *allStoreImageURL;
@end

@implementation OnLineResultViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNav];
    
    self.allImageURL = [NSMutableArray array];
    self.allStoreImageURL = [NSMutableArray array];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = self.footView;
    
    // 现场照片
    for (int i = 0; i < _storeDetail.attachments.count; i++) {
        NSDictionary *dict = (NSDictionary *)_storeDetail.attachments[i];
        NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kRedStarURL ,dict[@"fileUrl"]]];
        [_allImageURL addObject:imageUrl];
    }
    // 现场照片
    
    if (_storeDetail.storePictures.count == 0) {
        
        for (int i = 0; i < 4; i++) {
            NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", kRedStarURL]];
            [_allStoreImageURL addObject:imageUrl];
        }
        
    } else {
        for (int i = 0; i < _storeDetail.storePictures.count; i++) {
            NSDictionary *dict = (NSDictionary *)_storeDetail.storePictures[i];
            NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kRedStarURL ,dict[@"fileUrl"]]];
            [_allStoreImageURL addObject:imageUrl];
        }
    }
}

#pragma mark - Private Mothods
- (void)setupNav
{
    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;
}

- (void)doBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)returnClick:(UIButton *)sender
{
    if ([_storeDetail.state isEqualToString:@"initial"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未上报的商场不能打分评论！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    } else {
        if (!_backGroundView) {
            _backGroundView = [[UIView alloc] initWithFrame:self.view.bounds];
            UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBackGroundView)];
            [_backGroundView addGestureRecognizer:tapGR];
        }
        if (!_commentView) {
            _commentView = [[CommentWithStarView alloc] init];
            _commentView.backgroundColor = [UIColor whiteColor];
        }
        _commentView.contentTextView.text = @"";
        _commentView.contentTextView.delegate = self;
        [_commentView.quitBtn addTarget:self action:@selector(closeBackGroundView) forControlEvents:UIControlEventTouchUpInside];
        [_commentView.sureBtn addTarget:self action:@selector(submitComment:) forControlEvents:UIControlEventTouchUpInside];
        [self.view insertSubview:_backGroundView aboveSubview:_tableView];
        [self.view insertSubview:_commentView aboveSubview:_backGroundView];
        
        _backGroundView.alpha = 0;
        _backGroundView.backgroundColor = [UIColor blackColor];
        
        CGRect toFrame = CGRectMake(0, self.view.frame.size.height - kCommentWithStarViewHeight, kScreenWidth, kCommentWithStarViewHeight);
        CGRect fromFrame = CGRectMake(0, kScreenHeight, kScreenWidth, kCommentWithStarViewHeight);
        
        _commentView.frame = fromFrame;
        [UIView animateWithDuration:0.3 animations:^{
            _backGroundView.alpha = 0.6;
            _commentView.frame = toFrame;
        }];
    }
}

// 提交评论
- (void)submitComment:(UIButton *)sender
{
    // 提示框
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要提交评论吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 3699534;
    alert.delegate = self;
    [alert show];
}

- (void)closeBackGroundView
{
    CGRect fromFrame = CGRectMake(0, kScreenHeight, kScreenWidth, kCommentWithStarViewHeight);
    [UIView animateWithDuration:0.3 animations:^{
        _backGroundView.alpha = .0f;
        _commentView.frame = fromFrame;
    } completion:^(BOOL finished) {
        [_backGroundView removeFromSuperview];
        [_commentView removeFromSuperview];
    }];
}

#pragma mark - OnLineFooterViewDelegate
- (void)showOnLinePicture:(UITapGestureRecognizer *)sender
{
    // 获取到点击的显示图片的按钮
    UIImageView *imageView = (UIImageView *)sender.view;
    LargePictureViewController *largeVC = [[LargePictureViewController alloc] init];
    largeVC.index = imageView.tag - 1116;
    largeVC.allImageArray = _allImageURL;
    [self.navigationController pushViewController:largeVC animated:YES];
}

- (void)showOnLineStorePicture:(UIButton *)sender
{
    LargePictureViewController *largeVC = [[LargePictureViewController alloc] init];
    largeVC.index = sender.tag - 1117;
    largeVC.allImageArray = _allStoreImageURL;
    [self.navigationController pushViewController:largeVC animated:YES];
}

#pragma mark - UITextView Delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.3 animations:^{
        _commentView.frame = CGRectMake(0, self.view.frame.size.height - kCommentWithStarViewHeight - 173, kScreenWidth, kCommentWithStarViewHeight);
    }];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.3 animations:^{
        _commentView.frame = CGRectMake(0, self.view.frame.size.height - kCommentWithStarViewHeight, kScreenWidth, kCommentWithStarViewHeight);
    }];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if (![text isEqualToString:@""]) {
        _commentView.placeholderLabel2.hidden = YES;
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1) {
        _commentView.placeholderLabel2.hidden = NO;
    }
    
    if ([text isEqualToString:@"\n"]) {
        [_commentView.contentTextView resignFirstResponder];
        if (textView.text.length != 0) {
            _commentView.placeholderLabel2.hidden = YES;
        } else {
            _commentView.placeholderLabel2.hidden = NO;
        }
        return NO;
    }
    
    if (range.location>=500) {
        return  NO;
    } else {
        return YES;
    }
}

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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OnLineResultDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:kOnLineResultDetailCell];
    if (!cell) {
        cell = [[OnLineResultDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kOnLineResultDetailCell storePictures:_storeDetail.storePictures];
    }
    cell.contentView.backgroundColor = kResultTitleBackColor;
    cell.delegate = self;
    cell.shopNameLabel.text = [NSString stringWithFormat:@"%@", _storeDetail.store_name];
    cell.whiteView.backgroundColor = [UIColor whiteColor];
    if (_storeDetail.storeAddress == nil || _storeDetail.storeAddress == NULL || [_storeDetail.storeAddress isEqual:[NSNull null]] || _storeDetail.storeAddress == Nil || [_storeDetail.storeAddress isEqualToString:@"(null)"]) {
        cell.addressLabel.text = @"";
    } else {
        cell.addressLabel.text = [NSString stringWithFormat:@"%@", _storeDetail.storeAddress];
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

#pragma mark - UIAlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3699534) {
        if (buttonIndex == 1) {
            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:@"%@%@%@&operId=%@&operName=%@", kRedStarURL, kGradeCheckResultURL, dateString, operId, operName];
            url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            HttpClient *httpClient= [[HttpClient alloc] initWithUrl:url];
            
            NSDictionary *parameters = @{
                                         @"checkUuid":self.checkUuid,
                                         @"storeUuid":_storeDetail.store_uuid,
                                         @"score":@(_commentView.starBar.starNumber),
                                         @"comment":_commentView.contentTextView.text,
                                         };
            [httpClient gradeCheckResultWithParameters:parameters completion:^(id response, NSError *error) {
                
                if ([response[@"message"] isEqualToString:@"ok"]) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];

        }
    }
}

#pragma mark - lazy loading
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 200.0;
       // [_tableView registerClass:[OnLineResultDetailCell class] forCellReuseIdentifier:kOnLineResultDetailCell];
        [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;
}

- (OnLineResultFootView *)footView
{
    if (!_footView) {
        _footView = [[OnLineResultFootView alloc] initWithPicArray:_storeDetail.attachments];
        _footView.textView.text = _storeDetail.processNote;
        _footView.delegate = self;
        if ([_storeDetail.state isEqualToString:@"finished"]) {
            [_footView.returnButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
            [_footView.returnButton setTitle:@"返回上一页" forState:UIControlStateNormal];
            _footView.textView.userInteractionEnabled = NO;
        } else {
            [_footView.returnButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_footView.returnButton setTitle:@"打分评论" forState:UIControlStateNormal];
            _footView.textView.userInteractionEnabled = YES;
        }
    }
    return _footView;
}



@end
