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

#import "GMEndConsultView.h"
#import "GMEditQuesPartController.h"

@interface GMEndConsultView () <UITextViewDelegate>

@property (nonatomic, assign) GMEndConsultViewType type;
@property (nonatomic, strong) UIView *grayLineView;
@property (nonatomic, strong) GMLabel *titleLabel;
@property (nonatomic, strong) GMButton *confirmButton;
@property (nonatomic, strong) GMButton *cancelButton;

@property (nonatomic, strong) GMButton *complaintUserButton; // 投诉用户按钮
@property (nonatomic, strong) GMButton *laterButton; // 稍后填写按钮
@property (nonatomic, strong) GMLabel *tipLabel; // 用户申诉提示语

@property (nonatomic, strong) GMImageView *textImageView; // 投诉弹窗输入框背景图
@property (nonatomic, strong) GMPlaceholderTextContainer *textView; // 投诉弹窗输入框
@property (nonatomic, strong) GMLabel *countLabel;// 投诉弹窗输入框字数

@property (nonatomic, strong) UIView *starView; // 星星view
@property (nonatomic, strong) GMLabel *bottomLabel; // 星星下面的一行字
@property (nonatomic, assign) NSInteger starNum; // 星星个数
@end

@implementation GMEndConsultView

- (instancetype)initWithType:(GMEndConsultViewType)type starNum:(NSInteger)starNum{
    if (self = [super init]) {
        self.starNum = starNum;
        self.type = type;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)setup {
    [super setup];
    [self setUI];
    [self setLayout];
    [self containerRectCorner:self.container];
}
- (void)setUI {
    self.animationType = GMPopupAnimationTypeFlipFromBottom;
    [self.container addSubview:self.grayLineView];
    [self.container addSubview:self.titleLabel];
    [self.container addSubview:self.cancelButton];
    [self.container addSubview:self.confirmButton];
    [self.container addSubview:self.laterButton];
    [self.container addSubview:self.complaintUserButton];
    [self.container addSubview:self.tipLabel];
    [self.container addSubview:self.textImageView];
    [self.textImageView addSubview:self.textView];
    [self.textImageView addSubview:self.countLabel];
    [self.container addSubview:self.starView];
    [self.container addSubview:self.bottomLabel];
}
- (void)setLayout {
    [self.grayLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_equalTo(10);
        make.size.mas_equalTo(CGSizeMake(50, 5));
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_offset(75);
    }];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(17, 17));
        make.top.mas_offset(20);
        make.right.mas_offset(-20);
    }];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(45);
        make.bottom.mas_offset(-15);
        make.left.mas_offset(42);
        make.right.mas_offset(-42);
    }];
    [self.laterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(45);
        make.bottom.mas_offset(-15);
        make.left.mas_offset(42);
        make.right.mas_offset(-42);
    }];
    [self.complaintUserButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(20);
        make.width.mas_offset(80);
        make.top.mas_offset(64);
        make.right.mas_offset(-20);
    }];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(78);
        make.centerX.mas_equalTo(0);
    }];
    [self.textImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(74);
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_offset(87);
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(6, 4, 34, 4));
    }];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-12);
        make.right.mas_offset(-10);
        make.height.mas_offset(14);
    }];
    [self.starView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(98);
        make.size.mas_equalTo(CGSizeMake(238, 38));
    }];
    [self.bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(self.starView.mas_bottom).offset(12);
        make.left.right.mas_equalTo(0);
    }];
}

- (void)setType:(GMEndConsultViewType)type {
    _type = type;
    [self creatStarMethod];
    if ((type == GMEndConsultViewTypeGrayStar) || (type == GMEndConsultViewTypeViewEvaluate)) {
        self.bottomLabel.hidden = self.starView.hidden = NO;
    }else {
        self.bottomLabel.hidden = self.starView.hidden = YES;
    }
    if ((type == GMEndConsultViewTypeReport) || (type == GMEndConsultViewTypeGrayStar) || type == GMEndConsultViewTypeDefault) {
        self.complaintUserButton.hidden = NO;
    }else {
        self.complaintUserButton.hidden = YES;
    }
    if (type == GMEndConsultViewTypeUserComplaint || type == GMEndConsultViewTypeDoctorComplaint) {
        self.textImageView.hidden = NO;
    }else {
        self.textImageView.hidden = YES;
    }
    self.tipLabel.hidden = type != GMEndConsultViewTypeUserComplaint;
    self.laterButton.hidden = type != GMEndConsultViewTypeReport;
    self.confirmButton.hidden = type == GMEndConsultViewTypeViewEvaluate;
    
    self.titleLabel.text = @[@"此次面诊不需要填写面诊报告~", @"面诊结束了，记得填写面诊报告~", @"问题申诉提交成功", @"请输入投诉原因",@"申诉意见", @"更美邀请您对本次服务进行评价", @"本次服务评价"][type];
    NSArray *buttonTitle = @[@"知道了", @"立即填写", @"知道了", @"匿名提交", @"匿名提交", @"匿名提交", @""];
    [self.confirmButton setTitle:buttonTitle[type] forState:UIControlStateNormal];
    
    CGFloat containerHeight = [@[@(243), @(300), @(220), @(243), @(270), @(248), @(180)][type] floatValue];
    CGFloat titleTop = [@[@(105), @(105), @(75), @(30), @(30), @(30), @(30)][type] floatValue];
    
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(titleTop);
    }];
    [self.confirmButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(type == GMEndConsultViewTypeReport ? -65 - UIView.safeAreaInsetsBottom : -15 - UIView.safeAreaInsetsBottom);
    }];
    [self.starView mas_updateConstraints:^(MASConstraintMaker *make) {
        if (self.type == GMEndConsultViewTypeViewEvaluate) {
            make.top.mas_equalTo(70);
        }else {
            make.top.mas_equalTo(98);
        }
    }];
    if (type == GMEndConsultViewTypeDoctorComplaint) {
        [self.textImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(74);
        }];
    }else if(type == GMEndConsultViewTypeUserComplaint){
        [self.textImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(100);
        }];
    }
    [self.container layoutIfNeeded];
    [self.container mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(containerHeight + UIView.safeAreaInsetsBottom);
        make.bottom.mas_equalTo(0);
    }];
    self.container.frame = CGRectMake(0, MAINSCREEN_HEIGHT - containerHeight, MAINSCREEN_WIDTH, containerHeight);
}
- (void)setDesc:(NSString *)desc {
    //星级描述
    self.bottomLabel.text = desc;
}
- (void)setShowComplaint:(BOOL)showComplaint {
    self.complaintUserButton.hidden = !showComplaint;
}
- (void)setStarContentArray:(NSArray<GMStarInfoObject *> *)starContentArray {
    _starContentArray = starContentArray;
}
- (void)creatStarMethod {
    for (int i = 0; i < 5; i++) {
        GMButton *button = [GMButton buttonWithType:(UIButtonTypeCustom)];
        button.tag = i+1000;
        button.enableAdaptive = YES;
        NSString *imageStr = @"to_face_gray_star";
        if (self.type == GMEndConsultViewTypeViewEvaluate) {
            if (i <= self.starNum - 1) {
                imageStr = @"to_face_oriange_star";
            }
            [button setImage:[UIImage imageNamed:imageStr] forState:(UIControlStateNormal)];
            self.confirmButton.hidden = YES;
            self.container.height = 180.f;
        }else {
            [button setImage:[UIImage imageNamed:@"to_face_gray_star"] forState:(UIControlStateNormal)];
            [button setImage:[UIImage imageNamed:@"to_face_oriange_star"] forState:(UIControlStateSelected)];
            [button addTarget:self action:@selector(clickStarMethod:) forControlEvents:(UIControlEventTouchUpInside)];
        }
        [_starView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(i*50);
            make.size.mas_equalTo(CGSizeMake(38, 38));
        }];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *string = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if (string.length > 100) {
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
    self.countLabel.text = [NSString stringWithFormat:@"还能输入%d字", MAX((100 - textView.text.length), 0)];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    CGRect keyboredBeginFrame = [notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue];
    CGRect keyboredEndFrame = [notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat duration = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    [UIView animateWithDuration:duration animations:^{
        CGFloat yDistance = fabs(keyboredBeginFrame.origin.y - keyboredEndFrame.origin.y);
        if (!floor(yDistance)) {
            return;
        }
        // 键盘弹出或变化
        if (keyboredBeginFrame.origin.y > keyboredEndFrame.origin.y || (keyboredBeginFrame.size.height != yDistance)) {
            self.container.bottom = keyboredEndFrame.origin.y;
        }
        //键盘收起
        else{
            self.container.bottom = MAINSCREEN_HEIGHT;
        }
    } completion:nil];
}

- (void)complaint {
    [self.textView resignFirstResponder];
    NSDictionary *params = @{@"diagnosis_id" : self.recordId,
                             @"complaint_type" : @(self.complaintType),
                             @"content" : SafeString(self.textView.text)
    };
    [self showLoading];
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:API_CONSULTATION_COUNSEL_COMPLAINT method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * _Nonnull response) {
        [weakSelf hideLoading];
        if (response.isSuccess) {
            if (weakSelf.complaintType == GMComplaintTypeDoctor) {
                weakSelf.type = GMEndConsultViewTypeComplaintFinish;
            } else {
                [weakSelf hide];
            }
            if (weakSelf.complaintFinish) {
                weakSelf.complaintFinish([response.data[@"status"] integerValue]);
            }
            if (weakSelf.evaluateFinish) {
                weakSelf.evaluateFinish(1, 0, @"");
            }
            if (weakSelf.complaintType == GMComplaintTypeUser) {
                [GMHudModule toastInView:[AppDelegate shareInstance].window text:@"投诉意见提交成功"];
            }
        }else {
            [GMHudModule toastInView:[AppDelegate shareInstance].window text:response.message];
        }
    }];
}
#pragma mark - 提交星级
- (void)submitStar{
    [self showLoading];
    __weak __typeof(self)weakSelf = self;
    if (self.starNum <= 0) {
        [GMHudModule toastInView:[AppDelegate shareInstance].window text:@"请选择1-5星进行评价"];
        return;
    }
    [[GMInterfaceNetwork shareInstance] excuteToFaceEvaluateDiagnosis_id:self.recordId star:self.starNum SuccessBlock:^(id response) {
        if (weakSelf.evaluateFinish && weakSelf.starNum>=1) {
            GMStarInfoObject *object = weakSelf.starContentArray[weakSelf.starNum - 1];
            weakSelf.evaluateFinish(0, weakSelf.starNum, object.descrip);
        }
        [weakSelf hideLoading];
        [weakSelf hide];
        [GMHudModule toastInView:[AppDelegate shareInstance].window text:@"感谢您的评价～"];
    } failureBlock:^(NSInteger errorCode, NSString *message) {
        [weakSelf hideLoading];
        [weakSelf hide];
        [GMHudModule toastInView:[AppDelegate shareInstance].window text:message];
    }];
}
- (void)confirmButtonClick {
    if (self.type == GMEndConsultViewTypeReport) {
        GMEditQuesPartController *vc = [GMEditQuesPartController new];
        vc.viewModel.recordId = self.recordId;
        [AppDelegate.navigation pushViewController:vc animated:YES];
        [self hide];
    } else if (self.type == GMEndConsultViewTypeDoctorComplaint || self.type == GMEndConsultViewTypeUserComplaint) {
        if (self.textView.text.length < 10) {
            [AppDelegate.visibleController toast:@"请填写您的投诉原因，至少10个字"];
        } else {
            [self complaint];
        }
    } else if(self.type == GMEndConsultViewTypeGrayStar){
        [self submitStar];
    }else {
        [self hide];
    }
}

- (void)complaintUserButtonClick {
    if (self.clickComplaintButtonBlock) {
        self.clickComplaintButtonBlock();
    }
    self.type = GMEndConsultViewTypeDoctorComplaint;
}
- (void)clickStarMethod:(GMButton *)sender {
    NSInteger tag = sender.tag - 1000;
    self.starNum = tag+1;
    if (self.starContentArray.count >= (tag+1)) {
        GMStarInfoObject *object = self.starContentArray[tag];
        self.bottomLabel.text = object.descrip;
    }
    [self.container mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(289.f);
    }];
    [self.starView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GMButton *btn = (GMButton *)obj;
        btn.selected = idx<=tag;
    }];
}
- (void)cancelButtonClick {
    [self hide];
    //面诊订单列表页会用到,是为了更改h5订单列表该订单的状态
    if (self.hideFinish) {
        self.hideFinish();
    }
}
- (void)didTapView {
    [self.textView.textView resignFirstResponder];    
}
- (void)showLoading {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = nil;
}
- (void)hideLoading {
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
}
- (UIView *)grayLineView {
    if (!_grayLineView) {
        _grayLineView = [[UIView alloc] init];
        _grayLineView.backgroundColor = GMColorEEEEEE;
        _grayLineView.layer.cornerRadius = 2.5f;
        _grayLineView.layer.masksToBounds = YES;
    }
    return _grayLineView;
}
- (GMLabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [GMLabel labelWithTextColor:UIColor.headlineText fontSize:16];
        _titleLabel.font = [UIFont gmBoldFont:16];
    }
    return _titleLabel;
}

- (GMButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [GMButton buttonWithType:UIButtonTypeCustom];
        _confirmButton.layer.cornerRadius = 22.5;
        _confirmButton.layer.masksToBounds = YES;
        _confirmButton.titleLabel.font = [UIFont gmBoldFont:17];
        [_confirmButton setTitle:@"保存" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:GMColorFF8C8D forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (GMButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [GMButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.enableAdaptive = YES;
        [_cancelButton setBackgroundImage:[UIImage imageNamed:@"wt_cancel_icon"] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (GMButton *)laterButton {
    if (!_laterButton) {
        _laterButton = [GMButton buttonWithType:UIButtonTypeCustom];
        _laterButton.titleLabel.font = [UIFont gmFont:14];
        [_laterButton setTitle:@"稍后填写" forState:UIControlStateNormal];
        [_laterButton setTitleColor:UIColor.auxiliaryTextExtraLight forState:UIControlStateNormal];
        [_laterButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    }
    return _laterButton;
}

- (GMButton *)complaintUserButton {
    if (!_complaintUserButton) {
        _complaintUserButton = [GMButton buttonWithType:UIButtonTypeCustom];
        _complaintUserButton.titleLabel.font = [UIFont gmFont:13];
        [_complaintUserButton setTitle:@"我要投诉>" forState:UIControlStateNormal];
        [_complaintUserButton setTitleColor:GMColorFF8C8D forState:UIControlStateNormal];
        [_complaintUserButton addTarget:self action:@selector(complaintUserButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _complaintUserButton;
}

- (GMImageView *)textImageView {
    if (!_textImageView) {
        _textImageView = [[GMImageView alloc] initWithImage:[UIImage imageNamed:@"to_face_edit_ques_suggest_bg"]];
        _textImageView.userInteractionEnabled = YES;
    }
    return _textImageView;
}

- (GMPlaceholderTextContainer *)textView {
    if (!_textView) {
        _textView = [[GMPlaceholderTextContainer alloc] init];
        _textView.textView.delegate = self;
        _textView.textView.font = [UIFont gmFont:14];
        _textView.placeholder = @"请填写投诉原因，最少10个字";
        _textView.placeholderLabel.font = [UIFont gmFont:14];
        _textView.placeholderLabel.textColor = UIColor.auxiliaryTextExtraLight;
        _textView.textView.textColor = UIColor.headlineText;
        _textView.textView.inputAccessoryView = nil;
    }
    return _textView;
}

- (GMLabel *)countLabel {
    if (!_countLabel) {
        _countLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextExtraLight fontSize:10];
        _countLabel.text = @"还能输入100字";
    }
    return _countLabel;
}

- (UIView *)starView {
    if (!_starView) {
        _starView = [[UIView alloc] init];
    }
    return _starView;
}
- (GMLabel *)bottomLabel {
    if (!_bottomLabel) {
        _bottomLabel = [GMLabel labelWithTextColor:GMColor282828 fontSize:14];
        _bottomLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _bottomLabel;
}
- (GMLabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [GMLabel labelWithTextColor:GMColor282828 fontSize:11];
        _tipLabel.text = @"请详细填写您需要申诉的问题，审核通过后将会为您安排退款";
    }
    return _tipLabel;
}
@end
