//
//  GMDoctorRecommendShoppingView.m
//  Gengmei
//
//  Created by 卢悦明 on 2020/2/22.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDoctorRecommendShoppingView.h"
#import "GMDoctorShoppingViewCell.h"
#import "GMDoctorShopingViewSelectedCell.h"
#import "GMAISearchNavigationView.h"
#import "GMRecommendShopingModel.h"
#import "GMRtcManager.h"
#import "GMToFaceCommonEmptyView.h"
#import "GMContextualAcitonImage.h"
#import <GMKit/GMView.h>
#import "RequestHeader.h"
@import GMNetworking;
@protocol GMShoppingTitleView1Delegate <NSObject>

-(void)shoppingTitleView1TureBtnClick;
-(void)shoppingTitleView1CloseBtnClick;
-(void)shoppingTitleView1CancleBtnClick;

@end

@interface GMShoppingTitleView1 : GMView

@property(nonatomic, strong)GMButton *closeBtn; // 关闭按钮
@property(nonatomic, strong)GMButton *cancleBtn; // 取消按钮
@property(nonatomic, strong)GMButton *tureButton;  // 确定按钮
@property (nonatomic, weak)id<GMShoppingTitleView1Delegate> delegete;

@end

@implementation GMShoppingTitleView1

- (void)setup {
    [super setup];
    self.closeBtn = [[GMButton alloc] init];
    [_closeBtn setImage:[UIImage imageNamed:@"telephone_welfareClose"] forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_closeBtn];
    
    self.cancleBtn = [[GMButton alloc] init];
    [_cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_cancleBtn.titleLabel setFont:[UIFont gmFont:14]];
    [_cancleBtn setTitleColor:RGBCOLOR_HEX(0xBFC2CC) forState:UIControlStateNormal];
    [_cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self addSubview:_cancleBtn];
    
    self.tureButton = [[GMButton alloc] init];
    [_tureButton addTarget:self action:@selector(tureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_tureButton.titleLabel setFont:[UIFont gmFont:14]];
    [_tureButton setTitle:@"确定" forState:UIControlStateNormal];
    [self addSubview:_tureButton];
    
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(11);
        make.width.height.mas_equalTo(25);
    }];
    
    [_cancleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(25);
    }];
    
    [_tureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.right.mas_equalTo(_cancleBtn.mas_left).offset(-10);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(25);
    }];
}

- (void)closeBtnClick {
    if (self.delegete && [self.delegete respondsToSelector:@selector(shoppingTitleView1CloseBtnClick)]) {
        [self.delegete shoppingTitleView1CloseBtnClick];
    }
}

- (void)cancleBtnClick {
    if (self.delegete && [self.delegete respondsToSelector:@selector(shoppingTitleView1CancleBtnClick)]) {
        [self.delegete shoppingTitleView1CancleBtnClick];
    }
}

- (void)tureBtnClick {
    if (self.delegete && [self.delegete respondsToSelector:@selector(shoppingTitleView1TureBtnClick)]) {
        [self.delegete shoppingTitleView1TureBtnClick];
    }
}

@end

@protocol GMShoppingTitleViewDelegate <NSObject>

-(void)shoppingTitleViewAddGoods;
-(void)shoppingTitleViewCloseBtnClick;

@end

@interface GMShoppingTitleView : GMView

@property(nonatomic, strong)GMButton *closeBtn;
@property(nonatomic, strong)GMButton *addButton;

@property (nonatomic, weak)id<GMShoppingTitleViewDelegate> delegete;
@end

@implementation GMShoppingTitleView

- (void)setup {
    [super setup];
    self.closeBtn = [[GMButton alloc] init];
    [_closeBtn setImage:[UIImage imageNamed:@"telephone_welfareClose"] forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_closeBtn];
    
    self.addButton = [[GMButton alloc] init];
    [_addButton addTarget:self action:@selector(addGoods) forControlEvents:UIControlEventTouchUpInside];
    [_addButton.titleLabel setFont:[UIFont gmFont:14]];
    [_addButton setTitleColor:RGBCOLOR_HEX(0x20BDBB) forState:UIControlStateNormal];
    [_addButton setImage:[UIImage imageNamed:@"Telephone_add"] forState:UIControlStateNormal];
    [_addButton setImage:[UIImage imageNamed:@"Telephone_add"] forState:UIControlStateHighlighted];
    [_addButton setTitle:@" 添加推荐商品" forState:UIControlStateNormal];
    [self addSubview:_addButton];
    
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-11);
        make.width.height.mas_equalTo(25);
        make.top.mas_equalTo(15);
    }];
    
    [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_closeBtn.mas_left).offset(-10);
        make.width.mas_equalTo(130);
        make.height.mas_equalTo(25);
        make.top.mas_equalTo(15);
    }];
}

- (void)addGoods {
    if (self.delegete && [self.delegete respondsToSelector:@selector(shoppingTitleViewAddGoods)]) {
        [self.delegete shoppingTitleViewAddGoods];
    }
}

- (void)closeBtnClick {
    if (self.delegete && [self.delegete respondsToSelector:@selector(shoppingTitleViewCloseBtnClick)]) {
        [self.delegete shoppingTitleViewCloseBtnClick];
    }
}
@end


@interface GMDoctorRecommendShoppingView ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,GMShoppingTitleViewDelegate,GMShoppingTitleView1Delegate>

@property(nonatomic, strong)GMTableView *tableView;
@property(nonatomic, strong)GMAISearchNavigationView *searchNavigationView;
@property (nonatomic, strong)GMToFaceCommonEmptyView *emptyView;
@property(nonatomic, strong)GMShoppingTitleView *titltView;
@property(nonatomic, strong)GMShoppingTitleView1 *titltView1;
@property (nonatomic, assign)GMShoppingViewSelecteType seletedType;
// 购物袋加载出来的数据
@property (nonatomic, strong)NSMutableArray<GMRecommendShopingModel *> *shopingArray;
// 搜索出来的Model
@property (nonatomic, strong)NSMutableArray<GMRecommendShopingModel *> *searchArray;
@end

@implementation GMDoctorRecommendShoppingView

-(void)setup {
    [super setup];
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.titltView1];
    [self addSubview:self.titltView];
    [self addSubview:self.searchNavigationView];
    // 添加tableView
    [self addSubview:self.tableView];
    [self addemptyView];
}

- (void)setModel:(GMVideoTelephoneModel *)model {
    _model = model;
    [self loadRemoteData];
}

#pragma mark - 请求推荐接口
-(void)loadRemoteData {
    NSDictionary *params = @{@"record_id":SafeString(self.model.consultationRecordId)};
    [self.shopingArray removeAllObjects];
    [GMNetworking requestOCWithApi:API_CONSULTATION_GET_RECOM_BAG method:GMHTTPMethodGet parameters:params completion:^(GMResponseOC * _Nonnull response) {
        [GMHudModule hideLoading];
        if (response.isSuccess) {
            self.shopingArray = [GMRecommendShopingModel arrayOfModelsFromDictionaries:response.data[@"services"] error:nil];
            [self.tableView reloadData];
        }else {
            [GMHudModule showWarning:response.message];
        }
    }];
}

-(void)updateConstraints {
    [super updateConstraints];

    [_titltView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    [_titltView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    [_emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(100);
        make.right.mas_equalTo(-100);
        make.height.mas_equalTo(MAINSCREEN_WIDTH - 200);
        make.top.mas_equalTo(_titltView.mas_bottom).offset(80);
    }];
    
    [_searchNavigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_titltView.mas_bottom).offset(0);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(0);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_searchNavigationView.mas_bottom).offset(5);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

-(void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = rect;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

// 关闭弹框
- (void)hidenView {
    [self.searchNavigationView.textField resignFirstResponder];
    self.hidden = YES;
}

#pragma mark - <GMShoppingTitleViewDelegate，GMShoppingTitleView1Delegate>

-(void)shoppingTitleViewAddGoods{
    [self chageSubViewWithType:GMShoppingViewSelecteTwo];
    [self.searchArray removeAllObjects];
    [self.tableView reloadData];
}

-(void)shoppingTitleViewCloseBtnClick{
    [self hidenView];
}

#pragma mark - 确定按钮 添加美购
-(void)shoppingTitleView1TureBtnClick {
    [GMHudModule showLoading:@""];
    self.searchNavigationView.textField.text = @"";
    [self chageSubViewWithType:GMShoppingViewSelecteone];
    NSMutableArray *temp = [NSMutableArray array];
    for (GMRecommendShopingModel *model in self.searchArray) {
        if(model.isSelectedCell) {
            [temp addObject:model.serviceId];
        }
    }
    if (temp.count == 0) {
        [self.tableView reloadData];
        [GMHudModule hideLoading];
        return;
    }

    [self.shopingArray removeAllObjects];
    NSString *tempArrayStr = [NSString convertToPrettyPrintedJsonString: temp];
    NSDictionary *parame = @{@"service_ids":SafeString(tempArrayStr),
                             @"record_id":SafeString(self.model.consultationRecordId)};

    [GMNetworking requestOCWithApi:API_CONSULTATION_ADD_BAG method:GMHTTPMethodPost parameters:parame completion:^(GMResponseOC * _Nonnull response) {
        if (response.isSuccess) {
            [self loadRemoteData];
        } else {
            [GMHudModule hideLoading];
            [GMHudModule showWarning:response.message];
        }
    }];
}

-(void)shoppingTitleView1CloseBtnClick {
    [self hidenView];
}

-(void)shoppingTitleView1CancleBtnClick {
    [self chageSubViewWithType:GMShoppingViewSelecteone];
    [self.tableView reloadData];
}

-(void)chageSubViewWithType:(GMShoppingViewSelecteType)type {
    self.seletedType = type;
    _titltView.hidden = type;
    _titltView1.hidden = !type;
    _searchNavigationView.hidden = !type;
    if (type == GMShoppingViewSelecteone) {
        [self.searchNavigationView.textField resignFirstResponder];
        [_searchNavigationView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_titltView.mas_bottom).offset(5);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
    }else {
        [self.searchNavigationView.textField becomeFirstResponder];
        [_searchNavigationView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(44);
        }];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_searchNavigationView.mas_bottom).offset(5);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
    }
}

#pragma mark - <UITextFieldDelegate> 点击搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.searchNavigationView.textField resignFirstResponder];
    [GMHudModule showLoading:@""];
    NSDictionary *parame = @{@"doctor_id":SafeString(self.model.counsellorInfo.doctorId),
                             @"search_word":SafeString(textField.text),
                             @"record_id":SafeString(self.model.consultationRecordId)
    };
    [self.searchArray removeAllObjects];
    [GMNetworking requestOCWithApi:API_CONSULTATION_SEARCH_SERVICE method:GMHTTPMethodGet parameters:parame completion:^(GMResponseOC * _Nonnull response) {
        [GMHudModule hideLoading];
        if (response.isSuccess) {
            self.searchArray = [GMRecommendShopingModel arrayOfModelsFromDictionaries:response.data[@"services"] error:nil];
            [self.tableView reloadData];
        }else {
            [GMHudModule showWarning:response.message];
        }
    }];
    return YES;
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.seletedType){
        self.emptyView.hidden = self.searchArray.count;
        self.titltView1.tureButton.userInteractionEnabled = self.searchArray.count;
        if (self.searchArray.count > 0) {
            [self.titltView1.tureButton setTitleColor:RGBCOLOR_HEX(0x20BDBB) forState:UIControlStateNormal];
        } else {
            [self.titltView1.tureButton setTitleColor:RGBCOLOR_HEX(0xBFC2CC) forState:UIControlStateNormal];
        }
        return self.searchArray.count;
    }else {
        NSLog(@"%ld",self.shopingArray.count);
        self.emptyView.hidden = self.shopingArray.count;
        return self.shopingArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.seletedType) {
        GMDoctorShopingViewSelectedCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GMDoctorShopingViewSelectedCell class]) forIndexPath:indexPath];
        cell.listModel = self.searchArray[indexPath.row];
        return cell;
    }else {
        GMDoctorShoppingViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GMDoctorShoppingViewCell class]) forIndexPath:indexPath];
        if (self.shopingArray.count > indexPath.row) {
            cell.listModel = self.shopingArray[indexPath.row];
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.seletedType) {
        GMRecommendShopingModel *model = self.searchArray[indexPath.row];
        model.isSelectedCell = !model.isSelectedCell;
        [_tableView reloadData];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return (self.seletedType) ? NO : YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)){
    __weak typeof(self) weakSelf = self;
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [weakSelf deletedDataWithIndexpath:indexPath];
        [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
        completionHandler(YES);
    }];
    // iOS 12 设置image失败，所以用这种方式（UIContextualAction image clolor is write(UIContextualAction 颜色自动更改成白色)）
    deleteRowAction.image = [UIImage imageNamed:@"Telephone_delete"].contextualAcitonImage;

    deleteRowAction.backgroundColor = [UIColor whiteColor];
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
    return config;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self deletedDataWithIndexpath:indexPath];
}

#pragma mark - 点击删除
-(void)deletedDataWithIndexpath:(NSIndexPath *)indexPath {
    [GMHudModule showLoading:@""];
    GMRecommendShopingModel *listModel = self.shopingArray[indexPath.row];
    NSDictionary *parame = @{@"service_id": SafeString(listModel.serviceId),
                             @"record_id": SafeString(self.model.consultationRecordId)
    };
    [GMNetworking requestOCWithApi:API_CONSULTATION_DELETE_BAG method:GMHTTPMethodPost parameters:parame completion:^(GMResponseOC * _Nonnull response) {
        [GMHudModule hideLoading];
        if (response.isSuccess) {
            // 删除数据
            [self.shopingArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
        }else {
            [GMHudModule showWarning:response.message];
        }
    }];
}

#pragma mark - 懒加载控件

-(GMShoppingTitleView1 *)titltView1 {
    if (!_titltView1) {
        _titltView1 = [[GMShoppingTitleView1 alloc] init];
        _titltView1.delegete = self;
        _titltView1.hidden = YES;
    }
    return _titltView1;
}

-(GMShoppingTitleView *)titltView {
    if (!_titltView) {
        _titltView = [[GMShoppingTitleView alloc] init];
        _titltView.delegete = self;
    }
    return _titltView;
}

- (void)addemptyView {
    _emptyView = [[GMToFaceCommonEmptyView alloc] initWithFrame:CGRectZero];
    _emptyView.hidden = YES;
    _emptyView.emptyLabel.text = @"你的推荐带空空如也";
    [self addSubview:_emptyView];
}

- (GMAISearchNavigationView *)searchNavigationView{
    if (!_searchNavigationView) {
        _searchNavigationView = [GMAISearchNavigationView new];
        _searchNavigationView.textField.delegate = self;
        _searchNavigationView.hidden = YES;
        _searchNavigationView.textField.placeholder = @"请输入商品名称";
        _searchNavigationView.showCancelButton = NO;
    }
    return _searchNavigationView;
}

- (GMTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GMTableView alloc] init];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.rowHeight = 110;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView registerClass:[GMDoctorShoppingViewCell class] forCellReuseIdentifier:NSStringFromClass([GMDoctorShoppingViewCell class])];
        [_tableView registerClass:[GMDoctorShopingViewSelectedCell class] forCellReuseIdentifier:NSStringFromClass([GMDoctorShopingViewSelectedCell class])];
    }
    return _tableView;
}

-(NSMutableArray<GMRecommendShopingModel *> *)searchArray {
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

-(NSMutableArray<GMRecommendShopingModel *> *)shopingArray{
    if (!_shopingArray) {
        _shopingArray = [NSMutableArray array];
    }
    return _shopingArray;
}
@end
