//
//  PatrolExamViewController.m
//  patrol
//
//  Created by Javen on 2017/2/27.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "PatrolExamViewController.h"
#import "PatrolExamTopView.h"
#import "PatrolExamCellViewModel.h"
#import "PatrolExamCategoryTableViewCell.h"
#import "PatrolExamQuestionTableViewCell.h"
#import "PatrolExamSelectTableViewCell.h"
#import "PatrolExamAttachmentCell.h"
#import "PatrolExamInputCell.h"
#import "PatrolExamYesNoCell.h"
#import "PatrolExamScoreCell.h"
#import "PatrolExamStarCell.h"
#import "PatrolStartAnswerConfirmVC.h"
#import "ZJPatrolDetail.h"
#import "BaseNavigationViewController.h"
#import "InspectionTableViewController.h"
#import "AirplaneModeViewController.h"

@interface PatrolExamViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet PatrolExamTopView *topView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;
@property (weak, nonatomic) IBOutlet UIButton *expandButton;
@property (strong, nonatomic) NSTimer *timer;

/**
 是否答过
 */
@property (nonatomic, assign) BOOL isAnswered;

/**
 确认开始的弹框
 */
@property (strong, nonatomic) PatrolStartAnswerConfirmVC *confirmVC;

@end

@implementation PatrolExamViewController


#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.timer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(actionSave) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [self.tableView registerClass:[PatrolExamStarCell class] forCellReuseIdentifier:@"PatrolExamStarCell"];
    [self.btnSubmit setTitle:@"确认提交" forState:UIControlStateNormal];
    @weakify(self);
    self.viewModel.blockReHttp = ^{
        @strongify(self);
        //加载详情
        [IBTLoadingView showProgressLabel:@"加载中"];
        [self.viewModel httpDetailComplete:^{
            @strongify(self);
            [IBTLoadingView hideHUDWithText:nil];
            self.topView.viewModel = self.viewModel;
            //根据当前单据状态显示底部按钮
            self.btnSubmit.hidden = self.viewModel.state.type != PatrolExamStateProcessing;
            [self.tableView reloadData];
        }];
    };
    //状态是0，弹出开始答题提示
    if (self.viewModel.state.type == PatrolExamStateUnStart) {
        [RequestManager request_BeginPatrolPlanAnswer:self.viewModel.plan.uuid storeUuid:self.viewModel.storeResult.store_uuid selectedStoreUuid:@"" longtitude:kUser.longitude latitute:kUser.latitude success:^(id returnValue) {
            if ([BaseViewModel verifyData:returnValue]) {
                self.viewModel.storeResult.state = @(2);
                if (self.confirmVC.blockStart) {
                    self.confirmVC.blockStart();
                }
            }
        } failure:^(id errorValue) {
            [IBTLoadingView showTextOnly:errorValue];
        }];
    }else {
        //加载详情
        [IBTLoadingView showProgressLabel:@"加载中"];
        [self.viewModel httpDetailComplete:^{
            @strongify(self);
            [IBTLoadingView hideHUDWithText:nil];
            self.title = self.viewModel.inspector.store_name;
            self.topView.viewModel = self.viewModel;
            //根据当前单据状态显示底部按钮
            [self.tableView reloadData];
            [self showAirPlanModeVc];
            if (self.viewModel.state.type != PatrolExamStateUnStart) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSMutableArray *arrIndexs = [self.viewModel closeAll];
                    [self.tableView deleteRowsAtIndexPaths:arrIndexs withRowAnimation:UITableViewRowAnimationFade];
                });
            }
            //进行中的单据才显示保存按钮
            if (self.viewModel.state.type == PatrolExamStateProcessing) {
                UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(actionSave)];
                self.navigationItem.rightBarButtonItem = save;
                self.btnSubmit.hidden = NO;
            }
        }];
    };
    //统一刷新
    self.viewModel.blockReloadData = ^{
        @strongify(self);
        [self.tableView reloadData];
    };
    //答案有改动的回调  TODO 待优化，已经有一个通知了
    self.viewModel.blockAnswerAction = ^{
        @strongify(self);
        self.isAnswered = YES;
        self.topView.viewModel = self.viewModel;
    };
    //开始答题
    self.confirmVC.blockStart = ^{
        @strongify(self);
        UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(actionSave)];
        self.navigationItem.rightBarButtonItem = save;
        self.btnSubmit.hidden = NO;
        [IBTLoadingView showProgressLabel:@"加载中"];
        [self.viewModel httpDetailComplete:^{
            @strongify(self);
            [IBTLoadingView hideHUDWithText:nil];
            self.viewModel.state = [PatrolExamState stateWithCode:self.viewModel.storeResult.state];
            self.title = self.viewModel.inspector.store_name;
            self.topView.viewModel = self.viewModel;
            self.btnSubmit.hidden = self.viewModel.state.type != PatrolExamStateProcessing;
            [self.tableView reloadData];
            [self showAirPlanModeVc];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *arrIndexs = [self.viewModel closeAll];
                [self.tableView deleteRowsAtIndexPaths:arrIndexs withRowAnimation:UITableViewRowAnimationFade];
            });
            if (!self.isBackRootVc) {
                [kNotification postNotificationName:UPDATEPATROLONLINELIST object:nil];
            }
        }];
    };
    //手动监听返回方法，返回时是否定时器
    BaseNavigationViewController *nav = (BaseNavigationViewController *)self.navigationController;
    [nav setBackClickAction:^{
        @strongify(self);
        [self popViewControllerAnimated:YES];
    }];
    
    //监听刷新通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionNotiAnswerChanged:) name:kNotiPatrolAnswerChange object:nil];
    [self createBackBtn];
}

#pragma mark -显示飞行模式弹出框
- (void)showAirPlanModeVc {
    if (self.viewModel.airplanModeArray.count && (self.viewModel.state.type == PatrolExamStateProcessing)) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            AirplaneModeViewController *airplanModeVc = [AirplaneModeViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_PATROLINSPECT];
            airplanModeVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            airplanModeVc.datasArray = self.viewModel.airplanModeArray;
            [self presentViewController:airplanModeVc animated:YES completion:nil];
        });
    }
}

#pragma mark -自定义返回视图
- (void)createBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"result_back_icon"] forState:UIControlStateNormal];
    btn.frame  = CGRectMake(0, 0, 40, 40);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [btn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
}

#pragma mark -返回
- (void)backClicked {
    if (self.isBackRootVc) {
        [self PopToRootViewControllerAnimated:YES];
    }else {
        [self PopViewControllerAnimated:YES];
    }
}

#pragma mark -通知刷新回调
- (void)actionNotiAnswerChanged:(NSNotification *)noti {
    [self.tableView reloadData];
    [self showAirPlanModeVc];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellVM = [self.viewModel.arrCellData yx_objectAtIndex:indexPath.row];
    return cellVM.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.arrCellData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellVM = [self.viewModel.arrCellData yx_objectAtIndex:indexPath.row];
    switch (cellVM.cellType) {
        case ExamCellTypeCatogory: {
            PatrolExamCategoryTableViewCell *categoryCell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamCategoryTableViewCell" forIndexPath:indexPath];
            categoryCell.cellModel = cellVM;
            return categoryCell;
        } break;
        case ExamCellTypeQuestion: {
            PatrolExamQuestionTableViewCell *questionCell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamQuestionTableViewCell" forIndexPath:indexPath];
            questionCell.cellModel = cellVM;
            return questionCell;
        } break;
        case ExamCellTypeSingle: {
            PatrolExamSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamSelectTableViewCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeMultiple: {
            PatrolExamSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamSelectTableViewCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeStar: {
            PatrolExamStarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamStarCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeInput: {
            PatrolExamInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamInputCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeYesNO: {
            PatrolExamYesNoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamYesNoCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeScore: {
            PatrolExamScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamScoreCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;

            return cell;
        } break;
        case ExamCellTypeAttachment: {
            PatrolExamAttachmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamAttachmentCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        case ExamCellTypeSelectScore: {
            PatrolExamSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PatrolExamSelectTableViewCell" forIndexPath:indexPath];
            cell.cellModel = cellVM;
            return cell;
        } break;
        default:
            break;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellVM = [self.viewModel.arrCellData yx_objectAtIndex:indexPath.row];
    NSMutableArray *arrIndexs = [self.viewModel indexPathWithSelectIndexPath:indexPath];
    if (cellVM.isOpen) {
        cellVM.isOpen = NO;
        [self.tableView deleteRowsAtIndexPaths:arrIndexs withRowAnimation:UITableViewRowAnimationFade];
    } else {
        cellVM.isOpen = YES;
        [self.tableView insertRowsAtIndexPaths:arrIndexs withRowAnimation:UITableViewRowAnimationFade];
    }
}

//显示全部/收起
- (IBAction)actionOpenAll:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        [self.viewModel openAll];
    } else {
        NSMutableArray *arrIndexs = [self.viewModel closeAll];
        [self.tableView deleteRowsAtIndexPaths:arrIndexs withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark -提交VI检查任务
- (IBAction)actionSubmit:(id)sender {
    [self.viewModel openAll];
    self.expandButton.selected = YES;
    if (!self.viewModel.detail.temp) {
        //找到最上面一个没有回答的问题
        if (self.viewModel.detail.questions.count != self.viewModel.dicAnswers.count) {
            NSMutableArray *arrQuestionId = [NSMutableArray array];
            for (ZJPatrolDetail_questions *qustion in self.viewModel.detail.questions) {
                [arrQuestionId addObject:qustion.uuid];
            }
            NSMutableSet *setQuestionId = [NSMutableSet setWithArray:arrQuestionId];
            NSSet *setAnswerQuestionId = [NSSet setWithArray:self.viewModel.dicAnswers.allKeys];
            [setQuestionId minusSet:setAnswerQuestionId];
            for (NSInteger i = 0; i < self.viewModel.arrCellData.count; i++) {
                PatrolExamCellViewModel *vm = self.viewModel.arrCellData[i];
                if ([setQuestionId containsObject:vm.question.uuid]) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
                    break;
                }
            }
            [IBTLoadingView showTextOnly:@"您有未检查的项目"];
            return;
        }else {
            NSMutableArray *questionArray = [NSMutableArray array];
            for (id object in self.viewModel.dicAnswers.allValues) {
                if ([object isKindOfClass:[ZJPatrolDetail_results_answers class]]) {
                    ZJPatrolDetail_results_answers *answer = (ZJPatrolDetail_results_answers *)object;
                    if (answer.details.count && !answer.resultAttachments.count) {
                        [questionArray addObject:answer.questionUuid];
                    }
                }
            }
            for (NSInteger i = 0; i < self.viewModel.arrCellData.count; i++) {
                PatrolExamCellViewModel *vm = self.viewModel.arrCellData[i];
                if (photoType(vm.question.photoType) != PHOTO_TYPE_NO) {
                    if ([questionArray containsObject:vm.question.uuid]) {
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
                        break;
                    }
                }else {
                    [questionArray removeObject:vm.question.uuid];
                }
            }
            if (questionArray.count) {
                [IBTLoadingView showTextOnly:@"您有检查的项目未拍照"];
                return;
            }
        }
    }else {
        NSMutableArray *questionArray = [NSMutableArray array];
        for (id object in self.viewModel.dicAnswers.allValues) {
            if ([object isKindOfClass:[ZJPatrolDetail_results_answers class]]) {
                ZJPatrolDetail_results_answers *answer = (ZJPatrolDetail_results_answers *)object;
                if (answer.details.count && !answer.resultAttachments.count) {
                    [questionArray addObject:answer.questionUuid];
                }
            }
        }
        for (NSInteger i = 0; i < self.viewModel.arrCellData.count; i++) {
            PatrolExamCellViewModel *vm = self.viewModel.arrCellData[i];
            if ([questionArray containsObject:vm.question.uuid]) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
                break;
            }
        }
        if (questionArray.count) {
            [IBTLoadingView showTextOnly:@"您有检查的项目未拍照"];
            return;
        }
    }
    @weakify(self);
    NSMutableArray *answerArray = [NSMutableArray array];
    for (id object in self.viewModel.dicAnswers.allValues) {
        if ([object isKindOfClass:[ZJPatrolDetail_results_answers class]]) {
            ZJPatrolDetail_results_answers *answer = (ZJPatrolDetail_results_answers *)object;
            if (answer.details.count) {
                [answerArray addObject:@1];
            }
        }
    }
    NSString *message = [NSString stringWithFormat:@"当前已填写(%lu/%lu)项检查项目,请确认是否提交!",answerArray.count, self.viewModel.detail.questions.count];
    ShowAlertView(@"提示",message, @[@"取消",@"确认"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        @strongify(self);
        if (index == ONE) {
            [IBTLoadingView showProgressLabel:@"加载中"];
            [self.viewModel httpSubmitAnswerWithAction:(AnswerSubmitActionCommit) complete:^(BOOL isSuccess) {
                  [IBTLoadingView hideHUDWithText:nil];
                  if (isSuccess) {
                      [IBTLoadingView showTextOnly:@"提交成功"];
                      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(ONE * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                          InspectionTableViewController *patrolResultVc = [InspectionTableViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_PATROLINSPECTRESULT];
                          patrolResultVc.isBackRootVc = YES;
                          [self PushViewController:patrolResultVc animated:YES];
                      });
                  }
            }];
        }
    });
}

#pragma mark -保存VI检查答案
- (void)actionSave {
    @weakify(self);
    if (self.viewModel.state.type != PatrolExamStateProcessing || !self.viewModel.result) {
        return;
    }
    UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithTitle:@"保存中…" style:UIBarButtonItemStyleDone target:self action:nil];
    self.navigationItem.rightBarButtonItem = save;
    [self.viewModel httpSubmitAnswerWithAction:AnswerSubmitActionSave complete:^(BOOL isSuccess) {
          @strongify(self);
          if (isSuccess) {
              //刷新列表
              [kNotification postNotificationName:UPDATEPATROLONLINELIST object:nil];
              self.topView.viewModel = self.viewModel;
              UIBarButtonItem *save = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(actionSave)];
              self.navigationItem.rightBarButtonItem = save;
              self.isAnswered = NO;
          }
      }];
}

- (PatrolStartAnswerConfirmVC *)confirmVC {
    if (!_confirmVC) {
        _confirmVC = [PatrolStartAnswerConfirmVC viewControllerWithStoryBoardType:STORYBOARD_TYPE_PATROLINSPECT];
        _confirmVC.superVC = self;
        _confirmVC.viewModel = self.viewModel;
    }
    return _confirmVC;
}

- (PatrolExamViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [PatrolExamViewModel new];
    }
    return _viewModel;
}






















@end
