//
//  ChatMsgListVC.m
//  smartRhino
//
//  Created by armin on 2019/11/2.
//  Copyright © 2019 tederen. All rights reserved.
//

#import "ChatMsgListVC.h"
#import "ChatMsgListCell.h"
#import "GHRefreshCollectionView.h"
#import "ChatMsgCollectionCell.h"
#import "YCMenuView.h"
#import "ChatMsgTopSearchVC.h"
#import "WorkingGroupMainVC.h"
#import "ShowNewGroupAlert.h"
#import "ChatMsgNoticeVC.h"
#import "MoreAppVC.h"
#import "ChatNewGroupVC.h"
#import "NoticeUnreadVC.h"
#import "MailListVC.h"
#import "EMChatViewController.h"
#import "TDInterLeterHomeViewController.h"
#import "EMRealtimeSearch.h"
#import "EMConversationHelper.h"
#import "MoreAppModel.h"
#import "NavigationController.h"
#import "TabBarController.h"
#import "MyTDGroupViewController.h"
#import "WaitWorkVC.h"
#import "ChatMsgWorkModel.h"
#import "MyTDTopicViewController.h"
#import "TDInterLeterHomeViewController.h"
#import "ChatListMoveVC.h"
#import "NSDate+Extension.h"
#import "SWQRCodeConfig.h"
#import "SWQRCodeViewController.h"
#import "MailListDetailVC.h"
#import "ChatJoinGroupVC.h"
#import "TDQrJoinVC.h"
#import "MyTDGroupView.h"
#import "ChatTestingVC.h"
#import "ReplayMeVC.h"
#import "TDGroupInfoListVC.h"

static NSString *kConversation_IsRead = @"kHaveAtMessage";
static int kConversation_AtYou = 1;
static int kConversation_AtAll = 2;

@interface ChatMsgListVC ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,EMChatManagerDelegate, EMGroupManagerDelegate, EMConversationsDelegate,SWQRCodeViewControllerDelegate>
 
@property (weak,nonatomic) IBOutlet UIButton *operationBackButton;
@property (weak,nonatomic) IBOutlet UIButton *operationAllSelectButton;
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@property (weak, nonatomic) IBOutlet UIButton *menuBtn;
@property (weak,nonatomic) IBOutlet UIButton *rightButton;
@property (weak, nonatomic) IBOutlet UIView  *HeadView;
@property (strong,nonatomic)  UITableView    *tableView;
//菜单列表数据源
@property (strong,nonatomic) NSMutableArray *taskActionArray;
@property (strong, nonatomic) MyTDGroupView      *SearchView;
@property (nonatomic, strong) GHRefreshCollectionView *collectionView;
@property (strong,nonatomic) NSMutableArray *collectionDataSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchConstant;

//界面操作状态参数
@property (assign,nonatomic) OperationStateEnum operationStateEnum;
@property (weak, nonatomic) IBOutlet UIView *NavBar;

//界面操作视图
@property (strong,nonatomic) UIButton *operationBottomDeleteBtn;
@property (strong,nonatomic) UIButton *operationBottomMoveBtn;
@property (strong,nonatomic) UIView *operationBottomBgView;
@property (strong,nonatomic) NSMutableArray *dataArray;
@property (strong,nonatomic) NSMutableArray *chatListIMArray;
@property (strong,nonatomic) NSMutableArray *selectArray;
@property (assign,nonatomic) BOOL            isAllselect;
@property (copy,nonatomic) NSString         *ConfirmationDate;
@property (copy,nonatomic) NSString         *ReplyDate;
@property (assign,nonatomic) NSInteger       ReplyCount;
@property (assign,nonatomic) NSInteger       UReadVerifyCount;

@end

@implementation ChatMsgListVC
+(ChatMsgListVC *)initChatMsgListVC{
    ChatMsgListVC *controller = [StoryboardManager.shared.chatMsg instantiateViewControllerWithIdentifier:@"ChatMsgListVC"];
    return controller;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self headRefresh];
}
- (void)addTableRefresh
{
    WS(weakSelf);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headRefresh];
    }];
}
- (void)removeTableRefresh
{
    [self.tableView.mj_header removeFromSuperview];
}
- (void)headRefresh{
    [self.chatListIMArray removeAllObjects];
    [self getUnreadCount];
}
- (void)getUnreadCount
{
    [self initCollectionData];
    [self initChatMsgIMData];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)conversationListDidUpdate:(NSArray *)aConversationList
{
    [self _loadAllConversationsFromDBWithIsShowHud:NO];
}
- (void)messagesDidReceive:(NSArray *)aMessages
{
     [self performSelector:@selector(getUnreadCount) withObject:nil afterDelay:0.8];
}
- (void)_reSortedConversationModelsAndReloadView
{
    NSArray *sorted = [self.dataArray sortedArrayUsingComparator:^(EMConversationModel *obj1, EMConversationModel *obj2) {
        EMMessage *message1 = [obj1.emModel latestMessage];
        EMMessage *message2 = [obj2.emModel latestMessage];
        if(message1.timestamp > message2.timestamp) {
            return(NSComparisonResult)NSOrderedAscending;
        } else {
            return(NSComparisonResult)NSOrderedDescending;
        }}];

    NSMutableArray *conversationModels = [NSMutableArray array];
    for (EMConversationModel *model in sorted) {
        if (!model.emModel.latestMessage) {
            [EMClient.sharedClient.chatManager deleteConversation:model.emModel.conversationId
                                                 isDeleteMessages:NO
                                                       completion:nil];
            continue;
        }
        [conversationModels addObject:model];
    }
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:conversationModels];
    [self replaceChatData];
}
- (void)_loadAllConversationsFromDBWithIsShowHud:(BOOL)aIsShowHUD
{
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        NSArray *sorted = [conversations sortedArrayUsingComparator:^(EMConversation *obj1, EMConversation *obj2) {
            EMMessage *message1 = [obj1 latestMessage];
            EMMessage *message2 = [obj2 latestMessage];
            if(message1.timestamp > message2.timestamp) {
                return(NSComparisonResult)NSOrderedAscending;
            } else {
                return(NSComparisonResult)NSOrderedDescending;
            }}];
        
        [weakself.dataArray removeAllObjects];
        
        NSArray *models = [EMConversationHelper modelsFromEMConversations:sorted];
        [weakself.dataArray addObjectsFromArray:models];
        [weakself replaceChatData];
    });
}
#pragma mark - EMConversationsDelegate

- (void)didConversationUnreadCountToZero:(EMConversationModel *)aConversation
{
    [self replaceChatData];
}

- (void)didResortConversationsLatestMessage
{
    [self _reSortedConversationModelsAndReloadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = RGB(240, 239, 244);

    [self initBottomBgView];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleGroupSubjectUpdated:) name:GROUP_SUBJECT_UPDATED object:nil];
    [self.HeadView addSubview:self.SearchView];
    [self.SearchView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(6);
        make.left.right.mas_equalTo(self.HeadView);
        make.height.mas_offset(36);
    }];
    WS(weakSelf);
    [self.SearchView.button setAction:^{
        ChatMsgTopSearchVC *vc = [[ChatMsgTopSearchVC alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.HeadView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];

    [self.operationBackButton setAction:^{
        if(weakSelf.operationStateEnum == OperationStateEnum1){
            [weakSelf changeSelectStatus];
            [weakSelf changeToOperation:NO];
        }else if (weakSelf.operationStateEnum == OperationStateEnum2){
            [weakSelf userDidMove:NO isEdit:YES];
        }else{
            [super backAction:self.operationBackButton];
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushTDGroupController:) name:PUSHTDGROUPCOTROLLER object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushEMChatViewController:) name:PUSHEMCHATVIEWCOTROLLER object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushSubViewController:) name:DRAWERPUSHVC object:nil];
    [self changeToOperation:NO];
    [self resetRightBtnAction:YES];
}

-(void)resetRightBtnAction:(BOOL)isShowMenu{
    WS(weakSelf);
    if(isShowMenu){
        [self.rightButton setImage:[UIImage imageNamed:@"chatmsg_right_add_icon"] forState:UIControlStateNormal];
        [self.rightButton setAction:^{
            NSMutableArray *menuDataSourceArray = [weakSelf getMenuDataSource:weakSelf.taskActionArray];
            YCMenuView *view = [YCMenuView menuWithActions:menuDataSourceArray width:106 relyonView:weakSelf.rightButton];
            view.menuColor = RGB(255, 255, 255);
            view.separatorColor = RGB(234, 234, 234);
            view.textColor = RGB(102, 102, 102);
            view.textFont = [UIFont systemFontOfSize:16.0];
            view.menuCellHeight = 43.5;
            view.maxDisplayCount = 10;
            view.offset = - 6;
            [view show];
        }];
    }else{
//        [self.rightButton setImage:[UIImage imageNamed:@"chatmsg_right_fileadd_icon"] forState:UIControlStateNormal];
//        [self.rightButton setAction:^{
//            [ShowtipTool showErrorWithStatus:@"未做"];
//        }];
    }
}

-(void)initCollectionData{
    [self.collectionDataSource removeAllObjects];
    id chatMenuDict = [[NSUserDefaults standardUserDefaults] objectForKey:CHATMENUBAR];
    NSMutableArray * commonArray = [NSMutableArray array];
    NSMutableArray * moreArray = [NSMutableArray array];
    NSMutableArray * array = [NSMutableArray array];
    if (![chatMenuDict isKindOfClass:[NSDictionary class]]) {
        for (int i= 0;i < 5; i++) {
                MoreAppInfoModel *model = [[MoreAppInfoModel alloc] init];
                switch (i) {
                    case 0:{
                        model.title = @"通知";
                        model.imgName = @"chatmsg_tz_icon";
                        model.notImgName = @"chatmsg_tz_hui_icon";
                        model.type = ChatMenuNoticeType;
                        model.readNum = 0;
                        model.showEditFlag = NO;
                    }break;
                    case 1:{
                        model.title = @"站内信";
                        model.imgName = @"chatmsg_znx_icon";
                        model.notImgName = @"chatmsg_tz_hui_icon";
                        model.type = ChatMenuZhanXinType;
                        model.readNum = 0;
                        model.showEditFlag = YES;
                    }break;
                    case 2:{
                        model.title = @"通讯录";
                        model.imgName = @"chatmsg_txl_icon";
                        model.notImgName = @"chatmsg_tz_hui_icon";
                        model.type = ChatMenuTeleListType;
                        model.readNum = 0;
                        model.showEditFlag = YES;
                    }break;
                    case 3:{
                        model.title = @"小组";
                        model.imgName = @"chatmsg_xiaozu_icon";
                        model.notImgName = @"chatmsg_tz_hui_icon";
                        model.type = ChatMenuGroupType;
                        model.readNum = 0;
                        model.showEditFlag = YES;
                    }break;
                    case 4:{
                        model.title = @"话题";
                        model.imgName = @"chatmsg_ht_icon";
                        model.notImgName = @"chatmsg_tz_hui_icon";
                        model.type = ChatMenutopicType;
                        model.readNum = 0;
                        model.showEditFlag = YES;
                    }break;
                    default:
                        break;
                }
                [array addObject:model];
                NSDictionary *json = [model modelToJSONObject];
                [commonArray addObject:json];
            }
        for (NSInteger j = 0; j < 1; j ++) {
            MoreAppInfoModel *model = [[MoreAppInfoModel alloc] init];
            model.title = @"待办事项";
            model.imgName = @"chatmsg_dbsx_icon";
            model.notImgName = @"chatmsg_tz_hui_icon";
            model.type = ChatMenuWaitType;
            model.readNum = 0;
            model.showEditFlag = YES;
            [moreArray addObject:[model modelToJSONObject]];
        }
        self.collectionDataSource = array;
        [[NSUserDefaults standardUserDefaults] setObject:@{@"common":[NSArray arrayWithArray:commonArray],@"more":[NSArray arrayWithArray:moreArray]} forKey:CHATMENUBAR];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        NSArray * array = [chatMenuDict objectForKey:@"common"];
        for (NSDictionary * dict in array) {
            MoreAppInfoModel *model = [MoreAppInfoModel modelWithDictionary:dict];
            [self.collectionDataSource addObject:model];
        }
    }
}



-(void)initChatMsgIMData{
    [self.chatListIMArray removeAllObjects];
    ChatMsgListImModel * amodel = [[ChatMsgListImModel alloc] init];
    amodel.AttributeValue = 3;
    amodel.Name = @"通讯录";
    amodel.AvatarUrl = @"chat_phone_list";
    [self.chatListIMArray addObject:amodel];
    ChatMsgListImModel * bmodel = [[ChatMsgListImModel alloc] init];
    bmodel.AttributeValue = 4;
    bmodel.Name = @"验证信息";
    bmodel.AvatarUrl = @"chat_yan_message";
    [self.chatListIMArray addObject:bmodel];
    ChatMsgListImModel * cmodel = [[ChatMsgListImModel alloc] init];
    cmodel.AttributeValue = 5;
    cmodel.Name = @"回复我的";
    cmodel.AvatarUrl = @"chat_replay_me";
    [self.chatListIMArray addObject:cmodel];

    WS(weakSelf);
    SHOWLOADING
    NSString * url = [NSString stringWithFormat:@"%@0",Host(Often_Contact_List)];
    [[HttpManager sharedHttpManager] GETUrl:url parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
        REMOVESHOW
        [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"OftenContactInfos"] isKindOfClass:[NSArray class]]) {
            for (NSDictionary * dict in responseObject[@"OftenContactInfos"]) {
                ChatMsgListImModel * model = [ChatMsgListImModel modelWithDictionary:dict];
                [weakSelf.chatListIMArray addObject:model];
            }
        }
        weakSelf.ConfirmationDate = responseObject[@"ConfirmationDate"];
        weakSelf.ReplyDate = responseObject[@"ReplyDate"];
        weakSelf.ReplyCount = [responseObject[@"ReplyCount"] integerValue];
        weakSelf.UReadVerifyCount = [responseObject[@"UReadVerifyCount"] integerValue];
        [weakSelf _loadAllConversationsFromDBWithIsShowHud:NO];
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
        NSLog(@"%@",error);
    }];
}

- (NSString *)isNullWithString:(id)value
{
    if ([value isKindOfClass:[NSNull class]]) {
        return @"";
    }else{
        if ([value isKindOfClass:[NSString class]]) {
            return value;
        }else{
            return [value stringValue];
        }
    }
}
//- (BOOL)hidesBottomBarWhenPushed{
//    return NO;
//}
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath
//{
//    return YES;
//}

//#pragma mark - 左滑按钮 iOS8以上
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){// delete action
    WS(weakSelf);
    ChatMsgListImModel * model = weakSelf.chatListIMArray[indexPath.row];
    if(self.operationStateEnum == OperationStateEnum0){
            switch (model.AttributeValue) {
                case 2:
                {
                    UIContextualAction *action1 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"删除" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (YES);
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认删除" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [weakSelf chatListDelete:@[model].copy];
                        }];
                        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                        }];
                        [alert addAction:sureAction];
                        [alert addAction:cancelAction];
                        [weakSelf presentViewController:alert animated:YES completion:^{

                        }];

                    }];
                    action1.backgroundColor = RGB(255, 59, 47);
                    UIContextualAction *action2 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"重命名" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (NO);
                        [weakSelf workGroupReName:model];

                    }];
                    action2.backgroundColor = RGB(255, 149, 3);
                    UIContextualAction *action3 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:model.IsTop ? @"取消置顶" : @"置顶" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (YES);
                        [weakSelf chatListIsTop:model];
                    }];
                    action3.backgroundColor = RGB(197, 201, 204);
                    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[action1, action2, action3]];
                    actions.performsFirstActionWithFullSwipe = NO;
                    return actions;
                }
                    break;
                 case 0:
                {
                    UIContextualAction *action1 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"删除" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (YES);
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认删除" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [weakSelf chatListDelete:[NSMutableArray arrayWithArray:@[model]]];
                        }];
                        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                        }];
                        [alert addAction:sureAction];
                        [alert addAction:cancelAction];
                        [weakSelf presentViewController:alert animated:YES completion:^{

                        }];
                    }];
                    action1.backgroundColor = RGB(255, 59, 47);
                    UIContextualAction *action2 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"移动" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (YES);
                        [weakSelf chatListMove:@[@(model.Id)]];

                    }];
                    action2.backgroundColor = RGB(61, 156, 248);
                    UIContextualAction *action3 = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:model.IsTop ? @"取消置顶" : @"置顶" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,void (^ _Nonnull completionHandler)(BOOL)) {
                        completionHandler (YES);
                        [weakSelf chatListIsTop:model];
                    }];
                    action3.backgroundColor = RGB(197, 201, 204);
                    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[action1, action2, action3]];
                    actions.performsFirstActionWithFullSwipe = NO;
                    return actions;
                }
                    break;
            }
    }
    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[]];
    actions.performsFirstActionWithFullSwipe = NO;
    return actions;
}
#else
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS(weakSelf);
    ChatMsgListImModel * model = weakSelf.chatListIMArray[indexPath.row];
    if(self.operationStateEnum == OperationStateEnum0){
            switch (model.AttributeValue) {
                case 2:
                {
                    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认删除" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [weakSelf chatListDelete:@[model].copy];
                        }];
                        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                        }];
                        [alert addAction:sureAction];
                        [alert addAction:cancelAction];
                        [weakSelf presentViewController:alert animated:YES completion:^{

                        }];
                    }];
                    action1.backgroundColor = RGB(255, 59, 47);
                    UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"重命名" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        [weakSelf workGroupReName:model];
                    }];
                    action2.backgroundColor = RGB(255, 149, 3);
                    UITableViewRowAction *action3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:model.IsTop ? @"取消置顶" : @"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        [weakSelf chatListIsTop:model];
                    }];
                    action3.backgroundColor = RGB(197, 201, 204);
                    return @[action1, action2, action3];
                }
                    break;

                case 0:
                {
                    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认删除" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [weakSelf chatListDelete:[NSMutableArray arrayWithArray:@[model]]];
                        }];
                        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                        }];
                        [alert addAction:sureAction];
                        [alert addAction:cancelAction];
                        [weakSelf presentViewController:alert animated:YES completion:^{

                        }];
                    }];
                    action1.backgroundColor = RGB(255, 59, 47);
                    UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"移动" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        [weakSelf chatListMove:@[@(model.Id)]];
                    }];
                    action2.backgroundColor = RGB(61, 156, 248);
                    UITableViewRowAction *action3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:model.IsTop ? @"取消置顶" : @"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                        [weakSelf chatListIsTop:model];
                    }];
                    action3.backgroundColor = RGB(197, 201, 204);
                    return @[action1, action2, action3];
                }
                    break;
            }
    }
    return @[];
}
#endif

- (void)workGroupReName:(ChatMsgListImModel *)model
{
    WS(weakSelf);
    [[ShowNewGroupAlert initShowNewGroupAlertWithTitle:@"重命名" changeStr:model.FolderName confirm:^(NSString * _Nonnull groupName) {
        NSLog(@"%@",groupName);
        [[HttpManager sharedHttpManager] POSTUrl:Host(API_Find_ReName) parameters:@{@"FolderName":groupName,@"Id":@(model.Id)} responseStyle:DATA success:^(id  _Nonnull responseObject) {
            [weakSelf initChatMsgIMData];
        } failure:^(NSError * _Nonnull error) {
            NSLog(@"%@",error);
            SHOWERROR([ZYCTool handerResultData:error])
        }];
    } cancle:^{
    }] show];
}

- (void)getUserInfoInDocument:(NSString *)ImId{
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:USERDEFAULTSGET(@"ChatList")];
    for (NSMutableDictionary * dict in array) {
        if ([[dict objectForKey:@"ImId"] isEqualToString:ImId]) {
            [array removeObject:dict];
        }
    }
    USERDEFAULTSSET(array,@"ChatList");
}
- (void)chatListDelete:(NSMutableArray *)array
{
    NSMutableArray * addArray = [NSMutableArray array];
    for (ChatMsgListImModel * model in array) {
        [addArray addObject:@(model.Id)];
        [self getUserInfoInDocument:[NSString stringWithFormat:@"%ld",(long)model.ImId]];
    }
    SHOWLOADING
    WS(weakSelf);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:addArray forKey:@"MiddleIds"];
    [dic setValue:@(10) forKey:@"FolderType"];
    
    [[HttpManager sharedHttpManager] POSTUrl:Host(API_Find_DeleteRecord) parameters:dic responseStyle:DATA success:^(id  _Nonnull responseObject) {
        REMOVESHOW
        [weakSelf initChatMsgIMData];
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
        NSLog(@"%@",error);
        SHOWERROR([ZYCTool handerResultData:error])
    }];
}
- (void)chatListMove:(NSArray *)array
{
    ChatListMoveVC * vc = [ChatListMoveVC initChatListMoveVC];
    vc.Id = 0;
    vc.titleStr = @"移动到";
    vc.listArray = [NSMutableArray arrayWithArray:array];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)chatListIsTop:(ChatMsgListImModel *)model
{
    WS(weakSelf);
    SHOWLOADING
    [[HttpManager sharedHttpManager] PUTUrl:[NSString stringWithFormat:@"%@%ld",Host(API_Find_Top),(long)model.Id] parameters:@{} responseStyle:DATA success:^(id  _Nonnull responseObject) {
        REMOVESHOW
        [weakSelf reCreateTable];
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
        SHOWERROR([ZYCTool handerResultData:error])
    }];
}
- (void)reCreateTable
{
    [self.chatListIMArray removeAllObjects];
    ChatMsgListImModel * amodel = [[ChatMsgListImModel alloc] init];
    amodel.AttributeValue = 3;
    amodel.Name = @"通讯录";
    amodel.AvatarUrl = @"chat_phone_list";
    [self.chatListIMArray addObject:amodel];
    ChatMsgListImModel * bmodel = [[ChatMsgListImModel alloc] init];
    bmodel.AttributeValue = 4;
    bmodel.Name = @"验证信息";
    bmodel.AvatarUrl = @"chat_yan_message";
    [self.chatListIMArray addObject:bmodel];
    ChatMsgListImModel * cmodel = [[ChatMsgListImModel alloc] init];
    cmodel.AttributeValue = 5;
    cmodel.Name = @"回复我的";
    cmodel.AvatarUrl = @"chat_replay_me";
    [self.chatListIMArray addObject:cmodel];
    WS(weakSelf);
    NSString * url = [NSString stringWithFormat:@"%@0",Host(Often_Contact_List)];
    [[HttpManager sharedHttpManager] GETUrl:url parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
        [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"OftenContactInfos"] isKindOfClass:[NSArray class]]) {
            for (NSDictionary * dict in responseObject[@"OftenContactInfos"]) {
                ChatMsgListImModel * model = [ChatMsgListImModel modelWithDictionary:dict];
                [weakSelf.chatListIMArray addObject:model];
            }
        }
        weakSelf.ConfirmationDate = responseObject[@"ConfirmationDate"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView removeFromSuperview];
            weakSelf.tableView = nil;
            [weakSelf.view addSubview:weakSelf.tableView];
            weakSelf.tableView.delegate = weakSelf;
            weakSelf.tableView.dataSource = weakSelf;
            weakSelf.tableView.backgroundColor = [UIColor clearColor];
            [weakSelf.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(weakSelf.view);
                make.top.mas_equalTo(weakSelf.HeadView.mas_bottom);
                if (@available(iOS 11.0, *)) {
                    make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
                } else {
                    make.bottom.equalTo(weakSelf.view.mas_bottom);
                }
            }];
        });
        [weakSelf _loadAllConversationsFromDBWithIsShowHud:NO];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatListIMArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatMsgListImModel * model = self.chatListIMArray[indexPath.row];
    switch (model.AttributeValue) {
        case 2:
        {
            return [ChatMsgListCell configCell2Height];
        }
            break;
        case 0:
        {
            return [ChatMsgListCell configCell3Height];
        }
            break;
        default:
        {
            if (self.operationStateEnum == OperationStateEnum1) {
                return 0.01f;
            }
            return [ChatMsgListCell configCell3Height];
        }
            break;
    }
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
    ChatMsgListImModel * model = [self.chatListIMArray objectAtIndex:indexPath.row];
    switch (model.AttributeValue) {
        case 2:
        {
            ChatMsgListCell *cell = [ChatMsgListCell configCell2:tableView indexPath:indexPath];
            if(self.operationStateEnum == OperationStateEnum0){
                cell.cell2TitleLabel.text = model.FolderName;
                cell.cell2isTop.hidden = !model.IsTop;
                cell.cell2TimeLabel.hidden = NO;
                cell.cell2TimeLabel.text = [NSDate getTimeStringAutoShort2:model.LastModifiedDate];
                cell.cell2TimeLabel.textColor = RGB(153, 153, 153);
                cell.enterBtn.hidden = YES;
                return cell;
            }
            else if (self.operationStateEnum == OperationStateEnum1){
                ChatMsgListCell *cell = [ChatMsgListCell configCell6:tableView indexPath:indexPath];
                cell.cell6SelectBtn.selected = model.isSelected;
                cell.cell2TitleLabel.text = model.FolderName;
                cell.cell2TimeLabel.hidden = YES;
                cell.enterBtn.hidden = YES;
                cell.cell2RightArrowImgView.hidden = YES;
                cell.IsTopView.hidden = YES;
                self.isAllselect = [self checkChatListArray];
                [self checkMoveBtnEnable];
                [self.operationAllSelectButton setTitle:self.isAllselect ? @"取消全选": @"全选" forState:UIControlStateNormal];
                return cell;
            } else {///if (self.operationStateEnum == OperationStateEnum2)
                cell.cell2TimeLabel.text = @"进入";
                cell.cell2TitleLabel.text = model.FolderName;
                cell.cell2isTop.hidden = !model.IsTop;
                cell.cell2TimeLabel.textColor = RGB(57, 121, 211);
                return cell;
            }
        }
            break;
        case 0:
        {
            if(self.operationStateEnum == OperationStateEnum0){
                ChatMsgListCell *cell = [ChatMsgListCell configCell3:tableView indexPath:indexPath];
                cell.IsTopView.hidden = YES;
                [cell setCell3DataWithModel:model];
                return cell;
            }else if (self.operationStateEnum == OperationStateEnum1){
                ChatMsgListCell *cell = [ChatMsgListCell configCell5:tableView indexPath:indexPath];
                self.isAllselect = [self checkChatListArray];
                [self checkMoveBtnEnable];
                [cell setCell5DataWithModel:model];
                cell.IsTopView.hidden = YES;
                self.isAllselect = [self checkChatListArray];
                [self checkMoveBtnEnable];
                [self.operationAllSelectButton setTitle:self.isAllselect ? @"取消全选": @"全选" forState:UIControlStateNormal];
                [cell.cell5SelectBtn setAction:^{
                    model.isSelected = !model.isSelected;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationAutomatic];
                    });
                }];
                return cell;
            }else{///(self.operationStateEnum == OperationStateEnum2)
                ChatMsgListCell *cell = [ChatMsgListCell configCell3:tableView indexPath:indexPath];
                cell.cell3MengCengView.hidden = NO;
                [cell setCell3DataWithModel:model];
                return cell;
            }
        }
        case 3:{
            ChatMsgListCell *cell = [ChatMsgListCell configCell2:tableView indexPath:indexPath];
            if(self.operationStateEnum == OperationStateEnum1){
                cell.hidden = YES;
            }else{
                cell.hidden = NO;
                cell.cell2TitleLabel.text = model.Name;
                cell.cell2IconImgView.image = IMG(model.AvatarUrl);
                cell.cell2isTop.hidden = YES;
                cell.cell2TimeLabel.hidden = YES;
                cell.cell2TimeLabel.text = [NSDate getTimeStringAutoShort2:model.LastModifiedDate];
                cell.cell2TimeLabel.textColor = RGB(153, 153, 153);
                cell.enterBtn.hidden = YES;
            }
            return cell;
        }break;
        case 4:{
            ChatMsgListCell *cell = [ChatMsgListCell configCell2:tableView indexPath:indexPath];
            if(self.operationStateEnum == OperationStateEnum1){
                cell.hidden = YES;
            }else{
                cell.hidden = NO;
                cell.cell2RedBgView.hidden = self.UReadVerifyCount > 0 ? NO : YES;
                cell.cell2TitleLabel.text = model.Name;
                cell.cell2IconImgView.image = IMG(model.AvatarUrl);
                cell.cell2isTop.hidden = YES;
                cell.cell2TimeLabel.hidden = NO;
                cell.cell2TimeLabel.text = [NSDate getTimeStringAutoShort2:self.ConfirmationDate];
                cell.cell2TimeLabel.textColor = RGB(153, 153, 153);
                cell.enterBtn.hidden = YES;
            }
            return cell;
        }break;
        default:{
            ChatMsgListCell *cell = [ChatMsgListCell configCell2:tableView indexPath:indexPath];
            if(self.operationStateEnum == OperationStateEnum1){
                cell.hidden = YES;
            }else{
                cell.hidden = NO;
                cell.cell2RedBgView.hidden = self.ReplyCount > 0 ? NO : YES;
                cell.cell2TitleLabel.text = model.Name;
                cell.cell2IconImgView.image = IMG(model.AvatarUrl);
                cell.cell2isTop.hidden = YES;
                if (self.ReplyDate.length > 0) {
                    cell.cell2TimeLabel.hidden = NO;
                    cell.cell2TimeLabel.text = [NSDate getTimeStringAutoShort2:self.ReplyDate];
                }else{
                    cell.cell2TimeLabel.hidden = YES;
                }
                cell.cell2TimeLabel.textColor = RGB(153, 153, 153);
                cell.enterBtn.hidden = YES;
            }
            return cell;
        }break;
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ChatMsgListImModel *model = [self.chatListIMArray objectAtIndex:indexPath.row];
    switch (model.AttributeValue) {
        case 2:
        {
            if(self.operationStateEnum == OperationStateEnum0){
                WorkingGroupMainVC *vc = [WorkingGroupMainVC initWorkingGroupMainVC];
                vc.GroupId = [NSString stringWithFormat:@"%ld",(long)model.Id];
                vc.GroupTitle = model.FolderName;
                [self.navigationController pushViewController:vc animated:YES];
            }else if(self.operationStateEnum == OperationStateEnum1){
                //多选操作
                model.isSelected = !model.isSelected;
                [self.tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }
        }
            break;
        case 0:
        {
            if(self.operationStateEnum == OperationStateEnum0){
                //进入聊天界面
                if (model.ChatType == ChatType_SingleChat) {
                    [self enterChatView:model];
                }else{
                    [self getGroupInfo:model];
                }
            }
            else if(self.operationStateEnum == OperationStateEnum1){
                //多选操作
                model.isSelected = !model.isSelected;
                [self.tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
            }
            else if(self.operationStateEnum == OperationStateEnum2){
                //此时不可操作
            }
        }
            break;
        case 3:
        {
            MailListVC * vc = [MailListVC initMailListVC];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 4:
        {
            ChatTestingVC *vc = [ChatTestingVC initChatTestingVC];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
        {
            ReplayMeVC * vc = [ReplayMeVC initReplayMeVC];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
    }
}
- (void)checkMoveBtnEnable
{
    BOOL isEnable = YES;
    for (ChatMsgListImModel *model in self.chatListIMArray) {
        if (model.AttributeValue == 2 && model.isSelected) {
            isEnable = NO;
        }
    }
    [self.operationBottomMoveBtn setEnabled:isEnable];
}
#pragma mark -当环信收到新消息时,更新数据
- (void)replaceChatData
{
    WS(weakSelf);
    [self.chatListIMArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ChatMsgListImModel * chatModel = (ChatMsgListImModel *)obj;
        [weakSelf.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            EMConversationModel * model = (EMConversationModel *)obj;
            if (chatModel.ImId == [model.emModel.conversationId integerValue]) {
                EMConversation *conversation = model.emModel;
                if (!chatModel.IsDisturb) {
                    chatModel.redNum = model.emModel.unreadMessagesCount;
                }
                chatModel.ChatText = [weakSelf _getDetailWithModel:conversation];
            }
        }];
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.tableView reloadData];
    });
}
- (NSAttributedString *)_getDetailWithModel:(EMConversation *)aConversation
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    
    EMMessage *lastMessage = [aConversation latestMessage];
    if (!lastMessage) {
        return attributedStr;
    }
    
    NSString *latestMessageTitle = @"";
    EMMessageBody *messageBody = lastMessage.body;
    switch (messageBody.type) {
        case EMMessageBodyTypeText:
        {
            NSString *str = [EMEmojiHelper convertEmoji:((EMTextMessageBody *)messageBody).text];
            latestMessageTitle = str;
        }
            break;
        case EMMessageBodyTypeImage:
            latestMessageTitle = @"[图片]";
            break;
        case EMMessageBodyTypeVoice:
            latestMessageTitle = @"[音频]";
            break;
        case EMMessageBodyTypeLocation:
            latestMessageTitle = @"[位置]";
            break;
        case EMMessageBodyTypeVideo:
            latestMessageTitle = @"[视频]";
            break;
        case EMMessageBodyTypeFile:
            latestMessageTitle = @"[文件]";
            break;
        default:
            break;
    }
    
    NSDictionary *ext = aConversation.ext;
    if (ext && [ext[kConversation_IsRead] intValue] == kConversation_AtAll) {
        NSString *allMsg = @"[有全体消息]";
        latestMessageTitle = [NSString stringWithFormat:@"%@ %@", allMsg, latestMessageTitle];
        attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
        [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, allMsg.length)];
        
    } else if (ext && [ext[kConversation_IsRead] intValue] == kConversation_AtYou) {
        NSString *atStr = @"[有人@我]";
        latestMessageTitle = [NSString stringWithFormat:@"%@ %@", atStr, latestMessageTitle];
        attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
        [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, atStr.length)];
    } else {
        attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
    }
    
    return attributedStr;
}
- (BOOL)checkChatListArray
{
    if (self.chatListIMArray.count == 0) {
        return NO;
    }
    for (ChatMsgListImModel * model in self.chatListIMArray) {
        if (!model.isSelected) {
            return NO;
        }
    }
    return YES;
}
- (void)enterChatView:(ChatMsgListImModel *)chatModel
{
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:[NSString stringWithFormat:@"%ld",(long)chatModel.ImId] type: EMConversationTypeChat createIfNotExist:YES];
    EMConversationModel *model = [[EMConversationModel alloc] initWithEMModel:conversation];
    EMChatViewController *controller = [[EMChatViewController alloc] initWithCoversationModel:model];

    if (chatModel.ChatType == ChatType_SingleChat) {
        controller.toUserId = chatModel.ToUserId;
        controller.ReceiveIcon = chatModel.AvatarUrl;
        SelectModel * sModel = [[SelectModel alloc] init];
        sModel.UserId = chatModel.ToUserId;
        sModel.UserName = chatModel.Name;
        sModel.AvatarUrl = chatModel.AvatarUrl;
        controller.sModel = sModel;
    }
    model.name = chatModel.Name;
    controller.ImId = chatModel.ImId;
    controller.GroupId = chatModel.Id;
    controller.chatType = chatModel.ChatType;
    controller.listId = chatModel.Id;
    controller.isTop = chatModel.IsTop;
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)getGroupInfo:(ChatMsgListImModel *)chatModel
{
    self.tableView.allowsSelection = NO;
    WS(weakSelf);
    [[HttpManager sharedHttpManager] POSTUrl:Host(Group_chat_info) parameters:@{@"GroupChatImId":@(chatModel.ImId)} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        weakSelf.tableView.allowsSelection = YES;
        EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:[NSString stringWithFormat:@"%ld",(long)chatModel.ImId] type: EMConversationTypeGroupChat createIfNotExist:YES];
        EMConversationModel *model = [[EMConversationModel alloc] initWithEMModel:conversation];
        EMChatViewController *controller = [[EMChatViewController alloc] initWithCoversationModel:model];
        controller.toUserId = chatModel.ImId;
        controller.groupUserInfoArray = responseObject[@"Item"];
        model.name = chatModel.Name;
        controller.GroupId = chatModel.Id;
        controller.ImId = chatModel.ImId;
        controller.chatType = chatModel.ChatType;
        controller.isTop = chatModel.IsTop;
        controller.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:controller animated:YES];
    } failure:^(NSError * _Nonnull error) {
        weakSelf.tableView.allowsSelection = YES;
    }];
}

#pragma mark UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(GHRefreshCollectionView *)collectionView{
    if (self.operationStateEnum == OperationStateEnum1) {
        return 0;
    }
    return 1;
}

/**********************************************************************/
#pragma mark -UICollectionViewDataSource
/**********************************************************************/
- (NSInteger)collectionView:(GHRefreshCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectionDataSource.count;
}

- (UICollectionViewCell *)collectionView:(GHRefreshCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MoreAppInfoModel *bean = [self.collectionDataSource objectAtIndex:indexPath.item];
    ChatMsgCollectionCell *cell = [ collectionView dequeueReusableCellWithReuseIdentifier:@"ChatMsgCollectionCell" forIndexPath:indexPath];
    cell.cell0IconImg.image = [UIImage imageNamed:bean.imgName];
    cell.cell0TitleLabel.text = bean.title;
    switch (bean.type) {
        case ChatMenuNoticeType:
        {
            cell.cell0ReadNumLabel.hidden = YES;
            NSString * count = @"0";
            cell.cell0ReadNumLabel.text = count;
            UILabel * label = [UILabel new];
            label.font = [UIFont systemFontOfSize:12];
            label.text = count;
            CGFloat width = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH, 16)].width;
            if ((width + 5) < 16) {
                cell.constant.constant = 16;
            }else{
                cell.constant.constant = width + 8;
            }
        }
            break;
        case ChatMenuZhanXinType:
        {
            cell.cell0ReadNumLabel.hidden = YES;
            NSString * count = @"0";
            cell.cell0ReadNumLabel.text = count;
            UILabel * label = [UILabel new];
            label.font = [UIFont systemFontOfSize:12];
            label.text = count;
            CGFloat width = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH, 16)].width;
            if ((width + 5) < 16) {
                cell.constant.constant = 16;
            }else{
                cell.constant.constant = width + 8;
            }
        }
            break;
        case ChatMenuWaitType:
        {
            cell.cell0ReadNumLabel.hidden = YES;
            NSString * count = @"0";
            cell.cell0ReadNumLabel.text = count;
            UILabel * label = [UILabel new];
            label.font = [UIFont systemFontOfSize:12];
            label.text = count;
            CGFloat width = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH, 16)].width;
            if ((width + 5) < 16) {
                cell.constant.constant = 16;
            }else{
                cell.constant.constant = width + 8;
            }
        }
            break;
        default:
        {
            cell.cell0ReadNumLabel.hidden = YES ;
        }
            break;
    }
    if(self.operationStateEnum == OperationStateEnum0){
        cell.cell0MengCengView.hidden = YES;
    }else{
        cell.cell0MengCengView.hidden = NO;
    }
    return cell;
}

/****************************************************/
#pragma mark --UICollectionViewDelegateFlowLayout
/****************************************************/
- (CGSize)collectionView:(GHRefreshCollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    CGFloat width = SCREEN_WIDTH / 4;

    CGFloat width = (SCREEN_WIDTH - (15 + 7)) / 5;
    CGFloat height = 90;
    return CGSizeMake(width, height);
}

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

- (CGFloat)collectionView:(GHRefreshCollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(GHRefreshCollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}


- (void)collectionView:(GHRefreshCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if(self.operationStateEnum == OperationStateEnum0){
        MoreAppInfoModel * model = [self.collectionDataSource objectAtIndex:indexPath.item];
         switch (model.type) {
             case ChatMenuNoticeType:{
//                 [self pushChatMsgNoticeVC];
             }break;
             case ChatMenuZhanXinType:{
                 TDInterLeterHomeViewController *vc = [TDInterLeterHomeViewController initChatMsgNoticeVC];
                 vc.hidesBottomBarWhenPushed = YES;
                 vc.interLeterFolderId = 0;
                 vc.isHome = YES;
                 [self.navigationController pushViewController:vc animated:YES];
             }break;
             case ChatMenuTeleListType:{
                 MailListVC *vc = [MailListVC initMailListVC];
                 vc.isChat = YES;
                 vc.hidesBottomBarWhenPushed = YES;
                 [self.navigationController pushViewController:vc animated:YES];
             }break;
             case ChatMenuGroupType:{
                 MyTDGroupViewController *vc = [[MyTDGroupViewController alloc] init];
                 vc.hidesBottomBarWhenPushed = YES;
                 [self.navigationController pushViewController:vc animated:YES];
             }break;
             case ChatMenuWaitType:{
                 WaitWorkVC *vc = [WaitWorkVC initWaitWorkVC];
                 vc.hidesBottomBarWhenPushed = YES;
                 [self.navigationController pushViewController:vc animated:YES];
             }break;
             case ChatMenutopicType:{
                 MyTDTopicViewController *vc = [MyTDTopicViewController initMyTDTopicViewController];
                 vc.hidesBottomBarWhenPushed = YES;
                 [self.navigationController pushViewController:vc animated:YES];
             }break;
             default:
                 break;
         }
    }
    
}

-(NSMutableArray *)collectionDataSource{
    if(!_collectionDataSource){
        _collectionDataSource = [[NSMutableArray alloc] init];
    }
    return _collectionDataSource;
}

- (GHRefreshCollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        CGFloat width = (SCREEN_WIDTH - (15 + 7)) / 5;
        CGFloat height = 90;
        layout.itemSize = CGSizeMake(width, height);
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionView = [[GHRefreshCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"ChatMsgCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"ChatMsgCollectionCell"];
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

-(NSMutableArray *)getMenuDataSource:(NSMutableArray *)titleArray{
    NSMutableArray *menuDataSourceArray = [[NSMutableArray alloc] init];
    for(int i=0;i<titleArray.count;i++){
        NSString *titleStr = [titleArray objectAtIndex:i];
        WS(weakSelf);
        YCMenuAction *actionMenu = [YCMenuAction actionWithTitle:titleStr image:nil handler:^(YCMenuAction *action) {
            if([@"建文件夹" isEqualToString:action.title]){
                [[ShowNewGroupAlert initShowNewGroupAlertWithTitle:@"建文件夹" placeholder:@"请输入文件夹名称" confirm:^(NSString * _Nonnull groupName) {
                    NSLog(@"%@",groupName);
                    NSDictionary * paraDict = @{@"FolderName":groupName,
                                                @"UserId":@([AppUserModel sharedAppUserModel].Id),
                                                @"ParentId":@(0),
                                                @"TypeId":@(10)
                    };
                    [[HttpManager sharedHttpManager] PUTUrl:Host(APP_Middle_Add_Folder) parameters:paraDict responseStyle:JOSN success:^(id  _Nonnull responseObject) {
                        [weakSelf initChatMsgIMData];
                    } failure:^(NSError * _Nonnull error) {
                        NSLog(@"%@",error);
                        SHOWERROR([ZYCTool handerResultData:error])
                    }];
                } cancle:^{
                }] show];
            }
            else if ([@"批量编辑" isEqualToString:action.title]){
                [weakSelf changeToOperation:YES];
            }
            else if ([@"新建群聊" isEqualToString:action.title]){
                ChatNewGroupVC *vc = [ChatNewGroupVC initChatNewGroupVC];
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([@"扫一扫" isEqualToString:action.title]){
                [weakSelf scanAction];
            }
        }];
        [menuDataSourceArray addObject:actionMenu];
    }
    return menuDataSourceArray;
}
#pragma mark - buttonAction
- (void)scanAction{
    SWQRCodeConfig *config = [[SWQRCodeConfig alloc]init];
    config.scannerType = SWScannerTypeBoth;
    SWQRCodeViewController *qrcodeVC = [[SWQRCodeViewController alloc]init];
    qrcodeVC.codeConfig = config;
    qrcodeVC.delegate = self;
    [self.navigationController pushViewController:qrcodeVC animated:YES];
}
#pragma mark - 扫一扫结果
- (void)scanResult:(NSString *)scanStr{
    ScanResultModel *model = [[ScanResultModel alloc]initWithString:scanStr error:nil];
    NSLog(@"%@",model);
    WEAKSELF
    switch (model.key) {
        case 1:// 用户
        {
            [self scanNetWork:model.value urlStrong:SaoYiSao_Post ScanKey:@"Guid"  success:^(id responseObject) {
                NSDictionary *dic = responseObject;
                AddressUserModel *model = [[AddressUserModel alloc] initWithDictionary:dic error:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    MailListDetailVC *vc = [MailListDetailVC initMailListDetailVC];
                    vc.indexId = model.Id;
                    vc.isAdd = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                });
            } failure:^(NSError *error) {
                SHOWERROR([ZYCTool handerResultData:error]);
            }];
        }
            break;
        case 2:// 群聊
        {
            [self scanToNetWork:model.value urlStrong:SaoYiSao2_Post success:^(id responseObject) {
                ChatJoinGroupVC * vc = [ChatJoinGroupVC initChatJoinGroupVC];
                vc.dict = responseObject;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } failure:^(NSError *error) {
                SHOWERROR([ZYCTool handerResultData:error]);
            }];
        }
            break;
        case 3://小组
        {
            [self scanToNetWork:model.value urlStrong:SaoYiSao3_Post success:^(id responseObject) {
                if ([responseObject[@"IsUser"] boolValue]) {
                    TDGroupInfoListVC * vc = [TDGroupInfoListVC initTDGroupInfoListVC];
                    vc.GroupId = [responseObject[@"Id"] integerValue];
                    vc.titleStr = responseObject[@"Name"];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        TDQrJoinVC * vc = [TDQrJoinVC initTDQrJoinVC];
                        vc.dict = responseObject;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    });
                }
            } failure:^(NSError *error) {
                SHOWERROR([ZYCTool handerResultData:error]);
            }];
        }
            break;
        default:
            break;
    }
}
- (void)scanNetWork:(NSString *)scanStr urlStrong:(NSString *)urlstring ScanKey:(NSString*)key success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure{
    SHOWLOADING
    [[HttpManager sharedHttpManager] POSTUrl:[NSString stringWithFormat:@"%@%@",BaseUrl,urlstring] parameters:@{key:scanStr} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        successful(responseObject);
        REMOVESHOW
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
        failure(error);
    }];
}
- (void)scanToNetWork:(NSString *)scanStr urlStrong:(NSString *)urlstring success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure{
    SHOWLOADING
    NSString * url = [NSString stringWithFormat:@"%@%@",Host(urlstring),scanStr];
    [[HttpManager sharedHttpManager] GETUrl:url parameters:@{} success:^(id  _Nonnull responseObject) {
        REMOVESHOW
        successful(responseObject);
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
    }];
}
-(NSMutableArray *)taskActionArray{
    if(!_taskActionArray){
        _taskActionArray = [[NSMutableArray alloc] initWithObjects:@"建文件夹",@"批量编辑",@"新建群聊",@"扫一扫", nil];
    }
    return _taskActionArray;
}
- (void)changeSelectStatus
{
    for ( ChatMsgListImModel * model in self.chatListIMArray) {
        model.isSelected = NO;
    }
}
#pragma mark 批量操作与正常操作界面切换
-(void)changeToOperation:(BOOL)operation{
    if(operation){
        [self removeTableRefresh];
        self.rightButton.hidden = YES;
        self.titleL.text = @"批量编辑";
        //默认操作状态为批量编辑状态
        self.operationStateEnum = OperationStateEnum1;
        self.operationAllSelectButton.hidden = NO;
        self.menuBtn.hidden = YES;
        self.HeadView.hidden = YES;
        self.searchConstant.constant = 0.f;
        WS(weakSelf);
        [self.operationAllSelectButton setAction:^{
            NSLog(@"全选");
            for (ChatMsgListImModel *model in weakSelf.chatListIMArray) {
                model.isSelected = !weakSelf.isAllselect;
            }
            [weakSelf.tableView reloadData];
        }];
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.HeadView.mas_bottom);
            make.bottom.equalTo(self.operationBottomBgView.mas_top);
        }];
//        self.tabBarController.tabBar.hidden = YES;
        self.operationBottomBgView.hidden = NO;
    }else{
        [self addTableRefresh];
        self.titleL.text = @"私信";
        self.rightButton.hidden = NO;
        self.HeadView.hidden = NO;
        self.searchConstant.constant = 50.f;
        //默认操作状态为无状态
        self.operationStateEnum = OperationStateEnum0;
        self.operationAllSelectButton.hidden = YES;
        self.menuBtn.hidden = NO;
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.HeadView.mas_bottom);
            if (@available(iOS 11.0, *)) {
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.bottom.equalTo(self.view.mas_bottom);
            }
        }];
        self.operationBottomBgView.hidden = YES;
    }
    [self.tableView reloadData];
}

#pragma mark 移动     isEdit:当前是否为编辑状态
-(void)userDidMove:(BOOL)move isEdit:(BOOL)isEdit{
    //移动
    if(move){
        //默认操作状态为移动状态
        self.operationStateEnum = OperationStateEnum2;
        self.rightButton.hidden = NO;
        [self resetRightBtnAction:NO];
        
        //隐藏tabBar - 并将TableView至底端
        self.tabBarController.tabBar.hidden = YES;
        self.view.height += self.tabBarController.tabBar.height;
        self.tableView.height += self.tabBarController.tabBar.height;
        [self.view layoutIfNeeded];
        [self.tableView layoutIfNeeded];
        //隐藏operationBottomBgView
        self.operationBottomBgView.hidden = YES;
    }
    else{
        //隐藏tabBar - 并将TableView至底端有tabBar.height的高
        self.tabBarController.tabBar.hidden = YES;
        self.view.height -= self.tabBarController.tabBar.height;
        self.tableView.height -= self.tabBarController.tabBar.height;
        [self.view layoutIfNeeded];
        [self.tableView layoutIfNeeded];
        //显示operationBottomBgView
        self.operationBottomBgView.hidden = NO;
        
        if(isEdit){
            self.operationStateEnum = OperationStateEnum1;
            self.rightButton.hidden = YES;
            [self resetRightBtnAction:YES];
        }else{
            [self changeToOperation:NO];
        }
    }
    [self.tableView reloadData];
}

-(void)initBottomBgView{
    UIButton *leftCloseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftCloseBtn setTitle:@"删除" forState:UIControlStateNormal];
    [leftCloseBtn setTitleColor:RGB(255, 82, 82) forState:UIControlStateNormal];
    leftCloseBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [self.operationBottomBgView addSubview:leftCloseBtn];
    leftCloseBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH/2, self.operationBottomBgView.height);
    
    UIButton *rightMoveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightMoveBtn setTitle:@"移动" forState:UIControlStateNormal];
    [rightMoveBtn setTitleColor:RGB(57, 121, 211) forState:UIControlStateNormal];
    [rightMoveBtn setTitleColor:UIColorHex(#666666) forState:UIControlStateDisabled];
    rightMoveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    self.operationBottomDeleteBtn = leftCloseBtn;
    self.operationBottomMoveBtn = rightMoveBtn;
    [self.operationBottomBgView addSubview:rightMoveBtn];
    rightMoveBtn.frame = CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, self.operationBottomBgView.height);
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = RGB(240, 239, 244);
    [self.operationBottomBgView addSubview:line];
    line.frame = CGRectMake(SCREEN_WIDTH/2, 0, 0.5, self.operationBottomBgView.height);
    
    WS(weakSelf);
    [leftCloseBtn setAction:^{
        [weakSelf.selectArray removeAllObjects];
        for (ChatMsgListImModel * model in weakSelf.chatListIMArray) {
            if (model.isSelected) {
                [weakSelf.selectArray addObject:model];
            }
        }
        if (weakSelf.selectArray.count > 0) {
            [weakSelf isDel:weakSelf.selectArray];
        }
    }];
    [rightMoveBtn setAction:^{
        [weakSelf.selectArray removeAllObjects];
        for (ChatMsgListImModel * model in weakSelf.chatListIMArray) {
            if (model.isSelected) {
                [weakSelf.selectArray addObject:@(model.Id)];
            }
        }
        if (weakSelf.selectArray.count > 0) {
            [weakSelf chatListMove:weakSelf.selectArray];
        }
    }];
    
    [[UtilsTools getWindow] addSubview:self.operationBottomBgView];
}

-(UIView *)operationBottomBgView{
    if(!_operationBottomBgView){
        _operationBottomBgView = [[UIView alloc] init];
        CGFloat bottomBgViewH = self.tabBarController.tabBar.height;
        _operationBottomBgView.frame = CGRectMake(0, SCREEN_HEIGHT - bottomBgViewH, SCREEN_WIDTH, bottomBgViewH);
        _operationBottomBgView.backgroundColor = RGB(255, 255, 255);
        _operationBottomBgView.hidden = YES;
    }
    return _operationBottomBgView;
}

-(void)isDel:(NSMutableArray *)array
{
    WS(weakSelf);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确认删除?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf chatListDelete:array];
    }];
    [alertController addAction:cancel];
    [alertController addAction:ok];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(NSMutableArray *)chatListIMArray{
    if(!_chatListIMArray){
        _chatListIMArray = [[NSMutableArray alloc] init];
    }
    return _chatListIMArray;
}
-(NSMutableArray *)selectArray{
    if(!_selectArray){
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}
-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (MyTDGroupView *)SearchView
{
    if (!_SearchView) {
        _SearchView = [[MyTDGroupView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 36)];
    }
    return _SearchView;
}
- (void)getChatRecord{
    
}
#pragma mark - 接收通知跳转到群聊页面
- (void)pushEMChatViewController:(NSNotification *)notification
{
    NSDictionary * groupDict = notification.userInfo;
    NSString * groupId = [NSString stringWithFormat:@"%@",[groupDict objectForKey:@"GroupChatImId"]];
    WS(weakSelf);
    [[HttpManager sharedHttpManager] POSTUrl:Host(Group_chat_info) parameters:@{@"GroupChatImId":groupId} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:[NSString stringWithFormat:@"%@",groupId] type: EMConversationTypeGroupChat createIfNotExist:YES];
        EMConversationModel *model = [[EMConversationModel alloc] initWithEMModel:conversation];
        EMChatViewController *controller = [[EMChatViewController alloc] initWithCoversationModel:model];
        controller.toUserId = [[groupDict objectForKey:@"GroupChatImId"] integerValue];
        controller.groupUserInfoArray = responseObject[@"Item"];
        model.name = [groupDict objectForKey:@"Name"];
        controller.GroupId = [[groupDict objectForKey:@"Id"] integerValue];
        controller.chatType = ChatType_GroupChat;
        controller.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:controller animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (void)pushTDGroupController:(NSNotification *)notification
{
    MyTDGroupViewController *vc = [[MyTDGroupViewController alloc] init];
    vc.isPush = YES;
    vc.pushDict = notification.userInfo;
    [self.navigationController pushViewController:vc animated:NO];
}
//#pragma mark - 接收Drawer通知跳转到对应的子页面
//- (void)pushSubViewController:(NSNotification *)notification
//{
//    ///@"站内信", @"通知", @"收藏",@"笔记", @"设置"
//    NSInteger index = [[notification.userInfo objectForKey:VCINDEX] integerValue];
//    switch (index) {
//        case 0:
//        {
//            [self pushInterLeterVC];
//        }
//            break;
//        case 1:
//        {
//            [self pushChatMsgNoticeVC];
//        }
//            break;
//        default:
//            break;
//    }
//}
//#pragma mark - 跳转到站内信、通知页面
//- (void)pushInterLeterVC
//{
//    TDInterLeterHomeViewController *vc = [TDInterLeterHomeViewController initChatMsgNoticeVC];
//    vc.interLeterFolderId = 0;
//    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//}
//- (void)pushChatMsgNoticeVC
//{
//    ChatMsgListVC *vc = [ChatMsgListVC initChatMsgListVC];
//    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//}
- (void)viewWillDisappear:(BOOL)animated
{
    [self changeToOperation:NO];
}
- (void)dealloc
{
    [[EMClient sharedClient].chatManager removeDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
    [[EMConversationHelper shared] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end