//
//  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 "CommentWithStarView.h"
#import "StoreDetailModel.h"
#import "HttpClient.h"

#define kOnLineResultDetailCell @"lookOnLineResultDetailCell"

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

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

@end

@implementation OnLineResultViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNav];
    
    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;
}

#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 (!_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 - 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];
    }
    cell.contentView.backgroundColor = kResultTitleBackColor;
    cell.shopNameLabel.text = [NSString stringWithFormat:@"%@", _storeDetail.store_name];
    cell.whiteView.backgroundColor = [UIColor whiteColor];
    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];
            NSLog(@"抽查评分 = %@", url);
            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) {
                NSLog(@"抽查评分的 response = %@", response);
                NSLog(@"抽查评分的 error = %@", 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.storePictures];
        [_footView.returnButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
        _footView.textView.text = _storeDetail.processNote;
    }
    return _footView;
}



@end
