//
//  QuestionDealWithView.m
//  redstar
//
//  Created by admin on 16/6/5.
//  Copyright © 2016年 ZWF. All rights reserved.
//

#import "QuestionDealWithView.h"
#import "SolvedTypeTableViewCell.h"
#import "FeedContentTableCell.h"

#import "HttpClient.h"
#import <MBProgressHUD.h>

#import "SelectCategaryViewController.h"

#define kSolvedTypeTableViewCell @"solveTypeTableCell"
#define kFeedContentTableCell @"feedContentTableCell"

@interface QuestionDealWithView ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIButton *selectButton;

@property (nonatomic, assign) BOOL isComplete;
@property (nonatomic, assign) BOOL isLoad;

@property (nonatomic, strong) NSMutableDictionary *groupUuidDict;
@property (nonatomic, strong) NSMutableArray *categoryArray;
@property (nonatomic, strong) NSMutableArray *questionArray;

@property (nonatomic, assign) NSInteger groupNum;
@property (nonatomic, assign) NSInteger categoryNum;


@end

@implementation QuestionDealWithView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}


#pragma mark - Private Methods
- (void)setup
{
    self.titleLabel.text = @"问题处理";
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    _selectButton = [[UIButton alloc] init];
    _selectButton.tag = 323118;
    
    
    
    
    _isComplete = NO;
    _isLoad = NO;
    
    _groupNum = 0;
    _categoryNum = 0;
    
    self.groupUuidDict = [NSMutableDictionary dictionary];
    self.categoryArray = [NSMutableArray array];
    self.questionArray = [NSMutableArray array];
    
    [self requestGroupTitle];

}

- (void)selectCategaryWithIndexPath:(NSIndexPath *)indexPath rowNum:(NSInteger)rowNum{
    
    if (rowNum == 0) {
        _groupNum = indexPath.row;
        _categoryNum = 0;
        if (_categoryArray.count != 0) {
            NSString *nameStr = [NSString stringWithFormat:@"%@", _categoryArray[_groupNum]];
            [self requestCategoryWithGroupUuid:[_groupUuidDict objectForKey:nameStr]];
        }
 
    } else {
        _categoryNum = indexPath.row;
        [self.tableView reloadData];
    }
}

// 请求问题专业组
- (void)requestGroupTitle
{
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:[NSString stringWithFormat:@"%@%@", kRedStarURL, kQuestionGroupURL]];
    [httpClient getQuestionGroupWithCompletion:^(id response, NSError *error) {
        NSDictionary *dataDict = response[@"data"];
        NSArray *dataArray = dataDict[@"records"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        NSMutableArray *nameArray = [NSMutableArray array];
        for (NSDictionary *groupDict in dataArray) {
            NSString *name = [NSString stringWithFormat:@"%@", groupDict[@"name"]];
            NSString *groupUuid = [NSString stringWithFormat:@"%@", groupDict[@"uuid"]];
            [dict setObject:groupUuid forKey:name];
            [nameArray addObject:name];
        }
        _groupUuidDict = dict;
        _categoryArray = nameArray;
        _isComplete = YES;
        
        if (nameArray.count != 0) {
            NSString *nameStr = [NSString stringWithFormat:@"%@", nameArray[0]];
            [self requestCategoryWithGroupUuid:[dict objectForKey:nameStr]];
        }
        
        [self.tableView reloadData];
    }];
}

- (void)requestCategoryWithGroupUuid:(NSString *)groupUuid
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",kRedStarURL, kQuestionCategoryURL, groupUuid];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    HttpClient *http = [[HttpClient alloc] initWithUrl:url];
    [http getQuestionCategoryWithCompletion:^(id response, NSError *error) {
        NSDictionary *dictData = response[@"data"];
        NSArray *array = dictData[@"records"];
        NSMutableArray *categoryArray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            NSString *category = [NSString stringWithFormat:@"%@", dict[@"name"]];
            [categoryArray addObject:category];
        }
        _questionArray = categoryArray;
        _isLoad = YES;
        [self.tableView reloadData];
    }];
}


#pragma mark - lazy loading
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.userInteractionEnabled = YES;
        _titleLabel.font = [UIFont systemFontOfSize:18.0];
        _titleLabel.textColor = kLightBlack;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
        _titleLabel.backgroundColor = kSectionBackGroundColor;
        [self addSubview:_titleLabel];
        
        // 顶端
        NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self addConstraint:titleTop];
        
        // 左边
        NSLayoutConstraint *titleLeft = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self addConstraint:titleLeft];
        
        // 右边
        NSLayoutConstraint *titleRight = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self addConstraint:titleRight];
        
        // 右边
        NSLayoutConstraint *titleHeight = [NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:47];
        [self addConstraint:titleHeight];
        
    }
    return _titleLabel;
}

- (UIButton *)quitBtn
{
    if (!_quitBtn) {
        _quitBtn = [[UIButton alloc] init];
        _quitBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [_quitBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [self addSubview:_quitBtn];
        [self insertSubview:_quitBtn aboveSubview:_titleLabel];
        
        // 顶端
        NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_quitBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self addConstraint:titleTop];
        
        // 左边
        NSLayoutConstraint *titleWidth = [NSLayoutConstraint constraintWithItem:_quitBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:47];
        [self addConstraint:titleWidth];
        
        // 右边
        NSLayoutConstraint *titleRight = [NSLayoutConstraint constraintWithItem:_quitBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self addConstraint:titleRight];
        
        // 右边
        NSLayoutConstraint *titleHeight = [NSLayoutConstraint constraintWithItem:_quitBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:47];
        [self addConstraint:titleHeight];
        
    }
    return _quitBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
    }
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.translatesAutoresizingMaskIntoConstraints = NO;

    [self addSubview:_tableView];
    
    // 顶端
    NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.titleLabel attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
    [self addConstraint:titleTop];
    
    // 左边
    NSLayoutConstraint *titleLeft = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
    [self addConstraint:titleLeft];
    
    // 右边
    NSLayoutConstraint *titleRight = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
    [self addConstraint:titleRight];
    
    // 右边
    NSLayoutConstraint *titleBottom = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
    [self addConstraint:titleBottom];
    
    return _tableView;
}


#pragma mark - UITableView Delegate/DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 2) {
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"groupAndCategaryCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"groupAndCategaryCell"];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:17.0];
        cell.textLabel.textColor = kdetailCellTitleColor;
        if (indexPath.row == 0) {
            cell.textLabel.text = @"专业组";
            if (!self.groupTitle) {
                self.groupTitle = [[UILabel alloc] init];
            }
            _groupTitle.translatesAutoresizingMaskIntoConstraints = NO;
            _groupTitle.font = [UIFont systemFontOfSize:17.0];
            _groupTitle.textColor = [UIColor colorWithRed:136 /255.0 green:137 /255.0 blue:138 /255.0 alpha:1.0];;
            if (_categoryArray.count == 0) {
                _groupTitle.text = @"";
            } else {
                if (_isComplete) {
                    _groupTitle.text =_categoryArray[_groupNum];
                } else {
                    _groupTitle.text = @"";
                }
            }
            [cell.contentView addSubview:_groupTitle];
            
            // 顶端
            NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_groupTitle attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
            [cell.contentView addConstraint:titleTop];
            
            // 左边
            NSLayoutConstraint *titleLeft = [NSLayoutConstraint constraintWithItem:_groupTitle attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:110];
            [cell.contentView addConstraint:titleLeft];
            
            // 右边
            NSLayoutConstraint *titleWidth = [NSLayoutConstraint constraintWithItem:_groupTitle attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
            [cell.contentView addConstraint:titleWidth];
            
            // 高度
            NSLayoutConstraint *titleHeight = [NSLayoutConstraint constraintWithItem:_groupTitle attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40];
            [cell.contentView addConstraint:titleHeight];
            
        } else {
            cell.textLabel.text = @"问题分类";
            if (!self.categoryTitle) {
                self.categoryTitle = [[UILabel alloc] init];
            }
            _categoryTitle.translatesAutoresizingMaskIntoConstraints = NO;
            _categoryTitle.font = [UIFont systemFontOfSize:17.0];
            _categoryTitle.textColor = [UIColor colorWithRed:136 /255.0 green:137 /255.0 blue:138 /255.0 alpha:1.0];
            if (_questionArray.count == 0) {
                _categoryTitle.text = @"";
            } else {
                if (_isLoad) {
                    _categoryTitle.text = _questionArray[_categoryNum];
                } else {
                    _categoryTitle.text = @"";
                }
            }
            [cell.contentView addSubview:_categoryTitle];
            
            // 顶端
            NSLayoutConstraint *titleTop = [NSLayoutConstraint constraintWithItem:_categoryTitle attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
            [cell.contentView addConstraint:titleTop];
            
            // 左边
            NSLayoutConstraint *titleLeft = [NSLayoutConstraint constraintWithItem:_categoryTitle attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:110];
            [cell.contentView addConstraint:titleLeft];
            
            // 右边
            NSLayoutConstraint *titleWidth = [NSLayoutConstraint constraintWithItem:_categoryTitle attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
            [cell.contentView addConstraint:titleWidth];
            
            // 高度
            NSLayoutConstraint *titleHeight = [NSLayoutConstraint constraintWithItem:_categoryTitle attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40];
            [cell.contentView addConstraint:titleHeight];
        }
        
        return cell;
    } else if (indexPath.row == 2) {
        SolvedTypeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kSolvedTypeTableViewCell];
        if (!cell) {
            cell = [[SolvedTypeTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kSolvedTypeTableViewCell];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLabel.text = @"解决办法";
        [cell.quesBtn addTarget:self action:@selector(solveQues:) forControlEvents:UIControlEventTouchUpInside];
        [cell.FAQBtn addTarget:self action:@selector(solveQues:) forControlEvents:UIControlEventTouchUpInside];
        [cell.SOPBtn addTarget:self action:@selector(solveQues:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else {
        FeedContentTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kFeedContentTableCell];
        if (!cell) {
            cell = [[FeedContentTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kFeedContentTableCell];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLabel.text = @"反馈信息";
        UIImage *image = [UIImage imageNamed:@"textbox"];
        UIImage *resizingName = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 24, 24) resizingMode:UIImageResizingModeStretch];
        cell.backImageView1.image = resizingName;
        
        

        self.titleTextView.tag = 1001;
        _titleTextView.font = [UIFont systemFontOfSize:15.0];
        _titleTextView.translatesAutoresizingMaskIntoConstraints = NO;
        _titleTextView.backgroundColor = [UIColor clearColor];
        [cell.backImageView1 addSubview:_titleTextView];
        
        NSLayoutConstraint *contentTop = [NSLayoutConstraint constraintWithItem:_titleTextView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.backImageView1 attribute:NSLayoutAttributeTop multiplier:1.0 constant:1];
        [cell.backImageView1 addConstraint:contentTop];
        
        NSLayoutConstraint *contentLeft = [NSLayoutConstraint constraintWithItem:_titleTextView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.backImageView1 attribute:NSLayoutAttributeLeft multiplier:1.0 constant:1];
        [cell.backImageView1 addConstraint:contentLeft];
        
        NSLayoutConstraint *contentRight = [NSLayoutConstraint constraintWithItem:_titleTextView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.backImageView1 attribute:NSLayoutAttributeRight multiplier:1.0 constant:-1];
        [cell.backImageView1 addConstraint:contentRight];
        
        NSLayoutConstraint *contentHeight = [NSLayoutConstraint constraintWithItem:_titleTextView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.backImageView1 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-1];
        [cell.backImageView1 addConstraint:contentHeight];
        
        
        
        if (!_placeholderLabel1) {
                _placeholderLabel1 = [[UILabel alloc] init];
        }
        _placeholderLabel1.translatesAutoresizingMaskIntoConstraints = NO;
        _placeholderLabel1.font = [UIFont systemFontOfSize:15.0];
        _placeholderLabel1.textColor = kOnLineCellDetailColor;
        _placeholderLabel1.text = @"请输入反馈内容...";

        [self.titleTextView addSubview:_placeholderLabel1];
        
        NSLayoutConstraint *placeholderTop = [NSLayoutConstraint constraintWithItem:_placeholderLabel1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.titleTextView attribute:NSLayoutAttributeTop multiplier:1.0 constant:2];
        [self.titleTextView addConstraint:placeholderTop];
        
        NSLayoutConstraint *placeholderLeft = [NSLayoutConstraint constraintWithItem:_placeholderLabel1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.titleTextView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:5];
        [self.titleTextView addConstraint:placeholderLeft];
        
        NSLayoutConstraint *placeholderRight = [NSLayoutConstraint constraintWithItem:_placeholderLabel1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.titleTextView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.titleTextView addConstraint:placeholderRight];
        
        NSLayoutConstraint *placeholderHeight = [NSLayoutConstraint constraintWithItem:_placeholderLabel1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
        [self.titleTextView addConstraint:placeholderHeight];
        



        [cell.changeBtn addTarget:self action:@selector(changeClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.solveBtn addTarget:self action:@selector(solveClick:) forControlEvents:UIControlEventTouchUpInside];

        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *tempArray = [NSArray array];
    if (indexPath.row == 0) {
        tempArray = _categoryArray;
        if ([_delegate respondsToSelector:@selector(tableDidSelectAtIndexPath:nameArray:)]) {
            [_delegate tableDidSelectAtIndexPath:indexPath nameArray:tempArray];
        }
    } else if (indexPath.row == 1 ){
        tempArray = _questionArray;
        if ([_delegate respondsToSelector:@selector(tableDidSelectAtIndexPath:nameArray:)]) {
            [_delegate tableDidSelectAtIndexPath:indexPath nameArray:tempArray];
        }
    } else {
        
    }
    
    
}

- (void)solveQues:(UIButton *)sender {
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    SolvedTypeTableViewCell *cell = (SolvedTypeTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    if (sender.tag - 323118 == 0) {
        sender.selected = YES;
        cell.FAQBtn.selected = NO;
        cell.SOPBtn.selected = NO;
    } else if (sender.tag - 323118 == 1) {
        sender.selected = YES;
        cell.quesBtn.selected = NO;
        cell.SOPBtn.selected = NO;
    } else {
        sender.selected = YES;
        cell.quesBtn.selected = NO;
        cell.FAQBtn.selected = NO;
    }
    _selectButton = sender;
    [self.tableView reloadData];

}

- (void)changeClick:(UIButton *)sender {
    NSString *solutionType = nil;
    if (_selectButton.tag - 323118 == 0) {
        solutionType = @"question";
    } else if (_selectButton.tag - 323118 == 1){
        solutionType = @"faq";
    } else {
        solutionType = @"sop";
    }
        
    if (_delegate && [_delegate respondsToSelector:@selector(requestProlemDealWithResultWithGroupText:categoryText:solutionType:optionType:)]) {
        [_delegate requestProlemDealWithResultWithGroupText:_groupTitle.text categoryText:_categoryTitle.text solutionType:solutionType  optionType:@"update"];
    }
}


- (void)solveClick:(UIButton *)sender {
    
    if (_delegate && [_delegate respondsToSelector:@selector(requestProlemDealWithResultWithGroupText:categoryText:solutionType:optionType:)]) {
        [_delegate requestProlemDealWithResultWithGroupText:_groupTitle.text categoryText:_categoryTitle.text solutionType:@"question"  optionType:@"resolve"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < 2) {
        return 50;
    } else if (indexPath.row == 2) {
        return 88;
    } else {
        return 218;
    }
}
// section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

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

- (UITextView *)titleTextView {
    if (!_titleTextView) {
        _titleTextView = [[UITextView alloc] init];
    }
    return _titleTextView;
}

@end
