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

#import "CheckResultChangeViewController.h"

@interface CheckResultChangeViewController ()< UIGestureRecognizerDelegate,UITextFieldDelegate>
{
    UILabel* lblCheckRange;
    UILabel* lblCheckTime;
   
}
@property (nonatomic, strong) UIView *descView;
@property (nonatomic, strong) NSMutableArray *remarkArr;
@property (nonatomic, strong) NSMutableArray *scroeArr;
@end

typedef void(^selectRowAtIndex)(UITextField* filed,UITextField* filed1);
@interface CheckResultChangeViewCell : UITableViewCell
@property (nonatomic, copy) selectRowAtIndex BtnClickBlock;
@property (nonatomic, strong) UILabel *lblSmallAreaName;
@property (nonatomic, strong) UILabel *lblCheckResult;
@property (nonatomic, strong) UITextField *checkResultForSelfTextField;
@property (nonatomic, strong) UITextField *evaluateTextField;
@end

@implementation CheckResultChangeViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _remarkArr = [[NSMutableArray alloc] init];
    _scroeArr = [[NSMutableArray alloc] init];
    self.navigationItem.title = @"抽查结果";
    
    _descView = [[UIView alloc] init];
    _descView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_descView];
    [_descView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeBottom];
    [_descView autoSetDimension:ALDimensionHeight toSize:70];
    
    
    UILabel* lblCheckRangePre = [[UILabel alloc] init];
    lblCheckRangePre.textColor = [UIColor darkGrayColor];
    lblCheckRangePre.font = [UIFont systemFontOfSize:13];
    lblCheckRangePre.text = @"抽查范围:";
    [_descView addSubview:lblCheckRangePre];
    [lblCheckRangePre autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:13];
    [lblCheckRangePre autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
    
    lblCheckRange = [[UILabel alloc] init];
    lblCheckRange.textColor = [UIColor darkGrayColor];
    lblCheckRange.font = [UIFont systemFontOfSize:13];
    lblCheckRange.text = @"2015-03-23 ~ 2015-06-27";
    [_descView addSubview:lblCheckRange];
    [lblCheckRange autoAlignAxis:ALAxisHorizontal toSameAxisOfView:lblCheckRangePre];
    [lblCheckRange autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:lblCheckRangePre withOffset:5];
    
    UILabel* lblCheckTimePre = [[UILabel alloc] init];
    lblCheckTimePre.textColor = [UIColor darkGrayColor];
    lblCheckTimePre.font = [UIFont systemFontOfSize:13];
    lblCheckTimePre.text = @"抽查时间:";
    [_descView addSubview:lblCheckTimePre];
    [lblCheckTimePre autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:lblCheckRangePre withOffset:8];
    [lblCheckTimePre autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
    
    lblCheckTime = [[UILabel alloc] init];
    lblCheckTime.textColor = [UIColor darkGrayColor];
    lblCheckTime.font = [UIFont systemFontOfSize:13];
    lblCheckTime.text = @"2015-03-23  16:40";
    [_descView addSubview:lblCheckTime];
    [lblCheckTime autoAlignAxis:ALAxisHorizontal toSameAxisOfView:lblCheckTimePre];
    [lblCheckTime autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:lblCheckTimePre withOffset:5];
    
    self.tableVContent.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self registObserverOfTextInputView];
    [self setViewLayoutConstraint];
    
    //    UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [btnHome setBackgroundImage:[UIImage imageNamed:@"NavBar/btn_nav_home.png"] forState:UIControlStateNormal];
    //    [btnHome setFrame:CGRectMake(0, 0, 25, 25)];
    //    [btnHome addTarget:self action:@selector(btnHomeClick) forControlEvents:UIControlEventTouchUpInside];
    //
    //    [self.navigationController navbarRightItemCustomized:@[btnHome] onwer:self.navigationItem];
    
    UIButton* btnSubmit = [[UIButton alloc] init];
    [btnSubmit setBackgroundColor:RGBColor(3, 119, 193, 1)];
    [btnSubmit setTintColor:[UIColor whiteColor]];
    [btnSubmit setTitle:@"提交评分结果" forState:UIControlStateNormal];
    btnSubmit.titleLabel.font = [UIFont systemFontOfSize:15];
    btnSubmit.layer.cornerRadius = 5;
    [btnSubmit addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSubmit];
    [btnSubmit autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 15, 10, 15) excludingEdge:ALEdgeTop];
    [btnSubmit autoSetDimension:ALDimensionHeight toSize:35];
    
    [self requestDatas];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    if ([[UIApplication getObjectType:Number key:kShouldRequestDataWhenBack] boolValue]) {
    //        [self requestDatas];
    //    }
}

- (void)setViewLayoutConstraint
{
    [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 60, 0) excludingEdge:ALEdgeTop];
    [self.tableVContent autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_descView];
}

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

- (void)btnBackClick:(id)sender
{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:NSClassFromString(@"spotCheckViewController")]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}

- (void)submitClick
{
    NSArray* arrThirdParts = [self getArr];
    
    
    NSString *strParam = @"";
    if ([NSJSONSerialization isValidJSONObject:arrThirdParts]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrThirdParts
                                                           options:NSJSONWritingPrettyPrinted error:&error];
        strParam = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        DLog(@"strParam  %@", strParam);
    }
    
    NSDictionary *dicParam = @{@"surveyId":self.surveyID,
                               @"areaScoreList":strParam};
    [UIApplication showLoadingView:kTextShowInProgress];
    
    NSString *interface = @"updateSubjectiveScoreEX";
    
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                                interface:interface
                                                                   params:dicParam
                                                                 dataType:BRNetMgrDataTypeJSON
                                                                   method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
    
}

-(void)submitClick1
{
    NSDictionary *dicParam = @{
                               @"areaScoreList":[self getArr],
                               @"surveyId":self.surveyID};
    
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"updateSubjectiveScoreEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

-(NSArray*)getArr
{
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    
    
    
    for (int i = 0; i < self.arrContents.count; i++) {
//        NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:
//                             [NSString stringWithFormat:@"%@",self.arrContents[i][@"surveyScoreId"]],@"surveyScoreId",
//                             @"2",@"subjectiveScore",
//                             [NSString stringWithFormat:@"%d",i],@"remark", nil];
        
        NSDictionary* dic = [_scroeArr objectAtIndex:i];
        NSDictionary* dic1 = [_remarkArr objectAtIndex:i];
        
        NSDictionary *dictParam = @{@"surveyScoreId":[NSString stringWithFormat:@"%@",self.arrContents[i][@"surveyScoreId"]],
                                    @"subjectiveScore":[NSString stringWithFormat:@"%@",[dic objectForKey:@"scroe"]],
                                    @"remark":[NSString stringWithFormat:@"%@",[dic1 objectForKey:@"remark"]]};
        
        [arr addObject:dictParam];
    }

    return arr;
}

- (void)requestDatas
{
        NSDictionary *dicParam = @{@"surveyId":self.surveyID};
    
        [UIApplication showLoadingView:kTextShowInProgress];
        NSString *interface = @"querySurveyResultEX";
    
        NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                         interface:interface
                                                            params:dicParam
                                                          dataType:BRNetMgrDataTypeJSON
                                                            method:BRNetMgrMethodPost];
        [self.networkMgr startOperation:operation];
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"querySurveyResultEX"])
    {
        lblCheckRange.text = [NSString stringWithFormat:@"%@ ~ %@",result[@"surveyStartDate"],result[@"surveyEndDate"]];
        lblCheckTime.text = result[@"surveyTime"];
        
        self.arrContents = [result[@"areaScoreList"] validDataOfClass:[NSMutableArray class]];

        for (int i = 0; i < self.arrContents.count; i++) {
            NSDictionary* dic = @{@"remark":self.arrContents[i][@"remark"],@"tag":[NSString stringWithFormat:@"%d",i]};
            NSDictionary* dic1 = @{@"scroe":self.arrContents[i][@"score"],@"tag":[NSString stringWithFormat:@"%d",i]};
            [_remarkArr addObject:dic];
            [_scroeArr addObject:dic1];
        }
        
        [self.tableVContent reloadData];
        
        if (self.arrContents.count == 0) {
            self.imageVNoResult.hidden = NO;
        }
        else
        {
            self.imageVNoResult.hidden = YES;
        }
    }
    if ([operation.userInfo[@"interface"] isEqualToString:@"updateSubjectiveScoreEX"])
    {
        [UIApplication saveObject:@YES type:Number key:kShouldRequestDataWhenBack];
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:NSClassFromString(@"spotCheckViewController")]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }

}

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




- (void)configureCell:(CheckResultChangeViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
    cell.lblSmallAreaName.text = self.arrContents[indexPath.row][@"areaName"];
    cell.lblCheckResult.text = [NSString stringWithFormat:@"%@",self.arrContents[indexPath.row][@"score"]];
    cell.checkResultForSelfTextField.text = [NSString stringWithFormat:@"%@",self.arrContents[indexPath.row][@"score"]];
}

#pragma mark =============  UITableView DataSource  =============

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"TaskListCell";
    CheckResultChangeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[CheckResultChangeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
    }
    [self configureCell:cell forIndexPath:indexPath];
    cell.checkResultForSelfTextField.delegate = self;
    cell.evaluateTextField.delegate = self;
    cell.checkResultForSelfTextField.tag = 20+indexPath.row;
    cell.evaluateTextField.tag = 999+indexPath.row;
    [cell.checkResultForSelfTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [cell.evaluateTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    __weak typeof(CheckResultChangeViewController) *weakSelf = self;
    cell.BtnClickBlock = ^(UITextField* filed,UITextField* filed1) {
        [weakSelf regesite:filed and:filed1];
    };

    
    return cell;
}
-(void)regesite:(UITextField*) filed and:(UITextField* )filed1
{
    [self.view endEditing:YES];
}
-(void)textFieldDidChange:(UITextField*)textField
{
//    if (textField.tag >= 999) {
//        [_remarkArr removeObjectAtIndex:textField.tag-999];
//        NSDictionary* dic = @{@"remark":textField.text,@"tag":[NSString stringWithFormat:@"%d",textField.tag-999]};
//        [_remarkArr insertObject:dic atIndex:textField.tag-999];
//    }
//    else
//    {
//        [_scroeArr removeObjectAtIndex:textField.tag-20];
//        NSDictionary* dic = @{@"scroe":textField.text,@"tag":[NSString stringWithFormat:@"%d",textField.tag-20]};
//        [_scroeArr insertObject:dic atIndex:textField.tag-20];
//    }
    
    if(textField.tag >= 999)
    {
        if (textField.text.length > 50) {
            textField.text = [textField.text substringToIndex:50];
        }
        [_remarkArr removeObjectAtIndex:textField.tag-999];
        NSDictionary* dic = @{@"remark":textField.text,@"tag":[NSString stringWithFormat:@"%d",textField.tag-999]};
        [_remarkArr insertObject:dic atIndex:textField.tag-999];
    }
    else
    {
        if (textField.text.length > 1) {
            textField.text = [textField.text substringToIndex:1];
        }
        
        NSString* str =textField.text;
        if ([str isEqualToString:@""]) {
            textField.text = @"0";
        }
        else
        {
            if ([textField.text integerValue] > 5) {
                textField.text = @"5";
            }
            if ([textField.text integerValue] < 1) {
                textField.text = @"1";
            }
        }
        [_scroeArr removeObjectAtIndex:textField.tag-20];
        NSDictionary* dic = @{@"scroe":textField.text,@"tag":[NSString stringWithFormat:@"%d",textField.tag-20]};
        [_scroeArr insertObject:dic atIndex:textField.tag-20];
    }
}

#pragma mark =============  UITextField Delegate  =============
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    CGRect rect = [textField convertRect:textField.frame toView:self.view];
    
    CGFloat offset = self.view.frame.size.height - (rect.origin.y+textField.frame.size.height+216+50);
    if (offset <= 0) {
        [UIView animateWithDuration:0.3 animations:^
         {
             CGRect frame = self.view.frame;
             frame.origin.y = offset;
             self.view.frame = frame;
         }
         ];
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^
     {
         CGRect frame = self.view.frame;
         frame.origin.y = 70;
         self.view.frame = frame;
     }
     ];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return self.arrContents.count;
//    return 7;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}

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

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35)];
    //viewHeader.backgroundColor = [UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha:1];
    viewHeader.backgroundColor = [UIColor colorWithRed:0.9333 green:0.9333 blue:0.9333 alpha:1];
    
    UILabel *lblPoint = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 35)];
    lblPoint.textColor = [UIColor darkGrayColor];
    lblPoint.backgroundColor = [UIColor clearColor];
    lblPoint.font = [UIFont boldSystemFontOfSize:13];
    lblPoint.textAlignment = NSTextAlignmentCenter;
    lblPoint.text = @"小区名称";
    [viewHeader addSubview:lblPoint];
    
    
    UILabel *lblResultSelf= [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 70, 35)];
    lblResultSelf.textColor = [UIColor darkGrayColor];
    lblResultSelf.backgroundColor = [UIColor clearColor];
    lblResultSelf.font = [UIFont boldSystemFontOfSize:13];
    lblResultSelf.textAlignment = NSTextAlignmentCenter;
    lblResultSelf.text = @"自由评分";
    [viewHeader addSubview:lblResultSelf];
    
    UILabel *lblEvalute = [[UILabel alloc] initWithFrame:CGRectMake(180, 0, 140, 35)];
    lblEvalute.textColor = [UIColor darkGrayColor];
    lblEvalute.backgroundColor = [UIColor clearColor];
    lblEvalute.font = [UIFont boldSystemFontOfSize:13];
    lblEvalute.textAlignment = NSTextAlignmentCenter;
    lblEvalute.text = @"评价";
    [viewHeader addSubview:lblEvalute];
    return viewHeader;
}
-(void)searchClick
{
    NSLog(@"SearchClick");
}
#pragma mark =============  UITableView Delegate  =============

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    self.selectedIndexPath = indexPath;
        DLog(@"You Click At Section: %d Row: %d", (int)indexPath.section, (int)indexPath.row);
    //    BATaskDetailViewController* vc = [[BATaskDetailViewController alloc] init];
    //    vc.shopId = self.arrContents[indexPath.row][@"id"];
    //    vc.taskId = self.arrContents[indexPath.row][@"taskId"];
    //    [self.navigationController pushViewController:vc animated:YES];
}


@end

@implementation CheckResultChangeViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.lblSmallAreaName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, 34.5)];
        _lblSmallAreaName.textColor = [UIColor darkGrayColor];
        _lblSmallAreaName.backgroundColor = [UIColor clearColor];
        _lblSmallAreaName.font = [UIFont systemFontOfSize:13];
        _lblSmallAreaName.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_lblSmallAreaName];
        
        self.lblCheckResult = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 70, 34.5)];
        _lblCheckResult.textColor = [UIColor darkGrayColor];
        _lblCheckResult.backgroundColor = [UIColor clearColor];
        _lblCheckResult.font = [UIFont systemFontOfSize:13];
        _lblCheckResult.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_lblCheckResult];
        
        self.checkResultForSelfTextField = [[UITextField alloc] initWithFrame:CGRectMake(140, 4, 40, 27)];
        _checkResultForSelfTextField.textColor = [UIColor darkGrayColor];
        _checkResultForSelfTextField.backgroundColor = [UIColor clearColor];
        _checkResultForSelfTextField.font = [UIFont systemFontOfSize:13];
        _checkResultForSelfTextField.textAlignment = NSTextAlignmentCenter;
        _checkResultForSelfTextField.layer.borderWidth = 0.5;
        _checkResultForSelfTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _checkResultForSelfTextField.keyboardType= UIKeyboardTypeNumberPad;
        [self.contentView addSubview:_checkResultForSelfTextField];
        
        self.evaluateTextField = [[UITextField alloc] initWithFrame:CGRectMake(185, 4, 130, 27)];
        _evaluateTextField.textColor = [UIColor darkGrayColor];
        _evaluateTextField.backgroundColor = [UIColor clearColor];
        _evaluateTextField.font = [UIFont systemFontOfSize:13];
        _evaluateTextField.textAlignment = NSTextAlignmentLeft;
        _evaluateTextField.layer.borderWidth = 0.5;
        _evaluateTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _evaluateTextField.placeholder = @"请输入一句评价";
        [self.contentView addSubview:_evaluateTextField];
        
        UIView *viewLine = [[UIView alloc] initWithFrame:CGRectMake(0, 34.5, 350, 0.5)];
        viewLine.backgroundColor = [UIColor colorWithRed:0.7333 green:0.7333 blue:0.7333 alpha:1];
        [self.contentView addSubview:viewLine];
        
    }
    return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.BtnClickBlock) {//回调
        self.BtnClickBlock(_checkResultForSelfTextField,_evaluateTextField);
    }
//    [_checkResultForSelfTextField resignFirstResponder];
//    [_evaluateTextField resignFirstResponder];
}
@end