//
//  InspectionDetailTableViewController.m
//  patrol
//
//  Created by 曹云霄 on 16/9/1.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "InspectionDetailTableViewController.h"
#import "InspectionDetailsSectionTableViewCell.h"
#import "InspectionResultDetailsModel.h"
#import "InspectionAnswerViewController.h"
#import "CustomInspectionTableViewCell.h"

#define SECTION_HEIGHT 50
NSString *const CELL = @"CustomInspectionTableViewCell";

@interface InspectionDetailTableViewController ()<RefreshDelegate>


/*******************************有分数情况*******************************/
/**
 *  督导名字
 */
@property (weak, nonatomic) IBOutlet UILabel *supervisionNameLabel;

/**
 *  任务开始时间
 */
@property (weak, nonatomic) IBOutlet UILabel *taskBegineTimeLabel;

/**
 *  任务结束时间
 */
@property (weak, nonatomic) IBOutlet UILabel *taskFinishTimeLabel;

/**
 *  总分
 */
@property (weak, nonatomic) IBOutlet UILabel *totalScoreLabel;

/**
 门店
 */
@property (weak, nonatomic) IBOutlet UIButton *storeButton;

/**
 *  全部展开
 */
@property (weak, nonatomic) IBOutlet UIButton *allSectionOpenButton;

/**
 *  cell内选中sectionHeaderView
 */
@property (nonatomic,assign) NSInteger cellIndex;

/**
 *  记录每个Section内的section的闭合情况
 */
@property (nonatomic,strong) NSMutableArray *sectionOpenControl;

/**
 *  数据源
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 *  sectionTitle
 */
@property (nonatomic,strong) NSMutableArray *categoryArray;

/**
 嵌套tableview Row所需高度
 */
@property (nonatomic,strong) NSMutableArray *subTableViewHeightArray;

/**
 嵌套tableview Section所需高度
 */
@property (nonatomic, strong) NSMutableArray *subTableViewSectionHeightArray;

/**
 检查项
 */
@property (weak, nonatomic) IBOutlet UILabel *checkItemsLabel;

/**
 cell高度
 */
@property (nonatomic,assign) CGFloat cellHeight;

@end

@implementation InspectionDetailTableViewController


#pragma mark - lazy
- (NSMutableArray *)sectionOpenControl
{
    if (!_sectionOpenControl) {
        _sectionOpenControl = [NSMutableArray array];
    }
    return _sectionOpenControl;
}

- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

- (NSMutableArray *)categoryArray
{
    if (!_categoryArray) {
        _categoryArray = [NSMutableArray array];
    }
    return _categoryArray;
}

- (NSMutableArray *)subTableViewHeightArray
{
    if (!_subTableViewHeightArray) {
        _subTableViewHeightArray = [NSMutableArray array];
        for (int i=0; i<self.datasArray.count; i++) {
            NSArray *subArray = self.datasArray[i];
            NSMutableArray *subHeightArray = [NSMutableArray array];
            NSMutableArray *subSectionArray = [NSMutableArray array];
            for (int j=0; j<subArray.count; j++) {
                CGFloat cellContentHeight = 0;
                NewAnswers *answer = subArray[j];
                cellContentHeight += answer.contentHeight;
                cellContentHeight += answer.remarkHeight;
                cellContentHeight += answer.resultAttachmentsHeight;
                if (!answer.remarkHeight && !answer.resultAttachmentsHeight) {
                    cellContentHeight += 20;
                }else if ((answer.remarkHeight && !answer.resultAttachmentsHeight) || (!answer.remarkHeight && answer.resultAttachmentsHeight)){
                    cellContentHeight += 30;
                }else if (answer.remarkHeight && answer.resultAttachmentsHeight){
                    cellContentHeight += 40;
                }
                //Section 开启的高度
                [subHeightArray addObject:@(cellContentHeight)];
                [subSectionArray addObject:@(answer.questionHeight + 30)];
            }
            [_subTableViewHeightArray addObject:subHeightArray];
            [self.subTableViewSectionHeightArray addObject:subSectionArray];
        }
    }
    return _subTableViewHeightArray;
}

- (NSMutableArray *)subTableViewSectionHeightArray
{
    if (!_subTableViewSectionHeightArray) {
        _subTableViewSectionHeightArray = [NSMutableArray array];
    }
    return _subTableViewSectionHeightArray;
}

#pragma mark - 设置headerView
- (void)setupHeaderView
{
    [self.allSectionOpenButton setTitle:@"全部展开" forState:UIControlStateNormal];
    [self.allSectionOpenButton horizontalCenterTitleAndImage:5];
    [self.storeButton horizontalCenterImageAndTitle:5];
    self.checkItemsLabel.text = @"检查项";
}

#pragma mark -设置TableView
- (void)setupTableView
{
    [self.tableView registerClass:[CustomInspectionTableViewCell class] forCellReuseIdentifier:CELL];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupHeaderView];
    [self setupTableView];
    [self getInspectionResultDetails];
}

#pragma mark - 获取VI检查计划详情数据
- (void)getInspectionResultDetails
{
    @weakify(self);
    [IBTLoadingView showProgressLabel:@"加载中"];
    [RequestManager request_PatrolPlanResult:self.planUuid storeUuid:self.resultsModel.store_uuid success:^(id returnValue) {
        [IBTLoadingView hideHUDWithText:nil];
        @strongify(self);
        if ([BaseViewModel verifyData:returnValue]) {
            [self analyticalData:returnValue[@"data"]];
        }else {
             [IBTLoadingView showTextOnly:[BaseViewModel messageData:returnValue]];
        }
    } failure:^(id errorValue) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:errorValue];
    }];
}

#pragma mark - 解析数据
- (void)analyticalData:(NSDictionary *)dict
{
    InspectionResultDetailsModel *model = [[InspectionResultDetailsModel alloc]initWithDictionary:dict error:nil];
    [self updateHeaderView:model];
    for (NewAnswers *answer in model.answers) {
        if (![self.categoryArray containsObject:answer.questionCategory]) {
            [self.categoryArray addObject:answer.questionCategory];
        }
    }
    NSArray *sortDesc = @[ [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]];
    self.categoryArray = [NSMutableArray arrayWithArray:[self.categoryArray sortedArrayUsingDescriptors:sortDesc]];
    
    //划分数据
    for (NSString *string in self.categoryArray) {
        NSMutableArray *subArray = [NSMutableArray array];
        for (NewAnswers *answer in model.answers) {
            if ([answer.questionCategory isEqualToString:string]) {
                [subArray addObject:answer];
            }
        }
        [self.datasArray addObject:subArray];
    }
    //添加cell是否闭合属性
    for (NSArray *subArray in self.datasArray) {
        NSMutableArray *stateArray = [NSMutableArray array];
        for (int i=0; i<subArray.count; i++) {
            [stateArray addObject:@0];
        }
        [self.sectionOpenControl addObject:stateArray];
    }
    [self.tableView reloadData];
}

#pragma mark -更新HeaderView
- (void)updateHeaderView:(InspectionResultDetailsModel *)model;
{
    self.title = model.store_name;
    self.supervisionNameLabel.text = model.user_name;
    self.taskBegineTimeLabel.text = model.beginTime;
    self.taskFinishTimeLabel.text = model.endTime;
    self.totalScoreLabel.text = [NSString stringWithFormat:@"%.2lf",model.score];
    [self.storeButton setTitle:model.store_name forState:UIControlStateNormal];
    [self.storeButton setTitleColor:[self.resultsModel.realstoreUuid isEqualToString:model.store_uuid] ? [UIColor whiteColor] : [UIColor redColor] forState:UIControlStateNormal];
    [self.storeButton horizontalCenterImageAndTitle:5];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.datasArray.count;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CustomInspectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL forIndexPath:indexPath];
    cell.inspectionVc.delegate = self;
    [cell updateCell:self.datasArray[indexPath.section] rowHeightArray:self.subTableViewHeightArray[indexPath.section] sectionHeightArray:self.subTableViewSectionHeightArray[indexPath.section] closedControlArray:self.sectionOpenControl[indexPath.section]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *heightArray = self.subTableViewHeightArray[indexPath.section];
    NSArray *sectionHeightArray = self.subTableViewSectionHeightArray[indexPath.section];
    CGFloat rowHeight = 0;
    for (int i=0; i<heightArray.count; i++) {
        if ([self.sectionOpenControl[indexPath.section][i] boolValue]) {
            rowHeight += [heightArray[i] floatValue];
        }
        rowHeight += [sectionHeightArray[i] floatValue];
    }
    return rowHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    InspectionDetailsSectionTableViewCell *header = [tableView dequeueReusableCellWithIdentifier:@"InspectionDetailsSectionTableViewCell"];
    header.categoryTitleLabel.text = self.categoryArray[section];
    return header.contentView;
}

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


#pragma mark - <RefreshDelegate>
- (void)refreshSuperTableView
{
    [self.tableView reloadData];
}

#pragma mark - 全部展开或关闭
- (IBAction)allOpenOrCloseButtonClickAction:(UIButton *)sender {
    
    if ([[sender currentTitle] isEqualToString:@"全部展开"]) {
        for (int i=0; i<self.sectionOpenControl.count; i++) {
            NSMutableArray *sectionArray = self.sectionOpenControl[i];
            for (int j=0; j<sectionArray.count; j++) {
                //默认0关闭，1表示打开
                sectionArray[j] = @1;
            }
        }
        sender.selected = YES;
        [sender setTitle:@"全部收起" forState:UIControlStateNormal];
        [self.allSectionOpenButton horizontalCenterTitleAndImage:0];
    }else
    {
        for (int i=0; i<self.sectionOpenControl.count; i++) {
            NSMutableArray *sectionArray = self.sectionOpenControl[i];
            for (int j=0; j<sectionArray.count; j++) {
                //默认0关闭，1表示打开
                sectionArray[j] = @0;
            }
        }
        sender.selected = NO;
        [sender setTitle:@"全部展开" forState:UIControlStateNormal];
        [self.allSectionOpenButton horizontalCenterTitleAndImage:0];
    }
    [self.tableView reloadData];
}


@end
