//
//  GMDoctorInfoPopupView.m
//  Gengmei
//
//  Created by zhouLiang on 2020/3/6.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDoctorInfoPopupView.h"
#import "GMBasicInfoCardView.h"
#import "RequestHeader.h"
#import "GMLibraryHeader.h"
#import <GMBase/GMBaseTool.h>


@protocol GMDoctorInfoHeaderViewDelegate <NSObject>
- (void)followBtnClick:(BOOL)isFollow;
@end

@interface GMDoctorInfoHeaderView : UIView
@property (nonatomic, strong) UIImageView *icon;
@property (nonatomic, strong) UIImageView *idIcon;
@property (nonatomic, strong) GMLabel *nameLabel;
@property (nonatomic, strong) GMLabel *titleLabel;
/** 医生所在地点 */
@property (nonatomic, strong) UIView *positionView;
@property (nonatomic, strong) GMLabel *numLabel;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, weak) id<GMDoctorInfoHeaderViewDelegate>delegate;
@property (nonatomic, strong) GMConsultantInfoModel *doctorInfoModel;
/** 机构 */
@property (nonatomic, strong) UIView *organView;

@end

@implementation GMDoctorInfoHeaderView
- (instancetype)init {
    if (self = [super init]) {
        [self setUI];
        [self setLayout];
    }
    return self;
}
- (void)setUI {
    [self addSubview:self.icon];
    [self addSubview:self.idIcon];
    [self addSubview:self.nameLabel];
    [self addSubview:self.titleLabel];
    [self addSubview:self.positionView];
    [self addSubview:self.organView];
    [self addSubview:self.numLabel];
    [self addSubview:self.lineView];
}
- (void)setLayout {
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.left.top.mas_equalTo(20);
    }];
    
    [self.idIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(53.5, 15));
        make.centerX.mas_equalTo(self.icon.mas_centerX);
        make.bottom.mas_equalTo(self.icon.mas_bottom).offset(5);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.icon.mas_right).offset(10);
        make.right.mas_equalTo(-5);
        make.top.mas_equalTo(self.icon.mas_top).offset(6);
        make.height.mas_equalTo(18);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nameLabel.mas_left);
        make.height.mas_equalTo(14);
        make.top.equalTo(self.nameLabel.mas_bottom).offset(7);
    }];
    [self.positionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.left.equalTo(self.titleLabel.mas_right).offset(4);
        make.height.mas_equalTo(14);
        make.right.mas_equalTo(0);
    }];
    [self.organView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.nameLabel.mas_left);
        make.height.mas_equalTo(15);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
    }];
    [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(14);
        make.right.mas_equalTo(-15);
        make.top.equalTo(self.icon.mas_bottom).offset(15);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
        make.top.equalTo(self.numLabel.mas_bottom).offset(20);
        make.bottom.equalTo(self);
    }];
}
- (void)setDoctorInfoModel:(GMConsultantInfoModel *)doctorInfoModel {
    _doctorInfoModel = doctorInfoModel;
    [self.icon sd_setImageWithURL:[NSURL URLWithString:doctorInfoModel.portrait]];
    self.nameLabel.text = doctorInfoModel.nickname;
    self.titleLabel.text = [NSString stringWithFormat:@"从业%ld年",(long)doctorInfoModel.employmentDuration];
    [self.positionView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 1) {
            GMLabel *label = (GMLabel *)obj;
            label.text = SafeString(doctorInfoModel.area);
        }
    }];
    
    [self.organView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 1) {
            GMLabel *label = (GMLabel *)obj;
            label.text = doctorInfoModel.hospitalInfo.name;
        }
    }];
    
    self.numLabel.attributedText = [self rateLabelText];
}

- (NSMutableAttributedString *)rateLabelText {
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc] init];
    // 0：不显示1: 好评率 + 接通率 2: 好评率 + 有效面诊人数
    NSAttributedString *subContentA = [[NSAttributedString alloc] initWithString:@"好评率：" attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x282828)}];
    NSAttributedString *subContent = [[NSAttributedString alloc] initWithString:SafeString(_doctorInfoModel.likeRate) attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x51CDC7)}];
    
    NSAttributedString *subContentB = [[NSAttributedString alloc] initWithString:@"  接通率：" attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x282828)}];
    NSAttributedString *subContentC = [[NSAttributedString alloc] initWithString:SafeString(_doctorInfoModel.connectRate) attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x51CDC7)}];
    NSAttributedString *subContentD = [[NSAttributedString alloc] initWithString:@" 有效面诊：" attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x282828)}];
    NSAttributedString *subContentE = [[NSAttributedString alloc] initWithString:SafeString(_doctorInfoModel.consultPeopleNumber) attributes:@{NSFontAttributeName: [UIFont gmFont:12], NSForegroundColorAttributeName: RGBCOLOR_HEX(0x51CDC7)}];
    [content appendAttributedString: subContentA];
    [content appendAttributedString: subContent];
    [content appendAttributedString: subContentB];
    [content appendAttributedString: subContentC];
    [content appendAttributedString: subContentD];
    [content appendAttributedString: subContentE];
    return content;
}

- (UIImageView *)icon {
    if (!_icon) {
        _icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        _icon.contentMode = UIViewContentModeScaleAspectFill;
        _icon.layer.cornerRadius = 40.f;
        _icon.layer.masksToBounds = YES;
    }
    return _icon;
}
- (UIImageView *)idIcon {
    if (!_idIcon) {
        _idIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"to_face_con_text_icon"]];
        _idIcon.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _idIcon;
}
- (GMLabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:16];
        _nameLabel.font = [UIFont gmBoldFont:16];
        _nameLabel.text = @"赵宏伟";
    }
    return _nameLabel;
}
- (GMLabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x8E8E8E)  fontSize:12];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _titleLabel;
}
- (UIView *)positionView {
    if (!_positionView) {
        _positionView = [[UIView alloc] init];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cityLocatedBlue"]];
        [_positionView addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(14, 14));
            make.left.mas_equalTo(0);
            make.centerY.equalTo(_positionView.mas_centerY);
        }];
        GMLabel *label = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x8E8E8E)  fontSize:10];
        [_positionView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).offset(2);
            make.centerY.equalTo(_positionView.mas_centerY);
        }];
    }
    return _positionView;
}
- (GMLabel *)numLabel {
    if (!_numLabel) {
        _numLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x8E8E8E)  fontSize:12];
    }
    return _numLabel;
}
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
    }
    return _lineView;
}

- (UIView *)organView {
    if (!_organView) {
        _organView = [[UIView alloc] init];
        GMLabel *oneLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:13];
        oneLabel.text = @"机构：";
        GMLabel *twoLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:13];
        twoLabel.font = [UIFont gmBoldFont:13];
        twoLabel.userInteractionEnabled = YES;
        twoLabel.textAlignment = NSTextAlignmentLeft;
        [_organView addSubview:oneLabel];
        [_organView addSubview:twoLabel];
        [oneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(13);
            make.centerY.mas_equalTo(0);
        }];
        [twoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(oneLabel.mas_right);
            make.right.mas_equalTo(0);
            make.centerY.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
    }
    return _organView;
}
@end

@interface GMDoctorInfoPopupView ()<GMDoctorInfoHeaderViewDelegate>
/** 顶部信息view */
@property (nonatomic, strong) GMDoctorInfoHeaderView *headerView;
/** 擅长项目 */
@property (nonatomic, strong) GMLabel *projectLabel;
@property (nonatomic, strong) UIView *labelView;
/** 简介 */
@property (nonatomic, strong) GMLabel *introduceLabel;
@property (nonatomic, strong) GMLabel *infoLabel;

/** 底部按钮 */
@property (nonatomic, strong) UIButton *faceToFaceBtn;
@property (nonatomic, strong) GMButton *cancelBtn;
@end

@implementation GMDoctorInfoPopupView

- (void)setup {
    [super setup];
    [self setUI];
    [self setLayout];
    self.container.layer.cornerRadius = 4.f;
    self.container.layer.masksToBounds = YES;
}
- (void)setUI {
    self.animationType = GMPopupAnimationTypeSpringScaleFromCenter;
    
    [self.container addSubview:self.headerView];
    
    [self.container addSubview:self.projectLabel];
    [self.container addSubview:self.labelView];
    
    [self.container addSubview:self.introduceLabel];
    [self.container addSubview:self.infoLabel];
    
    
    [self.container addSubview:self.faceToFaceBtn];
    
    [self addSubview:self.cancelBtn];
}
- (void)setLayout {
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(MAINSCREEN_WIDTH-70, 147));
        make.top.left.mas_equalTo(0);
    }];
    [self.projectLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(13);
        make.top.equalTo(self.headerView.mas_bottom).offset(22);
    }];
    [self.labelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.projectLabel.mas_right);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(42);
        make.centerY.equalTo(self.projectLabel.mas_centerY);
    }];
    [self.introduceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(13);
        make.top.equalTo(self.labelView.mas_bottom).offset(10.5);
    }];
    [self.infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.introduceLabel.mas_right);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(90);
        make.top.equalTo(self.labelView.mas_bottom).offset(8);
    }];
    
    [self.faceToFaceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.container.mas_centerX);
        make.left.mas_equalTo(32);
        make.right.mas_equalTo(-32);
        make.height.mas_equalTo(45);
        make.top.equalTo(self.infoLabel.mas_bottom).offset(20);
    }];
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(36, 36));
        make.top.equalTo(self.container.mas_bottom).offset(28);
        make.centerX.mas_equalTo(0);
    }];
}
- (void)setModel:(GMConsultantInfoModel *)model {
    _model = model;
    self.headerView.doctorInfoModel = model;
    __block CGFloat horMargin = 0;//横向
    __block CGFloat verMargin = 0;//纵向
    __block CGFloat height = 0;//labelView高度
    __block NSInteger numberOfLines = 1;
    [model.goodAt enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GMLabel *label = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x4DBBB5) fontSize:11];
        label.layer.cornerRadius = 3.f;
        label.layer.masksToBounds = YES;
        label.backgroundColor = RGBCOLOR_HEX(0xEEF8F7);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = obj;
        CGFloat width = [label sizeThatFits:CGSizeMake(66, 17)].width + 22;
        if (horMargin + width > MAINSCREEN_WIDTH - 85 - 80) {
            horMargin = 0;
            numberOfLines++;
        }
        label.frame = CGRectMake(horMargin, verMargin, width, 17);
        if (numberOfLines == 2) {//2行直接返回，最多一行
            *stop = YES;
        }else {
            [self.labelView addSubview:label];
            horMargin = horMargin + 6 + width;
            height = CGRectGetMaxY(label.frame);
        }
        if (idx >= 2) {//产品要求最多只展示3个
            *stop = YES;
        }
    }];    
    //标签
    [self.labelView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    //简介
    self.infoLabel.text = model.introduction;
    CGFloat infoLabelHeight = [self.infoLabel sizeThatFits:CGSizeMake(MAINSCREEN_WIDTH - 85 - 100, 50)].height;
    [self.infoLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(infoLabelHeight);
    }];
    
    self.faceToFaceBtn.hidden = model.status != 2;
    
    //重新布局
    [self.container mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(0);
        make.width.mas_equalTo(MAINSCREEN_WIDTH-80);
        if (model.status == 2) {//两个按钮同时显示
            make.bottom.equalTo(self.faceToFaceBtn.mas_bottom).offset(20);
        }else {
            make.bottom.equalTo(self.infoLabel.mas_bottom).offset(20);
        }
    }];
}

- (void)cancelClickMethod {
    [self hide];
}
- (void)followBtnClick:(BOOL)isFollow {
    if ([self.delegate respondsToSelector:@selector(followBtnClick:)]) {
        [self.delegate followBtnClick:isFollow];
    }
}
#pragma mark - 视频面诊
- (void)faceToFaceBtnClickMethod {
    if (self.model.status != 2) {//在线
        [self onlineBtnClickMethod];
    }else {//1v1面诊
        [self faceRandomMethod];
    }
}
#pragma mark - 在线
- (void)onlineBtnClickMethod {
    BOOL status = (BOOL)[[GMRouter sharedInstance] pushScheme:@"gengmei://gm_showLoginViewIfNeeded"];
    if (status) {
        return;
    }

    [self hide];
    [Phobos track:@"on_click_button" attributes:@{@"page_name":[GMBaseTool getCurrentViewController].pageName,
                                                  @"tab_name":self.tabName,
                                                  @"button_name":@"online_consult",
                                                  @"doctor_id":self.model.counsellorId,
                                                  @"counsellor_type":@(2),
                                                  @"referrer_link":(self.referrerLink ? : @[])
    }];
    [[GMRouter sharedInstance] pushScheme:self.model.messageUrl];
}
#pragma mark - 随机1v1面诊
- (void)faceRandomMethod {
    BOOL status = (BOOL)[[GMRouter sharedInstance] pushScheme:@"gengmei://gm_showLoginViewIfNeeded"];

    if (status) {
        return;
    }

    [Phobos track:@"on_click_button" attributes:@{@"page_name":[GMBaseTool getCurrentViewController].pageName,
                                                  @"tab_name":self.tabName,
                                                  @"button_name":@"视频面诊",
                                                  @"doctor_id":self.model.counsellorId,
                                                  @"counsellor_type":@(2),
                                                  @"referrer_link":(self.referrerLink ? : @[])
    }];
    __weak __typeof(self)weakSelf = self;
    
    [GMNetworking requestOCWithApi:API_CONSULTATION_COUNSEL_BLOCK_INFO method:GMHTTPMethodGet parameters:@{} completion:^(GMResponseOC * responseOC) {
        if (responseOC.isSuccess) {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseOC.responseData options:NSJSONReadingMutableLeaves error:nil];
            NSDictionary *dict = response[@"block_info"];
            NSString *alert = dict[@"alert"];
            [weakSelf hide];
            if (![alert isNonEmpty]) {
                //未被禁止
                //请求用户填面诊信息的弹框
                GMBasicInfoCardView *cardView = [GMBasicInfoCardView new];
                cardView.referer = [GMBaseTool getCurrentViewController].pageName;
                cardView.counsellorId = weakSelf.model.counsellorId;
                cardView.doctorId = @"";
                cardView.tabName = self.tabName;
                [GMBasicInfoCardView showWithCorrectFrameView:cardView resultBlock:nil];
            }else {
                //被禁止
                if (weakSelf.blockInfoCallback) {
                    weakSelf.blockInfoCallback(alert);
                }
            }
        } else {
            [GMHudModule toast:responseOC.message];

        }
    }];

}

- (GMDoctorInfoHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[GMDoctorInfoHeaderView alloc] init];
        _headerView.delegate = self;
    }
    return _headerView;
}
- (GMLabel *)projectLabel {
    if (!_projectLabel) {
        _projectLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:13];
        _projectLabel.text = @"擅长：";
    }
    return _projectLabel;
}
- (UIView *)labelView {
    if (!_labelView) {
        _labelView = [[UIView alloc] init];
    }
    return _labelView;
}
- (GMLabel *)introduceLabel {
    if (!_introduceLabel) {
        _introduceLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:13];
        _introduceLabel.text = @"简介：";
    }
    return _introduceLabel;
}
- (GMLabel *)infoLabel {
    if (!_infoLabel) {
        _infoLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x999999) fontSize:13];
        _infoLabel.numberOfLines = 0;
    }
    return _infoLabel;
}

- (UIButton *)faceToFaceBtn {
    if (!_faceToFaceBtn) {
        _faceToFaceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_faceToFaceBtn addTarget:self action:@selector(faceToFaceBtnClickMethod) forControlEvents:(UIControlEventTouchUpInside)];
        _faceToFaceBtn.multiControlTimeInterva = 2.f;
        [_faceToFaceBtn setBackgroundColor:RGBCOLOR_HEX(0xFF8C8D)];
        [_faceToFaceBtn setTitle:@"立即视频面诊" forState:(UIControlStateNormal)];
        [_faceToFaceBtn setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
        [_faceToFaceBtn.titleLabel setFont:[UIFont gmBoldFont:16]];
        [_faceToFaceBtn setImage:[UIImage imageNamed:@"to_face_camera"] forState:(UIControlStateNormal)];
        _faceToFaceBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
        _faceToFaceBtn.layer.cornerRadius = 22.5f;
        _faceToFaceBtn.layer.masksToBounds = YES;
    }
    return _faceToFaceBtn;
}

- (GMButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [GMButton buttonWithType:(UIButtonTypeCustom)];
        [_cancelBtn setImage:[UIImage imageNamed:@"to_face_cancel"] forState:(UIControlStateNormal)];
        [_cancelBtn addTarget:self action:@selector(cancelClickMethod) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _cancelBtn;
}
@end
