//
//  ChatMsgTopSearchVC.m
//  smartRhino
//
//  Created by niuzhen on 2020/4/8.
//  Copyright © 2020 tederen. All rights reserved.
//

#import "ChatMsgTopSearchVC.h"
#import "MailListByZuCell.h"
#import "MailListDetailVC.h"
#import "ChatSearchModel.h"
#import "ChatMsgListCell.h"
#import "NSDate+Extension.h"
#import "EMChatViewController.h"
#import "WorkingGroupMainVC.h"

@interface ChatMsgTopSearchVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, copy) NSMutableArray *listArray;
@end

@implementation ChatMsgTopSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = RGB(255, 255, 255);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.historySearchType = HistorySearchType_XinYuan;
    [self addObserver:self forKeyPath:@"searchText" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    id obj = [change objectForKey:@"new"];
    NSString * text = @"";
    if ([obj isKindOfClass:[NSString class]]) {
        text = obj;
    }else{
        text  = [obj stringValue];
    }
    if (text.length > 0) {
        [self getData];
    }
}
- (void)getData
{
    WEAKSELF
    [self.listArray removeAllObjects];
    NSString * url = [NSString stringWithFormat:@"%@%@",Host(API_APP_Often_Contact_Search),self.searchText];
    NSString * urlHost = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [[HttpManager sharedHttpManager] GETUrl:urlHost parameters:@{} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        NSLog(@"搜索结果:%@",responseObject);
        for (NSDictionary *dic in responseObject) {
            ChatSearchModel * model = [ChatSearchModel modelWithDictionary:dic];
            [weakSelf.listArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.listArray.count > 0) {
                weakSelf.collectionView.hidden = YES;
                weakSelf.noDataView.hidden = YES;
                weakSelf.tableView.hidden = NO;
                [weakSelf.tableView reloadData];
            }else{
                weakSelf.noDataView.hidden = NO;
                weakSelf.collectionView.hidden = YES;
                weakSelf.tableView.hidden = YES;
                weakSelf.noDataL.text = @"暂无数据";
            }
        });
    } failure:^(NSError * _Nonnull error) {
          SHOWERROR([ZYCTool handerResultData:error])
          
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatSearchModel * model = [self.listArray objectAtIndex:indexPath.row];
    switch (model.TypeValue) {
        case ChatSearchUserType:
        {
            return [MailListByZuCell configCell2Height];
        }
            break;
        case ChatSearchOnlyType:
        {
            return [ChatMsgListCell configCell3Height];
        }
            break;
        case ChatSearchGroupType:
        {
            return [ChatMsgListCell configCell3Height];
        }
            break;
        default:
        {
            return [ChatMsgListCell configCell2Height];
        }
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatSearchModel * model = [self.listArray objectAtIndex:indexPath.row];
    switch (model.TypeValue) {
        case ChatSearchUserType:
        {
            MailListByZuCell *cell = [MailListByZuCell configCell2:tableView indexPath:indexPath];
            cell.cell0TitleLabel.text = model.Name;
            cell.cell0DepartMentName.text = model.DepartmentName;
            [cell.cell0ImgView sd_setImageWithURL:[NSURL URLWithString:model.AvatarUrl] placeholderImage:IMG(@"chatmsg_list_testuser_img")];
            return cell;
        }
            break;
        case ChatSearchOnlyType:
        {
            ChatMsgListCell *cell = [ChatMsgListCell configCell3:tableView indexPath:indexPath];
            [cell setCellSearchModel:model];
            return cell;
        }
            break;
        case ChatSearchGroupType:
        {
            ChatMsgListCell *cell = [ChatMsgListCell configCell3:tableView indexPath:indexPath];
            [cell setCellSearchModel:model];
            return cell;
        }
            break;
        default:
        {
            ChatMsgListCell *cell = [ChatMsgListCell configCell2:tableView indexPath:indexPath];
            cell.cell2TitleLabel.text = model.Name;
            cell.cell2TimeLabel.hidden = NO;
            cell.IsTopView.hidden = YES;
            cell.cell2TimeLabel.text = [NSDate getTimeStringAutoShort2:model.LastModifiedDate];
            cell.cell2TimeLabel.textColor = RGB(153, 153, 153);
            cell.enterBtn.hidden = YES;
            return cell;
        }
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ChatSearchModel *model = [self.listArray objectAtIndex:indexPath.row];
    switch (model.TypeValue) {
        case ChatSearchUserType:
        {
            MailListDetailVC *vc = [MailListDetailVC initMailListDetailVC];
            vc.indexId = model.Id;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case ChatSearchOnlyType:
        {
            [self enterChatView:model];
        }
            break;
        case ChatSearchGroupType:
        {
            [self getGroupInfo:model];
        }
            break;
        default:
        {
            WorkingGroupMainVC *vc = [WorkingGroupMainVC initWorkingGroupMainVC];
            vc.GroupId = [NSString stringWithFormat:@"%ld",(long)model.Id];
            vc.GroupTitle = model.Name;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
    }
}
- (void)enterChatView:(ChatSearchModel *)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.TypeValue == ChatSearchOnlyType) {
        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 = 1;
    controller.listId = chatModel.Id;
    controller.isTop = chatModel.IsTop;
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)getGroupInfo:(ChatSearchModel *)chatModel
{
    WS(weakSelf);
    [[HttpManager sharedHttpManager] POSTUrl:Host(Group_chat_info) parameters:@{@"GroupChatImId":@(chatModel.ImId)} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        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 = 2;
        controller.isTop = chatModel.IsTop;

        [weakSelf.navigationController pushViewController:controller animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (NSMutableArray *)listArray{
    if (!_listArray) {
        _listArray = [NSMutableArray new];
    }
    return _listArray;
}
@end