//
//  GMDiagnosisWorkingTableChooseIdentityView.m
//  Gengmei
//
//  Created by Jessica on 2020/2/19.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDiagnosisWorkingTableChooseIdentityView.h"
#import "UIView+CornerRadius.h"
#import "YYText.h"
#import "NSString+CalculateSize.h"
#import "WMTagObject.h"
#import <GMBase/GMBaseTool.h>
#import <GMBaseWeb/GMWebutil.h>
@import GMHud;
@import GMRouter;

@implementation GMChooseIdentityTagCell
- (void)setup {
    [super setup];
    _contentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _contentBtn.userInteractionEnabled = NO;
    [_contentBtn setImage:[UIImage imageNamed:@"wt_good_unselected_icon"] forState:UIControlStateNormal];
    [_contentBtn setImage:[UIImage imageNamed:@"wt_good_selected_icon"] forState:UIControlStateSelected];
    [_contentBtn setTitleColor:RGBCOLOR_HEX(0x282828) forState:UIControlStateNormal];
    _contentBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
    _contentBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 12, 6, 12);
    _contentBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _contentBtn.titleLabel.font = [UIFont gmFont:14];
    [self.contentView addSubview:_contentBtn];
    
    [_contentBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
}

- (void)updateStatus:(BOOL)status {
    _contentBtn.selected = status;
}

@end

@implementation GMChooseIdentityHeaderView {
    UITapGestureRecognizer *_tap;
}
- (void)setup {
    [super setup];
    _tap = [[UITapGestureRecognizer alloc] init];
    [self addGestureRecognizer:_tap];
    
    _headerIcon = [[GMImageView alloc] init];
    _headerIcon.layer.cornerRadius = 50;
    _headerIcon.layer.masksToBounds = YES;
    [self addSubview:_headerIcon];
    
    [_headerIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 100));
        make.centerX.mas_equalTo(self.mas_centerX);
        make.top.mas_equalTo(0);
    }];
    
    _identityBtn = [GMButton new];
    [_identityBtn setTitleColor:RGBCOLOR_HEX(0x282828) forState:UIControlStateNormal];
    _identityBtn.titleLabel.font = [UIFont gmBoldFont:16];
    [_identityBtn setImage:[UIImage imageNamed:@"wt_identity"] forState:UIControlStateNormal];
    [_identityBtn setImage:[UIImage imageNamed:@"wt_identity_selected"] forState:UIControlStateSelected];
    _identityBtn.selected = NO;
    _identityBtn.userInteractionEnabled = NO;
    [self addSubview:_identityBtn];
    [_identityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(90, 23));
        make.centerX.mas_equalTo(self.headerIcon.mas_centerX);
        make.top.mas_equalTo(self.headerIcon.mas_bottom).offset(10);
    }];
    
}

- (void)addIdentityTarget:(id)target action:(SEL)action {
    [_tap addTarget:target action:action];
}

@end

@interface GMDiagnosisWorkingTableChooseIdentityView()<UICollectionViewDataSource, UICollectionViewDelegate> {
    NSMutableArray *_tagIds;

}
@property(nonatomic, strong)GMCollectionView *projectCollection;
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)GMView *contentView;
@property(nonatomic, strong)GMButton *cancelBtn;
@property(nonatomic, strong)GMButton *openBtn;
@property(nonatomic, strong)UILabel *projectLabel;
@property(nonatomic, strong)GMChooseIdentityHeaderView *doctor;
@property(nonatomic, strong)GMChooseIdentityHeaderView *assistant;
@property(nonatomic, strong)YYLabel *contentLabel;
@property(nonatomic, strong)UILabel *tipLabel;


@end

@implementation GMDiagnosisWorkingTableChooseIdentityView
- (void)setup {
    [super setup];
    _tagIds = [NSMutableArray array];
    self.container.frame = CGRectMake(0, MAINSCREEN_HEIGHT, MAINSCREEN_WIDTH, 312 / 667.0 * MAINSCREEN_HEIGHT);
    [self.container containerRectCorner:CGSizeMake(12, 12) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight];
        
    _cancelBtn = [GMButton new];
    _cancelBtn.enableAdaptive = YES;
    [_cancelBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [_cancelBtn setImage:[UIImage imageNamed:@"wt_cancel_icon"] forState:UIControlStateNormal];
    [self.container addSubview:_cancelBtn];
    [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(15, 15));
        make.right.mas_equalTo(-18);
        make.top.mas_equalTo(18);
    }];
    
    _openBtn = [GMButton new];
    _openBtn.layer.cornerRadius = 22 + ONE_PIXEL;
    _openBtn.layer.masksToBounds = YES;
    _openBtn.enableAdaptive = YES;
    [_openBtn addTarget:self action:@selector(openAction) forControlEvents:UIControlEventTouchUpInside];
    [_openBtn setTitle:@"开启面诊" forState:UIControlStateNormal];
    _openBtn.titleLabel.font = [UIFont gmBoldFont:16];
    _openBtn.userInteractionEnabled = NO;
    [_openBtn setBackgroundColor:RGBCOLOR_HEX(0xFF8C8D) forState:UIControlStateNormal];
    [self.container addSubview:_openBtn];
    [_openBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.right.mas_equalTo(-42);
        make.left.mas_equalTo(42);
        make.bottom.mas_equalTo(-15 - UIView.safeAreaInsetsBottom);
    }];
    
    _scrollView = [UIScrollView new];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.container addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.openBtn.mas_top).offset(-12);
        make.right.left.mas_equalTo(0);
        make.top.mas_equalTo(_cancelBtn.mas_bottom).offset(15);
    }];
    
    //容器视图
    _contentView = [[GMView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    [_scrollView addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_scrollView);
        make.width.mas_equalTo(_scrollView);
    }];
    
    _projectLabel = [[UILabel alloc] init];
    _projectLabel.text = @"擅长的项目（最多3个）";
    _projectLabel.textColor = RGBCOLOR_HEX(0x282828);
    _projectLabel.textAlignment = NSTextAlignmentCenter;
    _projectLabel.font = [UIFont gmBoldFont:16];
    [self.contentView addSubview:_projectLabel];
    [_projectLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(170);
        make.height.mas_equalTo(23);
    }];
    
    [self.contentView addSubview: self.projectCollection];
    [_projectCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(MAINSCREEN_WIDTH);
        make.height.mas_equalTo(113);
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(_projectLabel.mas_bottom).offset(12);
    }];
    
    _tipLabel = [[UILabel alloc] init];
    _tipLabel.text = @"温馨提示：";
    _tipLabel.textColor = RGBCOLOR_HEX(0x282828);
    _tipLabel.textAlignment = NSTextAlignmentLeft;
    _tipLabel.font = [UIFont gmBoldFont:11];
    [self.contentView addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(_projectCollection.mas_bottom).offset(21);
        make.width.mas_equalTo(57);
        make.height.mas_equalTo(15);
    }];
    
    self.contentLabel = [YYLabel new];
    self.contentLabel.preferredMaxLayoutWidth = MAINSCREEN_WIDTH - 30;
    self.contentLabel.userInteractionEnabled = YES;
    self.contentLabel.numberOfLines = 0;
    NSString *content = @"①开启面诊，请确保真实面诊人员的身份跟「身份选择」一致 \n②开启面诊即代表您同意《视频面诊使用管理条例》";
    CGSize size = [content boundingRectWithSize:CGSizeMake(MAINSCREEN_WIDTH - 30, MAXFLOAT) font:[UIFont gmFont:11] lineSpacing:6];
    NSRange privateRange = [content rangeOfString:@"《视频面诊使用管理条例》"];
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:content];
    attribute.yy_lineSpacing = 6;
    attribute.yy_font = [UIFont gmFont:11];
    attribute.yy_color = RGBCOLOR_HEX(0x282828);
    [attribute yy_setTextHighlightRange:privateRange color:RGBCOLOR_HEX(0xFF8C8D) backgroundColor:UIColor.whiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        // 视频面诊使用管理条例
        NSString *host = [GMWebutil getCurrentApiHost];
        NSString *url = [NSString stringWithFormat: @"gengmei://common_webview?url=%@/phantom/about/treatment_agreement",host];
        [[GMRouter sharedInstance] pushScheme:url];
    }];
    self.contentLabel.attributedText = attribute;
    [self.contentView addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(self.tipLabel.mas_bottom).mas_equalTo(5);
        make.height.mas_equalTo(size.height + 5);
        make.bottom.mas_equalTo(_contentView.mas_bottom);
    }];
    
}

- (void)openAction {
    if ([self.openDelegate respondsToSelector:@selector(openWorkTableDidclickedWithTags:)]) {
        [self.openDelegate openWorkTableDidclickedWithTags:_tagIds];
    }
}

- (void)isCanOpen {
    if (_tagIds.count == 0) {
        _openBtn.userInteractionEnabled = NO;
        [_openBtn setBackgroundColor:RGBCOLOR_HEX(0xD5D5D5) forState:UIControlStateNormal];
    } else {
        _openBtn.userInteractionEnabled = YES;
        [_openBtn setBackgroundColor:RGBCOLOR_HEX(0xFF8C8D) forState:UIControlStateNormal];
    }
}

- (void)setTagsArray:(NSArray *)tagsArray {
    _tagsArray = tagsArray;
    [_tagIds removeAllObjects];
    for (WMTagObject *obj in tagsArray) {
        if (obj.isSelected) {
            [_tagIds addObject:@(obj.tagId)];
        }
    }
    
    [self updateConstraints];
    [self.projectCollection reloadData];
}


- (void)updateConstraints {
    [super updateConstraints];
    
    int n = _tagsArray.count / 3.0 > 3 ? (_tagsArray.count / 3 + 1) : _tagsArray.count / 3;
    CGFloat collectionH = n * 28 + (n - 1) * 8;
    [_projectCollection mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(collectionH);
    }];
    
    [_tipLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_projectCollection.mas_bottom).offset(21);
    }];
    
    [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tipLabel.mas_bottom).mas_equalTo(5);
        make.bottom.mas_equalTo(_contentView.mas_bottom);
    }];
    // 实时刷新开启button的UI
    [self isCanOpen];
}

#pragma mark -- UICollectionViewDelegate

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _tagsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMChooseIdentityTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMChooseIdentityTagCell" forIndexPath:indexPath];
    WMTagObject *tagObject = self.tagsArray[indexPath.row];
    [cell.contentBtn setTitle:tagObject.name forState:UIControlStateNormal];
    [cell updateStatus:tagObject.isSelected];
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

//动态设置每行的间距大小
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}

//动态设置每列的间距大小
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((MAINSCREEN_WIDTH - 30 - 24) / 3, 28);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    WMTagObject *tagObject = self.tagsArray[indexPath.row];
    GMChooseIdentityTagCell *cell = (GMChooseIdentityTagCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (!tagObject.isSelected && _tagIds.count < 3) {
        tagObject.isSelected = YES;
        [_tagIds addObject:@(tagObject.tagId)];
    } else if (tagObject.isSelected) {
        tagObject.isSelected = NO;
        if ([_tagIds containsObject:@(tagObject.tagId)]) {
            [_tagIds removeObject:@(tagObject.tagId)];
        }
    } else if (!tagObject.isSelected && _tagIds.count >= 3 ) {
        [[GMBaseTool getCurrentViewController] toast:@"最多选择三个"];
    }
    [cell updateStatus:tagObject.isSelected];
    
    [self isCanOpen];
}

- (GMCollectionView *)projectCollection {
    if (!_projectCollection) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _projectCollection = [[GMCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_projectCollection registerCell:[GMChooseIdentityTagCell class]];
        _projectCollection.backgroundColor = [UIColor whiteColor];
        _projectCollection.delegate = self;
        _projectCollection.dataSource = self;
    }
    return _projectCollection;
}

@end
