//
//  GTOPioneeringInfoViewController.m
//  total
//  原来打算：把新建跟编辑拓站的界面写到一起，因为之前写的这两块的逻辑跟跳转有些重复，不太和逻辑
//  Created by freecui on 15/11/14.
//  Copyright © 2015年 free. All rights reserved.
//

#import "GTOPioneeringInfoViewController.h"
#import "GTOQuestion.h"
#import "GTOAnswer.h"
#import "GXFBottomView.h"
#import "GTOCategoryItemView.h"
#import "GTOQuestionManager.h"
#import "GTOQResultViewController.h"
#import "GTOAlertInfoPioneeringViewController.h"
#import "RETableViewManager.h"
#import "GTOPioneering.h"
#import "GTOPioneeringSurveyItem.h"
#import "GTODisplayResult.h"
#import "GTOPioneeringTemplateViewController.h"
#import "GTOPatrolTemplate.h"
#define CELL_HEIGHT 65

@interface GTOPioneeringInfoViewController ()<GXFBottomViewDelegate,GTOAlertInfoPioneeringViewControllerDelegate>
@property (strong, readwrite, nonatomic) RETableViewManager *manager;
@property (strong, readwrite, nonatomic) RETextItem *titleItem;
@property (strong, readwrite, nonatomic) RERadioItem *templeteSelectItem;
@property (strong, readwrite, nonatomic) RETextItem *templeteItem;
@property (strong, readwrite, nonatomic) RETextItem *startTimeItem;
@property (strong, readwrite, nonatomic) RETextItem *pinoeeringItem;
@property (strong, readwrite, nonatomic) RETextItem *remarkItem; //RELongTextItem
@property (nonatomic, strong) UITableView *c_tableView;
@property (nonatomic, strong) GTOPioneering *d_pioneering;
@property (nonatomic, strong) GTOAlertInfoPioneeringViewController *alertInfoVC;
@property (nonatomic, strong) GTOPatrolTemplate *d_patrolTemplate;
@property (nonatomic, strong) BMKMapView *c_mapView;
@property (nonatomic, assign) BOOL d_isClosed; //点击弹框的“关闭”按钮
@property (nonatomic, assign) BOOL d_isNext;// 非弹框上的“下一步”
@end

@implementation GTOPioneeringInfoViewController

- (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.
    if(_d_pioneering &&  _d_pioneering.isHttpData)
    {
        [self p_saveHttpData];//网络中下载明细
    } else {
        [self initSubViews];
    }

}

- (void)initSubViews {
    self.c_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 5*44) style:UITableViewStylePlain];
    [self.view addSubview:_c_tableView];
    self.manager = [[RETableViewManager alloc]initWithTableView:self.c_tableView];
    RETableViewSection *section = [RETableViewSection section];
    [self.manager addSection:section];
    if (!_d_pioneering) { //新增页面
        self.titleItem = [RETextItem itemWithTitle:@"标题：" value:nil placeholder:@"请输入标题"];
        self.templeteSelectItem = [RERadioItem itemWithTitle:@"拓站模板：" value:nil selectionHandler:^(RERadioItem *item) {
            GTOPioneeringTemplateViewController *VC = [[GTOPioneeringTemplateViewController alloc]init];
            VC.purpose = @"licence";
            // if (VC.choseBaseInfo) {
            VC.choseBaseInfo = ^(NSArray *templateNames) {
                GTOPatrolTemplate *patroTemplate = templateNames[0];
                self.templeteSelectItem.value = patroTemplate.name;
                self.d_patrolTemplate = patroTemplate;
                [item reloadRowWithAnimation:UITableViewRowAnimationNone];
            };
            [self PushViewController:VC animated:YES];
        
        }];
        
        self.startTimeItem = [RETextItem itemWithTitle:@"开始时间：" value:[[NSDate date] httpParameterString] placeholder:@"输入备注内容"];
        self.pinoeeringItem = [RETextItem itemWithTitle:@"拓站人员：" value:nil placeholder:@"Password item"];
        self.remarkItem = [RETextItem itemWithTitle:@"备注" value:nil placeholder:@"输入备注内容"];
    } else { //编辑页面
        self.titleItem = [RETextItem itemWithTitle:@"标题：" value:_d_pioneering.title placeholder:@"请输入标题"];
        self.templeteItem = [RETextItem itemWithTitle:@"拓站模板：" value: _d_pioneering.templateName placeholder:@"请输选择拓站模板"];
       
        self.startTimeItem = [RETextItem itemWithTitle:@"开始时间：" value:_d_pioneering.beginDate placeholder:@"输入备注内容"];
        self.pinoeeringItem = [RETextItem itemWithTitle:@"拓站人员：" value:_d_pioneering.pioneer_name placeholder:@""];
        self.remarkItem = [RETextItem itemWithTitle:@"备注" value:_d_pioneering.remark placeholder:@"输入备注内容"];
    }


    [section addItem:_titleItem];
    if (!_d_pioneering) {
        [section addItem:_templeteSelectItem];
    } else {
        [section addItem:_templeteItem];
    }
    [section addItem:_startTimeItem];
    [section addItem:_pinoeeringItem];
    [section addItem:_remarkItem];

    CGFloat signBtnW = 120;
    UIButton *signBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width - signBtnW,_c_tableView.bottom + 10, signBtnW , 44)];
    signBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [signBtn.titleLabel setTextAlignment:NSTextAlignmentRight];
    [signBtn setTitle:@"记录位置" forState:UIControlStateNormal];
    [signBtn setTitleColor:GTO_BLUE_TINT_COLOR forState:UIControlStateNormal];
    // [signBtn setImage:[UIImage imageNamed:@"icon_nav_start"] forState:UIControlStateNormal];
    [signBtn addTarget:self action:@selector(signClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:signBtn];
    
    CGFloat latitude = [_d_pioneering.latitude floatValue];
    CGFloat longitude = [_d_pioneering.longitude floatValue];
    IBTUILabel *locationValueLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(10, signBtn.y, self.view.width - 10 - signBtn.left,signBtn.height) text:[NSString stringWithFormat:@"坐标(%.6f,%.6f)",latitude,longitude] font:[UIFont systemFontOfSize:17] tintColor:[UIColor blackColor] backgroundColor:nil textAlignment:NSTextAlignmentRight]; //_d_pioneering.longitude,_d_pioneering.latitude
    [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];
    
    _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];
}

- (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 initSubViews];
        [_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];
}

#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)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
