//
//  GTOEditPioneeringViewController.m
//  total
//
//  Created by freecui on 15/10/15.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOEditPioneeringViewController.h"
#import "GXFTableViewCell.h"
#import "GXFBottomView.h"
#import "GTOPioneering.h"
#import "GTOQuestion.h"
#import "GTOAnswer.h"
#import "GTOPioneeingProcess.h"
#import "GTOCategoryItemView.h"
#import "GTOQuestionManager.h"
#import "GTOQResultViewController.h"
#import "GTOAlertInfoPioneeringViewController.h"

#import "GTOPioneeringSurveyItem.h"
#import "GTODisplayResult.h"
#import <BaiduMapAPI/BMapKit.h>
#define CELL_HEIGHT 65
@interface GTOEditPioneeringViewController ()
<UITableViewDataSource,UITableViewDelegate,GXFBottomViewDelegate,
UITextFieldDelegate,GTOAlertInfoPioneeringViewControllerDelegate>
@property (nonatomic, strong) UITableView *c_tableView;
@property (nonatomic, strong) NSArray *d_leftArr;//uitableView左边显示的提示
@property (nonatomic, strong) NSArray *d_rightArr;//右边placeholder提示
@property (nonatomic, strong) NSArray *d_rightValueArr;//右边内容显示
@property (nonatomic, strong) GTOPioneering *d_pioneering;

@property (nonatomic, strong) BMKMapView *c_mapView;

@property (nonatomic, assign) BOOL d_isClosed; //点击弹框的“关闭”按钮
@property (nonatomic, assign) BOOL d_isNext;// 非弹框上的“下一步”
//重构
@property (nonatomic, strong) GTOAlertInfoPioneeringViewController *alertInfoVC;
@end
typedef NS_ENUM(NSUInteger, bottomTag){
   kCategoryTableVTag = 2,
    kNextbottomVTag
} ;
@implementation GTOEditPioneeringViewController

- (instancetype)initWithPioneering: (GTOPioneering *)pioneering {
    self = [super init];
    if (!self) {
        return nil;
    }
    self.d_pioneering = pioneering;
    
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"编辑拓站";
    [self p_initData];
    
    
    if(_d_pioneering.isHttpData)
    {
        [self p_saveHttpData];//网络中下载明细
    }

}
- (void)p_saveHttpData {
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    
    [IBTLoadingView showProgressLabel:@"正在获取数据"];
    // [IBTLoadingView hideHUDWithText:nil];
    void (^success)(id data) = ^(id data) {
//        CLog(@"%@", data);
        
         [IBTLoadingView hideHUDWithText:nil];
        NSInteger intSucc = [data[@"success"] integerValue];
        if (intSucc == 1) {
            
        }
        NSArray *arrItems = [data[@"data"] objectForKey:@"items"];
        NSMutableArray *muArrQuestions = [NSMutableArray array];
        NSMutableArray *muArrCategory = [NSMutableArray array];
        for(NSDictionary *dictItem in arrItems) {
            
            GTOPioneeringSurveyItem *item = [GTOPioneeringSurveyItem DBObject];
            [item praseFromJsonDict:dictItem];
            GTOQuestion *question = [GTOQuestion DBObject];
            [question praseFromJsonDict:dictItem];
            [question saveToDBWithHandleData:NULL complete:NULL fail:NULL];
            CLog(@"%@",question.uuid);
            [muArrQuestions addObject:[question dictForCommit]];
            
            GTOAnswer *answer = [GTOAnswer DBObject];
            [answer praseFromJsonDict:dictItem];
            
            NSUInteger count = 0;//记录是否被回答：根据答案有无
            if(answer.resultScore) count++;
            if(answer.resultContent) count++;
            if(answer.resultRemark) count++;
            if(answer.resultDetails.count) count++;
            if (count > 0 ) {
                answer.bIsAnswered = YES;
                answer.questionUuid = item.uuid;
                answer.pioneeringUuid = _d_pioneering.uuid;
                if(answer.resultAttachmentUrls.count > 0) answer.bIsDownLoadImgs = YES;
                [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
            }
            
            [muArrCategory addObject:item.category];
            
        }
        _d_pioneering.questions = muArrQuestions;
        //GTODisplayResult
        NSSet *setCategory = [NSSet setWithArray:muArrCategory];
        NSMutableArray *muArrDisplayRs = [NSMutableArray array];
        for(NSString *category in setCategory) {
            NSMutableArray *muArrQuestions = [NSMutableArray array];
            for(NSDictionary *dictQ in _d_pioneering.questions) {
                GTOQuestion *question = [GTOQuestion DBObject];
                [question praseFromJsonDict:dictQ];
                if ([question.category isEqualToString:category]) {
                    [muArrQuestions addObject:dictQ];
                }
            }
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            displayR.arrQuestions = muArrQuestions;
            displayR.category = category;
            displayR.isDisplay = NO;
            [muArrDisplayRs addObject:[displayR dictForCommit]];
        }
        

        _d_pioneering.arrDisplayResults = muArrDisplayRs;
        [self p_initWithSubViews];
        [_d_pioneering saveToDBWithHandleData:NULL
                                     complete:^{
                                         
                                     }
                                         fail:^(NSError *error) {
                                             
                                             [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                         }];
    };
    void (^failure)(id ) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
//        CLog(@"%@", data);
    };
    
    [httpC getPioneeringItemsWithPioneeringUuid:_d_pioneering.uuid success:success failure:failure];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    if (_d_isClosed && _d_isNext) {

        [self p_addAlerInfoPioneeringView];
    }
}
- (void)p_initData {
    if (!_d_pioneering) {
        self.d_pioneering = [[GTOPioneering alloc]init];
    }
    
    

    self.d_leftArr = @[@"标题：",@"拓站模板",@"开始时间：",@"拓站人员：",@"备注："];
    self.d_rightArr = @[@"请输入标题",@"",@"",@"",@"输入备注内容"];
    self.d_rightValueArr = @[[GTOCommonTools stringWithId:_d_pioneering.title],
                        [GTOCommonTools stringWithId:_d_pioneering.templateName],
                        _d_pioneering.beginDate,
                        [GTOCommonTools stringWithId:_d_pioneering.pioneer_name],
                        [GTOCommonTools stringWithId:_d_pioneering.remark]];
  
}

- (void)p_initWithSubViews {
    CGFloat latitude = [_d_pioneering.latitude floatValue];
    CGFloat longitude = [_d_pioneering.longitude floatValue];
    
    self.c_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,ScreenSize.width, 44 * _d_leftArr.count) style:(UITableViewStylePlain)];
    
    self.c_tableView.delegate = self;
    self.c_tableView.dataSource = self;
    [self.view addSubview:self.c_tableView];
    IBTUILabel *locationLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(10, _c_tableView.bottom + 10, (self.view.width - 20) * 0.5, 20) text:@"记录位置" font:[UIFont systemFontOfSize:19] tintColor:GTO_BLUE_TINT_COLOR backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    IBTUILabel *locationValueLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(locationLbl.right, locationLbl.y, locationLbl.width, locationLbl.height) text:[NSString stringWithFormat:@"坐标(%.2f,%.2f)",latitude,longitude] font:[UIFont systemFontOfSize:17] tintColor:[UIColor blackColor] backgroundColor:nil textAlignment:NSTextAlignmentRight]; //_d_pioneering.longitude,_d_pioneering.latitude
    [self.view addSubview:locationLbl];
    [self.view addSubview:locationValueLbl];

    self.c_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, locationValueLbl.bottom,self.view.width, self.view.height - locationValueLbl.bottom - BottomViewHeight - 20)];
    [self.view addSubview:_c_mapView];
    // CLLocationCoordinate2D  @"31.235,121.529

    _c_mapView.centerCoordinate = CLLocationCoordinate2DMake(latitude,longitude);
    //闵行坐标 latitude = 31.2357360000,longitude = 121.5292150000
    //增加大头针
    BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = latitude;
    coor.longitude = longitude;
    pointAnnotation.coordinate = coor;
    [_c_mapView addAnnotation:pointAnnotation];
    _c_mapView.zoomLevel = 17;
    
    GXFBottomView *bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:CGRectMake(0, _c_mapView.bottom  +20, self.view.width, BottomViewHeight) buttonColor:GTO_RED_COLOR buttonTitle:@"下一步"];
    bottomV.delegate = self;
    [self.view addSubview:bottomV];
    
}
#pragma UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _d_leftArr.count;
//    return tableView.tag == kCategoryTableVTag ? _d_arrCategorys.count : _d_leftArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        GXFTableViewCell *xfCell ;
        xfCell.width = _c_tableView.width;
    xfCell = [tableView dequeueReusableCellWithIdentifier:noLblCell];//-
    if (!xfCell) {
        xfCell = [[GXFTableViewCell alloc]initWithWidth:_c_tableView.width Style:UITableViewCellStyleDefault reuseIdentifier:arrowCell textFieldPlaceholder:_d_rightArr[indexPath.row] isEdit:YES];
        
    }
        if (indexPath.row == 1  ||  indexPath.row == 2 || indexPath.row == 3) {
        xfCell.f_textField.textColor = GTO_GRAY_TINT_COLOR;
        xfCell.f_textField.userInteractionEnabled = NO;
    }
    


 
    for(int count = 0; count < _d_rightValueArr.count; count ++){
        if ([_d_rightValueArr[count] length] > 0) {
            xfCell.f_textField.text = _d_rightValueArr[indexPath.row];
        }
    }
    
    
    if (xfCell.f_textField) {
        xfCell.f_textField.delegate = self;
    }
    //xfCell.f_textField.text = _d_rightValueArr[indexPath.row];
    xfCell.selectionStyle = UITableViewCellAccessoryNone;
    xfCell.f_textField.tag = indexPath.row;
    xfCell.textLabel.text = _d_leftArr[indexPath.row];
    
    return xfCell;
   // }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 44;
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//}

#pragma  GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView oneButtonClicked:(UIButton *)oneBtn {
    __weak typeof(self)weakSelf = self;
    [_d_pioneering saveToDBWithHandleData:NULL
                                 complete:^{
                                     __strong __typeof(weakSelf)strongSelf = weakSelf;
                                     [IBTLoadingView hideHUDWithText:nil];

                                 }
                                     fail:^(NSError *error) {
                                         
                                         [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                     }];
    
    self.d_isNext = YES;
    [self p_addAlerInfoPioneeringView];
   // [self p_addAlertBgView];
    
}
- (void)p_addAlerInfoPioneeringView {
    GTOAlertInfoPioneeringViewController *alertInfoVC = [[GTOAlertInfoPioneeringViewController alloc]initWithPioneering:_d_pioneering];
    self.alertInfoVC = alertInfoVC;
    alertInfoVC.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_alertInfoVC.view];
}
#pragma GTOAlertInfoPioneeringViewControllerDelegate
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering closeClickedWithBtton:(UIButton *)btn {
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering seeResultClickedWithBtton:(UIButton *)btn {
    GTOQResultViewController *resultVC = [[GTOQResultViewController alloc]initWithPioneering:_d_pioneering];
    
    self.d_isClosed = YES;
    [_alertInfoVC.view removeFromSuperview];
    [self PushViewController:resultVC animated:YES];
}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering nextClickedWithBtton:(UIButton *)btn {
      BOOL isAllFinished = YES;
    for(NSDictionary *dict in _d_pioneering.arrDisplayResults) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dict];
        if (displayR.arrAnswers.count < displayR.arrQuestions.count) {
            GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
            mgr.d_category = displayR.category;
             [mgr openQuestionVCFromViewControler:self withPioneering:_d_pioneering];
            [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
             isAllFinished = NO;
            break;
        }
    }
    
    if (isAllFinished) {
        NSDictionary *dictR = [_d_pioneering.arrDisplayResults lastObject];
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictR];
        GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
        mgr.d_category = displayR.category;
        [mgr openQuestionVCFromViewControler:self withPioneering:_d_pioneering];
        [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
    }
    

}
- (void)alertInfoPioneeringViewController:(GTOAlertInfoPioneeringViewController *)alertInfoPioneering didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[indexPath.row]];
    mgr.d_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
    [mgr openQuestionVCFromViewControler:self withPioneering:_d_pioneering];
    [self alertInfoPioneeringViewController:alertInfoPioneering closeClickedWithBtton:nil];
}

//- (void)bottomViewleftButtonClicked:(UIButton *)leftBtn {
//    GTOQResultViewController *questionRVC = [[GTOQResultViewController alloc]initWithPioneering:_d_pioneering];
//    [self PushViewController:questionRVC animated:YES];
//    [self closeCliced];
//   // [self presentViewController:questionRVC animated:YES completion:nil]; 为什么view会往上64？？？
//}
- (UILabel *)p_labelWithFrame: (CGRect)frame
                         Text: (NSString *)text {
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:frame];
    lbl.font = [UIFont systemFontOfSize:17];
    lbl.textAlignment = NSTextAlignmentLeft;
    lbl.text = text;
    return lbl;
    
}


- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self textFieldShouldReturn:textField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    switch (textField.tag) {
        case 0:
            self.d_pioneering.title = textField.text;
            break;
        case 1:
            // self.d_processProduct.productName = textField.text;
            break;
        case 2:
       
            break;
        case 3:
            self.d_pioneering.remark = textField.text;
            break;
        default:
            break;
    }
    return YES;
}


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



@end
