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

#import "PatrolAttachmentViewController.h"
#import "ZJPictureTableViewCell.h"
#import "UploadManager.h"
#import "PatrolExamViewModel.h"
#import "PatrolTaskRemarkFooterView.h"

@interface PatrolAttachmentViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/**
 问题标题
 */
@property (weak, nonatomic) IBOutlet UILabel *labelQuestionTitle;
@property (weak, nonatomic) IBOutlet UIButton *btnBottom;

@end

@implementation PatrolAttachmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.labelQuestionTitle.text = self.cellModel.question.title;
    [self.btnBottom setTitle:@"提交" forState:UIControlStateNormal];
    [self.tableView registerNib:[UINib nibWithNibName:PatrolTaskRemarkFooterView.className bundle:nil] forHeaderFooterViewReuseIdentifier:PatrolTaskRemarkFooterView.className];
    [self configWithType];
}

- (void)configWithType {
    switch (self.viewModel.type) {
        case kPicCellTypeAdd:
        {
            self.title = [NSString stringWithFormat:@"%@",@"添加图片附件"];
        }
            break;
        case kPicCellTypeRead:
        {
            self.title = [NSString stringWithFormat:@"%@%@",@"查看",@"图片附件"];
            self.btnBottom.hidden = YES;
            if ([UploadManager getUploadType] == UPLOAD_COMMON) {
            [RequestManager request_QueryPatrolPlanAttachments:self.cellModel.answer.resultAttachmentId success:^(id returnValue) {
                if ([BaseViewModel verifyData:returnValue]) {
                    NSMutableArray *arrPic = [NSMutableArray array];
                    NSArray *dataArray = (NSArray *)[BaseViewModel formatData:returnValue];
                    for (NSInteger i = 0; i < dataArray.count; i++) {
                        NSDictionary *dict = dataArray[i];
                        PostAttachmentModel *model = [[PostAttachmentModel alloc] initWithDictionary:dict error:nil];
                        [arrPic addObject:model.fileUrl];
                    }
                    self.viewModel.arrPics = arrPic;
                    [self.tableView reloadData];
                }
        
            } failure:^(id errorValue) {
                [IBTLoadingView showTextOnly:errorValue];
            }];
            }else{
                NSMutableArray *pic = [NSMutableArray array];
                for (ZJPatrolDetail_questions_attachmentUrls *urls in self.cellModel.answer.resultAttachments) {
                    if ([urls.fileUrl hasPrefix:@"http"]) {
                        [pic addObject:urls.fileUrl];
                    }else{
                        [pic addObject:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,urls.fileUrl]];
                    }
                }
                self.viewModel.arrPics = pic;
                [self.tableView reloadData];
            }
        }
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.viewModel cellHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZJPictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZJPictureTableViewCell" forIndexPath:indexPath];
    NSString *memarkString = [NSString stringWithFormat:@"%@  %@\n%@  %@",kUser.f_user_name,self.cellModel.question.title,[[NSDate date] httpParameterString],self.cellModel.viewModel.inspector.store_name];
    PHOTO_TYPE type = photoType(self.cellModel.question.photoType);
    [cell configCellWithViewModel:self.viewModel indexPath:indexPath target:self remarkString:memarkString photoType:type];
    @weakify(self);
    cell.blockReloadData = ^{
        @strongify(self);
        [self.tableView reloadData];
    };
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    PatrolTaskRemarkFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:PatrolTaskRemarkFooterView.className];
    footerView.remarkTextView.text = self.cellModel.getAnswer.remark;
    WS(weakSelf);
    [footerView.remarkTextView.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        weakSelf.cellModel.getAnswer.remark = x;
    }];
    footerView.userInteractionEnabled = self.cellModel.viewModel.state.type == PatrolExamStateProcessing;
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 150;
}

- (IBAction)actionSubmit:(id)sender {
    @weakify(self);
    ShowAlertView(@"提示", @"确认提交附件?", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
        @strongify(self);
        [self httpUploadPictures];
    });
}

- (void)httpUploadPictures{
    NSMutableArray *arrAttachment = [NSMutableArray array];
    for (NSString *imageName in self.viewModel.arrPics) {
        PostAttachmentModel *imageModel = [[PostAttachmentModel alloc] init];
        imageModel.attachmentType = ATTACHMENT_IMAGE;
        imageModel.thumbnailUrl = [kPathDocument stringByAppendingPathComponent:imageName];
        imageModel.fileUrl = [kPathDocument stringByAppendingPathComponent:imageName];
        imageModel.entityType = ENTITY_PATROL;
        imageModel.fileName = imageName;
        [arrAttachment addObject:imageModel];
    }
    @weakify(self);
    [UploadManager uploadObjectArray:arrAttachment completed:^(UploadResponse *success) {
        @strongify(self);
        ZJPatrolDetail_results_answers *answer = self.cellModel.getAnswer;
        PatrolTaskRemarkFooterView *footerView = (PatrolTaskRemarkFooterView *)[self.tableView footerViewForSection:0];
        answer.remark = footerView.remarkTextView.text;
        answer.resultAttachmentId = [ToolsManager getTheTimestamp];
        answer.attachmenturls = (NSMutableArray<ZJPatrolDetail_questions_attachmentUrls,Optional> *)[NSMutableArray array];
        if (success.type == UPLOAD_COMMON) {
            
        }else{
            for (PostAttachmentModel *model in success.response) {
                if (![model.entityUuid isEqualToString:model.thumbnailName]) {
                    ZJPatrolDetail_questions_attachmentUrls *url = [ZJPatrolDetail_questions_attachmentUrls modelWithDic:model.toDictionary];
                    url.fileUrl = model.entityUrl;
                    [answer.attachmenturls addObject:url];
                }
            }
        }
        [IBTLoadingView showProgressLabel:@"加载中"];
        [self.cellModel.viewModel httpSubmitAnswerWithAction:(AnswerSubmitActionSave) complete:^(BOOL isSuccess) {
            [IBTLoadingView hideHUDWithText:nil];
            if (isSuccess) {
                 self.cellModel.viewModel.blockReHttp();
                 [self popViewControllerAnimated:YES];
            }else{
                [IBTLoadingView showTextOnly:@"上传失败"];
            }
        }];
        
    } failed:^(id error) {
        [IBTLoadingView showTextOnly:@"上传失败"];
    }];
}


@end
