//
//  AddLookUpUserSecondVC.m
//  smartRhino
//
//  Created by tederen on 2019/11/25.
//  Copyright © 2019 tederen. All rights reserved.
//

#import "AddLookUpUserSecondVC.h"
#import "SendInfoGroupCell.h"
#import "SendGroupBCell.h"
#import "MailListSearchVC.h"
#import "MyTDGroupView.h"
#import "MailModel.h"
#import "MailListCell.h"
#import "ShareSysVC.h"
#import "ShareCusVC.h"
#import "ShowSysVC.h"
#import "ShowUserVC.h"
#import "ShowDesVC.h"

@interface AddLookUpUserSecondVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) TDTableView               *myTableView;
@property (nonatomic, strong) UIView *listHeaderVIew;
@property (nonatomic, strong) TDButton *serachButton;
@property (nonatomic, strong) AddressBookGroupModel *addressBookModel;
@property (nonatomic, strong) MyTDGroupView         *searchView;
@property (nonatomic,assign) NSInteger indexflag;
@property (nonatomic, strong) NSMutableArray <SelectModel*>*selectArray;
@property (nonatomic, strong) NSMutableArray <Department *>*selectDepartArray;
@property (nonatomic, strong) NSMutableArray <SelectModel*>*usersSourceDataArray;
@property (nonatomic, strong) NSMutableArray               *dataSourceArray;
@property (nonatomic, strong) NSMutableArray               *OtherArray;
@property (nonatomic, strong) UIView      *SortView;
@property (nonatomic, strong) UIButton    *allSelectBtn;
@property (nonatomic, strong) UILabel     *selectCountL;
@property (nonatomic, assign) BOOL         allSelected;

@end

@implementation AddLookUpUserSecondVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self countMailArray:@[]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getdata];
    [self.view addSubview:self.listHeaderVIew];
    [self.listHeaderVIew mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.myNavigationBar.mas_bottom);
        make.height.mas_offset(44);
    }];
    [self.listHeaderVIew addSubview:self.searchView];
    [self addSortV];
    [self.view addSubview:self.myTableView];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.SortView.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
    WS(weakSelf);
    [self.searchView.button setAction:^{
        MailGroupListSerachVC *vc = [[MailGroupListSerachVC alloc] init];
        vc.IsSelect = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColorHex(#FFFFFF);
    self.myTableView.backgroundColor =  UIColorHex(#F5F6F8);
    [self createnavi];
}
#pragma mark - 导航视图
- (void)createnavi{
    self.myNavigationBar.titleLabel.text = self.titleStr;
    [self.myNavigationBar.rightButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.myNavigationBar.rightButton setTitle:@"确定" forState:UIControlStateNormal];
    [[self.myNavigationBar.rightButton titleLabel] setFont:[UIFont systemFontOfSize:15.f]];
    self.myNavigationBar.rightButton.hidden = NO;
    [self.myNavigationBar.rightButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.myNavigationBar.backButton);
        make.height.mas_offset(@44);
        make.right.mas_equalTo(self.myNavigationBar.mas_right).offset(-15);
    }];
}

#pragma mark - 导航事件处理
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)back1{
    for ( NSInteger i = (self.navigationController.viewControllers.count - 1); i >= 0 ;i --) {
           NSLog(@"%@",self.navigationController.viewControllers[i]);
        if ([self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"MyWorkWordVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"SourceHomeVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"ChatNewGroupVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"H5ViewController")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"MyTDTopicCreateVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"MyFavoriteNewFindVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"ChatNewRowVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"MyTDTopicGroupUserVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"WorkFlowOrderController")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"CreateInterLeterVC")]
            || [self.navigationController.viewControllers[i] isKindOfClass:NSClassFromString(@"MailListByZuVC")]) {
            [self.navigationController popToViewController:self.navigationController.viewControllers[i] animated:YES];
            return;
        }
    }
}

//全选操作
- (void)selectedAction{
    if (self.allSelected) {
        [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
    }else{
        [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
    }
    if (self.IsSubVC) {
        NSInteger count = 0;
        for(NSInteger i = 0 ; i < 2 ; i++){
            if (i == 0) {
                for (Department *depart in self.departSourceDataArray) {
                     depart.hadSelected = self.allSelected;
                    if (depart.hadSelected) {
                        count ++;
                    }
                    [self countMailArray:@[depart]];
                }
            }
            if (i == 1) {
                for (SelectModel * model in self.usersSourceDataArray) {
                    model.hadSelected = self.allSelected;
                    if (model.hadSelected) {
                        count ++;
                    }
                    [self countMailArray:@[model]];
                }
            }
        }
        self.selectCountL.text = [NSString stringWithFormat:@"%ld",count];
    }else{
        NSInteger count = 0;
        for (NSArray * array in self.dataSourceArray) {
            for (id sub in array) {
                if ([sub isKindOfClass:[MailModel class]]) {
                    MailModel * model = (MailModel *)sub;
                    model.IsSelect = self.allSelected;
                    if (model.IsSelect) {
                        count ++;
                    }
                    [self countMailArray:@[model]];
                }
                if ([sub isKindOfClass:[SelectModel class]]) {
                    SelectModel * model = (SelectModel *)sub;
                    model.hadSelected = self.allSelected;
                    if (model.hadSelected) {
                        count ++;
                    }
                    [self countMailArray:@[model]];
                }
            }
        }
        self.selectCountL.text = [NSString stringWithFormat:@"%ld",count];
    }
    [self.myTableView reloadData];
}
// 左边按钮 全选 取消全选
- (void)secondBarButtonItems:(TDButton *)sender{
    [super menuAction:sender];
}
- (void)rightButtonAction:(TDButton *)sender{
    [self confirmAction:sender];
}
- (BOOL)hidesBottomBarWhenPushed{
    return YES;
}

- (void)confirmAction:(UIButton*)btn{
    NSMutableArray * mailArray = [NSMutableArray arrayWithArray:USERDEFAULTSGET(MAILSELECT)];
    NSMutableArray * chaoArray = [NSMutableArray array];
    NSMutableDictionary * paraDict = [NSMutableDictionary dictionary];
    NSMutableArray * mArray = [NSMutableArray array];
    [self.selectArray removeAllObjects];
    [mailArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SelectModel * sModel = (SelectModel*) [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)obj];
        [chaoArray addObject:sModel];
        [mArray addObject:@{@"SourceType":@(sModel.SourceType),@"SourceId":@(sModel.SourceId),@"SourceTypeValue":@(sModel.TypeValue),@"SourceName":sModel.SourceName}];
    }];
    if (self.isAllSelected) {
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFI_ChaoSongRen object:nil userInfo:@{@"selectPeople":chaoArray}];
        [self back1];
        return;
    }else{
        [paraDict setValue:mArray forKey:@"Item"];
        SHOWLOADING
        WS(weakSelf);
        [[HttpManager sharedHttpManager] POSTUrl:Host(API_APP_User_Middle) parameters:paraDict responseStyle:JOSN success:^(id  _Nonnull responseObject) {
            REMOVESHOW
            for (NSDictionary *dict in responseObject) {
                SelectModel * model = [SelectModel modelWithDictionary:dict];
                model.UserId = model.Id;
                model.UserName = model.Name;
                model.SourceType = model.SourceType;
                model.SourceId = model.UserId;
                model.SourceName = model.UserName;
                [weakSelf.selectArray addObject:model];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFI_ChaoSongRen object:nil userInfo:@{@"selectPeople":weakSelf.selectArray}];
            [weakSelf back1];
        } failure:^(NSError * _Nonnull error) {
//            SHOWERROR([ZYCTool handerResultData:error]);
        }];
    }
}
#pragma mark - setter
- (TDTableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[TDTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        [self.myTableView registerNib:[UINib nibWithNibName:@"SendInfoGroupCell" bundle:nil] forCellReuseIdentifier:@"SendInfoGroupCell"];//SendGroupBCell
        [self.myTableView registerNib:[UINib nibWithNibName:@"SendGroupBCell" bundle:nil] forCellReuseIdentifier:@"SendGroupBCell"];
    }
    return _myTableView;
}
- (UIView *)listHeaderVIew{
    if (!_listHeaderVIew) {
        _listHeaderVIew = [UIView new];
        _listHeaderVIew.backgroundColor = UIColorHex(#FFFFFF);
    }
    return _listHeaderVIew;
}
- (MyTDGroupView *)searchView
{
    if (!_searchView) {
        _searchView = [[MyTDGroupView alloc] initWithFrame:CGRectMake(0, 4, SCREEN_WIDTH, 36)];
    }
    return _searchView;
}
- (TDButton *)serachButton{
    if (!_serachButton) {
        _serachButton = [[TDButton alloc]initWithFrame:CGRectMake(20,5, kGXScreenWidth-40,40)];
        [_serachButton setTitle:@"搜索" forState:UIControlStateNormal];
        [[_serachButton titleLabel] setFont:[UIFont systemFontOfSize:14.f]];
        [_serachButton setImage:IMG(@"sendinfo_search") forState:UIControlStateNormal];
        [_serachButton setTitleColor:UIColorHex(B6B7B9) forState:UIControlStateNormal];
        _serachButton.backgroundColor = UIColorHex(F5F6F8);
        [_serachButton addTarget:self action:@selector(searchhander:) forControlEvents:UIControlEventTouchDown];
        [_serachButton layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:2];
        _serachButton.layer.cornerRadius = 20;
        _serachButton.layer.masksToBounds = YES;
    }
    return _serachButton;
}
- (NSMutableArray<SelectModel *> *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (!self.IsSubVC) {
        return self.dataSourceArray.count;
    }else{
        return 2;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!self.IsSubVC) {
        NSArray * array = self.dataSourceArray[section];
        return [array count];
    }else{
        if (section == 0) {
            return self.departSourceDataArray.count;
        }else{
            return self.usersSourceDataArray.count;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);

    if (!self.IsSubVC) {
        if ([self checkAllSelect:2]) {
            [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
        }else{
            [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
        }
        NSString *cellIdentifier2 = @"SendGroupBCell";
        SendGroupBCell * cell = (SendGroupBCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
        NSArray * array = self.dataSourceArray[indexPath.section];
        switch (indexPath.section) {
            case 0:
            {
                if (array.count > 0) {
                    MailModel * model = array[indexPath.row];
                    [cell setDataModel:model];
                    [cell.selectbuton setAction:^{
                        model.IsSelect = !model.IsSelect;
                        [weakSelf checkSelectCount:model];
                        [weakSelf.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                    }];
                }
            }
                break;
            default:{
                NSString *cellIdentifier = @"SendInfoGroupCell";
                SendInfoGroupCell * detailCommentCell = (SendInfoGroupCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
                SelectModel *model = array[indexPath.row];
                [detailCommentCell loadDataDepartUserModel:model indexWith:indexPath];
                [detailCommentCell.selectbuton setAction:^{
                    model.hadSelected = !model.hadSelected;
                    [weakSelf checkSelectCount:model];
                    [weakSelf.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }];
                detailCommentCell.rightImgeView.hidden = YES;
                return detailCommentCell;
            }
                break;
        }
        return cell;
    }else{
        if (indexPath.section == 1) {
            if ([self checkAllSelect:0]) {
                [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
            }else{
                [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
            }
            NSString *cellIdentifier = @"SendInfoGroupCell";
            SendInfoGroupCell * detailCommentCell = (SendInfoGroupCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            SelectModel *model = self.usersSourceDataArray[indexPath.row];
            [detailCommentCell loadDataDepartUserModel:model indexWith:indexPath];
            [detailCommentCell.selectbuton setAction:^{
                model.hadSelected = !model.hadSelected;
                [weakSelf checkSelectCount:model];
                [weakSelf.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }];
            detailCommentCell.rightImgeView.hidden = YES;
            return detailCommentCell;
        }else{
            if ([self checkAllSelect:1]) {
                [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
            }else{
                [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
            }
            NSString *cellIdentifier2 = @"SendGroupBCell";
            SendGroupBCell * sendB = (SendGroupBCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
            Department *model = self.departSourceDataArray[indexPath.row];
            [sendB loadDataModelDepartment: model WithIndex:indexPath];
            [sendB.selectbuton setAction:^{
                model.hadSelected = !model.hadSelected;
                [weakSelf checkSelectCount:model];
                [weakSelf.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }];
            sendB.rightImgeView.hidden = NO;
            return sendB;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!self.IsSubVC && section > 0) {
        return 36.f;
    }else{
        return 0.01f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (!self.IsSubVC && section > 0) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 36)];
        view.backgroundColor = UIColorHex(0xF0EFF4);
        UILabel * titleL = [UILabel new];
        [view addSubview:titleL];
        titleL.textColor = UIColorHex(0x666666);
        titleL.font = Kfont(13);
        titleL.text = @"最近聊天";
        [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(48);
            make.centerY.mas_equalTo(view);
        }];
        return view;
    }else{
        return [UIView new];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.IsSubVC) {
        if (self.isDefalutPage == 1) {
            if (indexPath.row == 0) { //
                Department *model = self.departSourceDataArray[indexPath.row];
                AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init];
                if (model.hadSelected) {
                    model.hadSelected = !model.hadSelected;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    vc.indexId = model.Id;
                    vc.isDefalutPage = 2;
                    vc.isMyGroup = 1;
                    vc.SourceType = 1;
                    vc.IsSubVC = YES;
                    vc.isShow = self.isShow;
                    vc.UserIds = self.UserIds;
                    vc.titleStr = self.titleStr;
                    vc.grouperArray = self.grouperArray;
                    vc.isAllSelected = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                Department *model = self.departSourceDataArray[indexPath.row];
                AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init];
                if (model.hadSelected) {
                    model.hadSelected = !model.hadSelected;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    vc.indexId = model.Id;
                    vc.isDefalutPage = 2;
                    vc.isMyGroup = 2;
                    vc.titleStr = self.titleStr;
                    vc.SourceType = 3;
                    vc.IsSubVC = YES;
                    vc.isShow = self.isShow;
                    vc.UserIds = self.UserIds;
                    vc.grouperArray = self.grouperArray;
                    vc.isAllSelected = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        }else{
            if (indexPath.section == 0) {
                Department *model = self.departSourceDataArray[indexPath.row];
                if (model.hadSelected) {
                    model.hadSelected = !model.hadSelected;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init];
                    vc.indexId = model.Id;
                    vc.isDefalutPage = 2;
                    vc.IsSubVC = YES;
                    vc.isShow = self.isShow;
                    vc.UserIds = self.UserIds;
                    vc.titleStr = self.titleStr;
                    vc.isMyGroup = self.isMyGroup;
                    vc.SourceType = self.SourceType;
                    vc.grouperArray = self.grouperArray;
                    vc.isAllSelected = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                SelectModel *model = self.usersSourceDataArray[indexPath.row];
                model.hadSelected = !model.hadSelected;
                [self checkSelectCount:model];
                [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    }else{
        NSArray * array = [self.dataSourceArray objectAtIndex:indexPath.section];
        MailModel * model = [array objectAtIndex:indexPath.row];
        switch (model.TypeId) {
            case MailListUserType:
            {
                SelectModel * smodel = [array objectAtIndex:indexPath.row];
                smodel.hadSelected = !smodel.hadSelected;
                [self checkSelectCount:smodel];
                [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }
                break;
            case MailListDesType:
            {
                if (model.IsSelect) {
                    model.IsSelect = !model.IsSelect;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    ShowDesVC * vc = [ShowDesVC initShowDesVC];
                    vc.dataSourceArray = model.Items.mutableCopy;
                    vc.IsSelect = YES;
                    vc.IsSelectDes = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            case MailListSysType:
            {
                if (model.IsSelect) {
                    model.IsSelect = !model.IsSelect;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    ShowSysVC * vc = [ShowSysVC initShowSysVC];
                    vc.dataSourceArray = model.Items.mutableCopy;
                    vc.IsSelect = YES;
                    vc.IsSelectDes = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            case MailListCusType:
            {
                if (model.IsSelect) {
                    model.IsSelect = !model.IsSelect;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init];
                    vc.indexId = self.departSourceDataArray[indexPath.row].Id;
                    vc.isDefalutPage = 2;
                    vc.isMyGroup = 2;
                    vc.titleStr = self.titleStr;
                    vc.SourceType = 3;
                    vc.IsSubVC = YES;
                    vc.isShow = self.isShow;
                    vc.UserIds = self.UserIds;
                    vc.grouperArray = self.grouperArray;
                    vc.isAllSelected = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            case MailListOtherType:
            {
                if (model.IsSelect) {
                    model.IsSelect = !model.IsSelect;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    ShowUserVC * vc = [ShowUserVC initShowUserVC];
                    vc.IsSelect = YES;
                    vc.IsSelectDes = self.isAllSelected;
                    vc.dataSourceArray = self.OtherArray.mutableCopy;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            default:
            {
                if (model.IsSelect) {
                    model.IsSelect = !model.IsSelect;
                    [self.myTableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init];
                    vc.indexId = self.departSourceDataArray[indexPath.row].Id;
                    vc.isDefalutPage = 2;
                    vc.isMyGroup = 2;
                    vc.titleStr = self.titleStr;
                    vc.SourceType = 3;
                    vc.IsSubVC = YES;
                    vc.isShow = self.isShow;
                    vc.UserIds = self.UserIds;
                    vc.grouperArray = self.grouperArray;
                    vc.isAllSelected = self.isAllSelected;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
        }
    }
}

- (BOOL)checkAllSelect:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            for (SelectModel * model in self.usersSourceDataArray) {
                if (!model.hadSelected) {
                    [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
                    return NO;
                }
            }
            [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
            return YES;
        }
            break;
        case 1:
        {
            for (Department * model in self.departSourceDataArray) {
                if (!model.hadSelected) {
                    [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
                    return NO;
                }
            }
            [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
            return YES;
        }
            break;
        default:
        {
            for (NSArray * array in self.dataSourceArray) {
                for (id sub in array) {
                    if ([sub isKindOfClass:[MailModel class]]) {
                        MailModel * model = (MailModel *)sub;
                        if (!model.IsSelect) {
                            [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
                            return NO;
                        }
                    }
                    if ([sub isKindOfClass:[SelectModel class]]) {
                        SelectModel * model = (SelectModel *)sub;
                        if (!model.hadSelected) {
                            [self.allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
                            return NO;
                        }
                    }
                }
            }
            [self.allSelectBtn setImage:IMG(@"sendinfo_yes") forState:UIControlStateNormal];
            return YES;
        }
            break;
    }
}
- (void)checkSelectCount:(id)detail
{
    NSInteger count = 0;
    for (SelectModel * model in self.usersSourceDataArray) {
        if (model.hadSelected) {
            count++;
        }
    }
    for (NSArray * subArray in self.dataSourceArray) {
        for (id sub in subArray) {
            if ([sub isKindOfClass:[MailModel class]]) {
                MailModel * model = (MailModel *)sub;
                if (model.IsSelect) {
                    count++;
                }
            }
            if ([sub isKindOfClass:[SelectModel class]]) {
                SelectModel * model = (SelectModel *)sub;
                if (model.hadSelected) {
                    count++;
                }
            }
        }
    }
    for (SelectModel * model in self.departSourceDataArray) {
        if (model.hadSelected) {
            count++;
        }
    }
    self.selectCountL.text = [NSString stringWithFormat:@"%ld",count];
    [self countMailArray:@[detail]];
}
- (void)countMailArray:(NSArray *)sssArray
{
    NSMutableArray * mailArray = [NSMutableArray arrayWithArray:USERDEFAULTSGET(MAILSELECT)];
    for (id detail in sssArray) {
        SelectModel * ssmodel = [self addSelectModel:detail];
        
        __block BOOL isEque = NO;
        [mailArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SelectModel * sModel = (SelectModel*) [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)obj];
            if (sModel.SourceType == ssmodel.SourceType && sModel.SourceId == ssmodel.SourceId) {
                isEque = YES;
                if (!ssmodel.hadSelected) {
                    [mailArray removeObject:obj];
                }
            }
        }];
        if (!isEque && ssmodel.hadSelected) {
            NSData * ssdata  = [NSKeyedArchiver archivedDataWithRootObject:ssmodel];
            [mailArray addObject:ssdata];
        }
        USERDEFAULTSSET(mailArray, MAILSELECT);
    }
    if (mailArray.count > 0) {
        self.myNavigationBar.rightButton.enabled = YES;
        [self.myNavigationBar.rightButton setTitleColor:UIColorHex(#3979D3) forState:UIControlStateNormal];
        [self.myNavigationBar.rightButton setTitle:[NSString stringWithFormat:@"确定(%ld)",(long)mailArray.count] forState:UIControlStateNormal];
    }else{
        self.myNavigationBar.rightButton.enabled = NO;
        [self.myNavigationBar.rightButton setTitle:@"确定" forState:UIControlStateNormal];
        [self.myNavigationBar.rightButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}
- (SelectModel *)addSelectModel:(id)model
{
    if ([model isKindOfClass:[SelectModel class]]) {
        SelectModel * sModel = (SelectModel *)model;
        sModel.SourceType = 0;
        sModel.SourceId = sModel.UserId;
        sModel.SourceName = sModel.UserName;
        sModel.hadSelected = sModel.hadSelected;
        sModel.AvatarUrl = sModel.AvatarUrl;
        return sModel;
    }
    if ([model isKindOfClass:[MailModel class]]) {
        MailModel * mModel = (MailModel *)model;
        SelectModel * sModel = [[SelectModel alloc] init];
        sModel.SourceType = mModel.TypeId;
        sModel.SourceId = mModel.Id;
        sModel.SourceName = mModel.Name;
        sModel.TypeValue = mModel.TypeValue;
        sModel.hadSelected = mModel.IsSelect;
        return sModel;
    }
    if ([model isKindOfClass:[MailSubModel class]]) {
        MailSubModel * mModel = (MailSubModel *)model;
        SelectModel * sModel = [[SelectModel alloc] init];
        sModel.SourceType = mModel.TypeId;
        sModel.SourceId = mModel.Id;
        sModel.SourceName = mModel.Name;
        sModel.TypeValue = mModel.TypeValue;
        sModel.hadSelected = mModel.IsSelect;
        return sModel;
    }
    if ([model isKindOfClass:[Department class]]) {
        Department * mModel = (Department *)model;
        SelectModel * sModel = [[SelectModel alloc] init];
        if (self.isDefalutPage == 2 && self.isMyGroup == 2) {
            sModel.SourceType = 3;
            sModel.SourceName = mModel.GroupName;
        }else{
            sModel.SourceType = 1;
            sModel.SourceName = mModel.Name;
        }
        sModel.SourceId = mModel.Id;
        sModel.TypeValue = 0;
        sModel.hadSelected = mModel.hadSelected;
        return sModel;
    }
    return nil;
}
#pragma mark - 网络数据请求
- (void)getdata{
    if (!self.IsSubVC) {
        [self getRootData];
    }
    if (self.isDefalutPage == 1) {
        return ;
    }
    if (self.isMyGroup == 1) {
        [self defaltGroupData];
    }
    if (self.isMyGroup == 2) {
        [self myGroupData];
    }
}
- (void)getRootData
{
    SHOWLOADING
    WS(weakSelf);
    [self.dataSourceArray removeAllObjects];
    [self.OtherArray removeAllObjects];
    [[HttpManager sharedHttpManager] GETUrl:Host(API_APP_User_Link) parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
        REMOVESHOW
        NSMutableArray * fArray = [NSMutableArray array];
        if ([responseObject[@"Items"] isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject[@"Items"];
            for (NSDictionary * dict in array) {
                MailModel * model = [MailModel modelWithDictionary:dict];
                [fArray addObject:model];
            }
            if ([responseObject[@"FriendUsers"] isKindOfClass:[NSArray class]]) {
                NSArray * array = responseObject[@"FriendUsers"];
                for (NSDictionary * dict in array) {
                    SelectModel * smodel = [[SelectModel alloc] initDict:dict];
                    smodel.SourceId = smodel.UserId;
                    smodel.SourceName = smodel.UserName;
                    smodel.SourceType = 0;
                    [weakSelf.OtherArray addObject:smodel];
                }
            }
            NSMutableArray * sArray = [NSMutableArray array];

            if ([responseObject[@"LatelyChatUsers"] isKindOfClass:[NSArray class]]) {
                NSArray * array = responseObject[@"LatelyChatUsers"];
                for (NSDictionary * dict in array) {
                    SelectModel * smodel = [[SelectModel alloc] initDict:dict];
                    smodel.SourceId = smodel.UserId;
                    smodel.SourceName = smodel.UserName;
                    smodel.SourceType = 0;
                    [sArray addObject:smodel];
                }
            }
            [weakSelf.dataSourceArray addObject:fArray];
            [weakSelf.dataSourceArray addObject:sArray];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.myTableView reloadData];
            });
        }
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
    }];
}
- (void)defaltGroupData{
    SHOWLOADING
    NSDictionary * paraDict = @{@"DepartmentId":@(self.indexId),@"UserIds":self.UserIds,@"IsShow":@(self.isShow)};
    NSLog(@"%@",paraDict);
    [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,AddressBookGroup_DepartemntDetail_Post] parameters:paraDict responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        REMOVESHOW;
        NSDictionary *dic = responseObject;
        NSArray *departMentArray = dic[@"Departments"];
        NSMutableArray *departMentMutableArray = [NSMutableArray array];
        for (NSDictionary *dic2 in departMentArray) {
            Department *model  = [[Department alloc]initWithDictionary:dic2 error:nil];
            [departMentMutableArray addObject:model];
        }
        self.departSourceDataArray = departMentMutableArray;
        NSArray *userArray = dic[@"Users"];
        NSMutableArray *usersMutableArray  = [NSMutableArray array];
        for (NSDictionary *dic2 in userArray) {
            SelectModel * model = [[SelectModel alloc] initDict:dic2];
            [usersMutableArray addObject:model];
        }
        for (SelectModel * model in self.grouperArray) {
            for (SelectModel * userModel in usersMutableArray) {
                if (userModel.UserId == model.UserId) {
                    userModel.IsDelete = YES;
                }
            }
        }
        NSMutableArray * checkUserArray = [NSMutableArray array];
        for (SelectModel * model in usersMutableArray) {
            if (!model.IsDelete) {
                [checkUserArray addObject:model];
            }
        }
        self.usersSourceDataArray = checkUserArray;
        [self.myTableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        SHOWERROR([ZYCTool handerResultData:error]);
    }];
}
- (void)myGroupData{
    SHOWLOADING
    NSDictionary * paraDict = @{@"AddressBookGroupId":@(self.indexId),@"UserIds":self.UserIds,@"IsShow":@(self.isShow)};
    NSLog(@"%@",paraDict);
    [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,AddressBookGroupUser_Get_Post] parameters:paraDict responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        REMOVESHOW;
        NSDictionary *dic = responseObject;
        NSArray *departMentArray = dic[@"AddressBookGroups"];
        NSMutableArray *departMentMutableArray = [NSMutableArray array];
        for (NSDictionary *dic2 in departMentArray) {
            Department *model  = [[Department alloc]initWithDictionary:dic2 error:nil];
            [departMentMutableArray addObject:model];
        }
        self.departSourceDataArray = departMentMutableArray;
        NSArray *userArray = dic[@"AddressBookGroupUsers"];
        NSMutableArray *usersMutableArray  = [NSMutableArray array];
        for (NSDictionary *dic2 in userArray) {
            SelectModel * model = [SelectModel modelWithDictionary:dic2];
            [usersMutableArray addObject:model];
        }
        for (SelectModel * model in self.grouperArray) {
            for (SelectModel * userModel in usersMutableArray) {
                if (userModel.UserId == model.UserId) {
                    userModel.IsDelete = YES;
                }
            }
        }
        NSMutableArray * checkUserArray = [NSMutableArray array];
        for (SelectModel * model in usersMutableArray) {
            if (!model.IsDelete) {
                [checkUserArray addObject:model];
            }
        }
        self.usersSourceDataArray = checkUserArray;
        [self.myTableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        SHOWERROR([ZYCTool handerResultData:error]);
    }];
}
#pragma mark - 搜索事件处理
- (void)searchhander:(TDButton *)sedner{
    
}
-(void)getSearchKeyWord:(NSString *)searchWord{
    NSLog(@"%@",searchWord);
    if(searchWord.length > 0){
       NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       [dict setObject:searchWord forKey:@"Key"];
        WEAKSELF
        [[HttpManager sharedHttpManager] POSTWithUrl:Host(AddressBookGroup_Search_Post) parameters:dict success:^(id  _Nonnull responseObject) {
               STRONGSELF
               NSArray *array = responseObject;

               if (array.count == 0) {
                    SHOWERROR(@"没有搜到结果");
               }else{
                   
                   NSArray *userArray = responseObject;
                   NSMutableArray *usersMutableArray  = [NSMutableArray array];
                   for (NSDictionary *dic2 in userArray) {
                       SelectModel * model = [[SelectModel alloc] initDict:dic2];
                       [usersMutableArray addObject:model];
                   }
                   [strongSelf.departSourceDataArray removeAllObjects];
                   strongSelf.usersSourceDataArray = usersMutableArray;
                   [strongSelf.myTableView reloadData];
                   [strongSelf.myTableView reloadData];
                   
               }
           } failure:^(NSError * _Nonnull error) {
                 SHOWERROR([ZYCTool handerResultData:error])
                 
           }];
    }else{
      
    }
}
- (void)canCelAllSelect
{
    for (SelectModel * model in self.usersSourceDataArray) {
        model.hadSelected = NO;
    }
    for (Department * model in self.departSourceDataArray) {
        model.hadSelected = NO;
    }
}
- (UIButton *)allSelectBtn
{
    if (!_allSelectBtn) {
        _allSelectBtn = [UIButton new];
        [_allSelectBtn setImage:IMG(@"sendinfo_no") forState:UIControlStateNormal];
    }
    return _allSelectBtn;
}
- (UILabel *)selectCountL
{
    if (!_selectCountL) {
        _selectCountL = [UILabel new];
        _selectCountL.font = Kfont(13);
        _selectCountL.text = @"0";
        _selectCountL.textColor = UIColorHex(0x0F88EB);
    }
    return _selectCountL;
}
- (UIView *)SortView
{
    if (!_SortView) {
        _SortView = [UIView new];
        _SortView.backgroundColor = UIColorHex(0xF0EFF4);
    }
    return _SortView;
}
- (void)addSortV
{
    [self.view addSubview:self.SortView];
    [self.SortView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.height.mas_offset(38);
        make.top.mas_equalTo(self.listHeaderVIew.mas_bottom);
    }];
    [self.SortView addSubview:self.allSelectBtn];
    [self.SortView addSubview:self.selectCountL];
    [self.allSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(5);
        make.centerY.mas_equalTo(self.SortView);
        make.size.mas_offset(CGSizeMake(38, 38));
    }];
    UILabel * leftL = [UILabel new];
    leftL.text = @"已选:";
    leftL.textColor = UIColorHex(0x666666);
    leftL.font = Kfont(13);
    [self.SortView addSubview:leftL];
    [leftL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.allSelectBtn.mas_right).offset(5);
        make.centerY.mas_equalTo(self.SortView);
    }];
    [self.selectCountL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftL.mas_right).offset(8);
        make.centerY.mas_equalTo(self.SortView);
    }];
    
    WS(weakSelf);
    [self.allSelectBtn setAction:^{
        weakSelf.allSelected = !weakSelf.allSelected;
        [weakSelf selectedAction];
    }];
}
- (NSMutableArray *)dataSourceArray
{
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}
- (NSMutableArray *)OtherArray
{
    if (!_OtherArray) {
        _OtherArray = [NSMutableArray array];
    }
    return _OtherArray;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self canCelAllSelect];
    [self.myTableView reloadData];
}
@end