//
//  HWMConfDetailViewController.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2020/11/2.
//  Copyright © 2020 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMConfDetailViewController.h"
#import <HWMUISDK/HWMUISDK.h>
#import "HWMConfDetailCell.h"
#import "HWMConfDetailItemModel.h"
#import "HWMBookConfViewController.h"
#import "NSViewController+HWMNavigation.h"
#import "HWMSubCycleConfCountCell.h"
#import "HWMBookCycleConfViewController.h"
#import "HWMSubConfListViewController.h"

@interface HWMConfDetailViewController ()<NSTableViewDelegate, NSTableViewDataSource>
/// tableView
@property (nonatomic, strong) NSTableView *listView;
/// scrollView
@property (nonatomic, strong) NSScrollView *scrollView;
/// 会议数据
@property (nonatomic, strong) NSMutableArray <HWMConfDetailItemModel *> *dataArr;
/// 编辑
@property (nonatomic, strong) NSButton *editBtn;
/// 取消按钮
@property (nonatomic, strong) NSButton *cancelBtn;

/// model
@property (nonatomic, strong) HWMConfDetail *detailModel;

@end

@implementation HWMConfDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}

#pragma mark - Data
- (void)loadData {
    if (![HWMSdk hasInit]) {
        return;
    }

    @weakify(self)
    [[HWMBizSdk getBizOpenApi] getConfDetail: self.confId completeHandler:^(NSError *_Nullable error, HWMConfDetail *_Nullable result) {
        @strongify(self)
        if (error) {
            [HWMConsoleManager shareInstance].error = error;
        } else {
            [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"获取会议详情 %@", [result yy_modelDescription]];
            [self setupDetailData:result];
            [self.listView reloadData];
        }
    }];
}

- (void)setupDetailData:(HWMConfDetail *)detail {
    [self.dataArr removeAllObjects];
    self.detailModel = detail;
    HWMConfDetailItemModel *subModel = [[HWMConfDetailItemModel alloc] init];
    subModel.title = @"会议主题";
    subModel.content = detail.confSubject;
    [self.dataArr addObject:subModel];

    HWMConfDetailItemModel *timeModel = [[HWMConfDetailItemModel alloc] init];
    timeModel.title = @"会议时间";
    
    NSString *startTime = [NSString timeStringFromTimeInterval:detail.startTimeStamp];
    NSString *endTime = [NSString timeStringFromTimeInterval:detail.endTimeStamp];
    timeModel.content = [NSString stringWithFormat:@"%@ - %@", startTime, endTime];
    [self.dataArr addObject:timeModel];

    HWMConfDetailItemModel *idModel = [[HWMConfDetailItemModel alloc] init];
    idModel.title = @"会议ID";
    idModel.content = detail.vmrConferenceId.length > 0 ? detail.vmrConferenceId : detail.confId;
    [self.dataArr addObject:idModel];

    HWMConfDetailItemModel *hostModel = [[HWMConfDetailItemModel alloc] init];
    hostModel.title = @"主持人密码";
    hostModel.content = detail.chairmanPwd;
    [self.dataArr addObject:hostModel];

    HWMConfDetailItemModel *guestModel = [[HWMConfDetailItemModel alloc] init];
    guestModel.title = @"来宾密码";
    guestModel.content = detail.generalPwd;
    [self.dataArr addObject:guestModel];

    HWMConfDetailItemModel *typeModel = [[HWMConfDetailItemModel alloc] init];
    typeModel.title = @"会议类型";
    typeModel.content = detail.videoConf ? @"视频会议" : @"音频会议";
    [self.dataArr addObject:typeModel];

    HWMConfDetailItemModel *orderModel = [[HWMConfDetailItemModel alloc] init];
    orderModel.title = @"会议预订人";
    orderModel.content = detail.confScheduledName;
    [self.dataArr addObject:orderModel];

    HWMConfDetailItemModel *recordModel = [[HWMConfDetailItemModel alloc] init];
    recordModel.title = @"自动录制会议";
    recordModel.content = detail.isAutoRecord ? @"是" : @"否";
    [self.dataArr addObject:recordModel];
    
    HWMConfDetailItemModel *allowGuestJoinModel = [[HWMConfDetailItemModel alloc] init];
    allowGuestJoinModel.title = @"允许来宾提前入会";
    allowGuestJoinModel.content = detail.allowGuestStartConf ? @"允许" : @"不允许";
    [self.dataArr addObject:allowGuestJoinModel];
    
    if (![self isFixedVmrConf] && detail.allowGuestStartConf) {
        HWMConfDetailItemModel *allowGuestTimeModel = [[HWMConfDetailItemModel alloc] init];
        allowGuestTimeModel.title = @"允许来宾提前多久入会";
        allowGuestTimeModel.content = detail.allowGuestStartConfTime > 0 ?  [NSString stringWithFormat:@"%ld分钟",detail.allowGuestStartConfTime] : @"任意时间";
        [self.dataArr addObject:allowGuestTimeModel];
    }
    
    HWMConfDetailItemModel *openWaitingRoomModel = [[HWMConfDetailItemModel alloc] init];
    openWaitingRoomModel.title = @"是否开启等候室";
    openWaitingRoomModel.content = detail.isOpenWaitingRoom ? @"开启" : @"关闭";
    [self.dataArr addObject:openWaitingRoomModel];

    HWMConfDetailItemModel *autoMuteModel = [[HWMConfDetailItemModel alloc] init];
    autoMuteModel.title = @"个人客户端入会自动静音";
    autoMuteModel.content = detail.autoMuteMode == HWMSDKAutoMuteTypeMute ? @"开启" : @"关闭";
    [self.dataArr addObject:autoMuteModel];
    
    HWMConfDetailItemModel *hardTerminalAutoModel = [[HWMConfDetailItemModel alloc] init];
    hardTerminalAutoModel.title = @"会议室设备入会自动静音";
    hardTerminalAutoModel.content = detail.hardTerminalAutoMuteMode == HWMSDKAutoMuteTypeMute ? @"开启" : @"关闭";
    [self.dataArr addObject:hardTerminalAutoModel];
    
    HWMConfDetailItemModel *supportWatermarkModel = [[HWMConfDetailItemModel alloc] init];
    supportWatermarkModel.title = @"是否支持水印";
    supportWatermarkModel.content = detail.supportWatermark ? @"开启" : @"关闭";
    [self.dataArr addObject:supportWatermarkModel];
    
    HWMConfDetailItemModel *defaultSummaryStateModel = [[HWMConfDetailItemModel alloc] init];
    defaultSummaryStateModel.title = @"录制时开启会议纪要";
    defaultSummaryStateModel.content = detail.defaultSummaryState ? @"开启" : @"关闭";
    [self.dataArr addObject:defaultSummaryStateModel];
    
    HWMConfDetailItemModel *autoPublishSummaryModel = [[HWMConfDetailItemModel alloc] init];
    autoPublishSummaryModel.title = @"自动发布会议纪要";
    autoPublishSummaryModel.content = detail.autoPublishSummary ? @"开启" : @"关闭";
    [self.dataArr addObject:autoPublishSummaryModel];

    HWMConfDetailItemModel *customInfoModel = [[HWMConfDetailItemModel alloc] init];
    customInfoModel.title = @"自定义信息";
    customInfoModel.content = detail.customInfo;
    [self.dataArr addObject:customInfoModel];
    
    HWMConfDetailItemModel *maxModel = [[HWMConfDetailItemModel alloc] init];
    maxModel.title = @"最大与会人数";
    maxModel.content = [NSString stringWithFormat:@"%ld", detail.concurrentParticipants];
    [self.dataArr addObject:maxModel];
    
    HWMConfDetailItemModel *timeZoneModel = [[HWMConfDetailItemModel alloc] init];
    timeZoneModel.title = @"时区";
    timeZoneModel.content = [NSTimeZone systemTimeZone].name;
    [self.dataArr addObject:timeZoneModel];
}

- (BOOL)isFixedVmrConf {
    return self.detailModel.vmrFlag && self.detailModel.vmrConfIdType == HWMVmrConfIdTypeFixed;
}

#pragma mark - UI
- (void)setupUI {
    self.scrollView = [[NSScrollView alloc] init];
    [self.scrollView setHasVerticalScroller:YES];
    [self.scrollView setHasHorizontalScroller:NO];
    [self.scrollView setBorderType:NSNoBorder];
    [self.scrollView setDrawsBackground:NO];
    [self.scrollView setAutohidesScrollers:YES];
    [self.scrollView setHorizontalScrollElasticity:NSScrollElasticityNone];
    [self.scrollView setVerticalScrollElasticity:NSScrollElasticityNone];
    [self.view addSubview:self.scrollView];

    self.listView = [[NSTableView alloc] init];
    self.listView.delegate = self;
    self.listView.dataSource = self;
    self.listView.backgroundColor = [NSColor whiteColor];
    self.listView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone;
    NSTableHeaderView *headerView = [[NSTableHeaderView alloc] initWithFrame:NSZeroRect];
    self.listView.headerView = headerView;
    NSTableColumn *colmn = [[NSTableColumn alloc] initWithIdentifier:@"createConf"];
    [self.listView addTableColumn:colmn];
    self.scrollView.documentView = self.listView;

    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(45);
        make.trailing.equalTo(self.view).offset(-15);
        make.bottom.equalTo(self.view).offset(-75);
    }];

    [self.view addSubview:self.editBtn];
    [self.view addSubview:self.cancelBtn];

    [self.editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view).offset(-20);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(100);
    }];

    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.editBtn.mas_leading).offset(-10);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(100);
    }];
}

#pragma mark - Event

- (void)editConf {
    NSString *startTime = [NSString timeStringFromTimeInterval:self.detailModel.startTimeStamp];
    if ([self isOverTime:startTime]) {
        [HWMConsoleManager shareInstance].console = @"会议已开始，不可以编辑";
        return;
    }
    
    if (self.detailModel.conferenceType == HWMSDKConfTypeCycle) {
        HWMBookCycleConfViewController *bookCycle = [[HWMBookCycleConfViewController alloc] init];
        bookCycle.detailModel = self.detailModel;
        @weakify(self)
        [bookCycle setEditCycleConfSuccessHandler:^{
            @strongify(self)
            [self loadData];
        }];
        [self.customNavigationController pushViewController:bookCycle animated:YES];
    } else {
        HWMBookConfViewController *book = [[HWMBookConfViewController alloc] init];
        book.detailModel = self.detailModel;
        @weakify(self)
        [book setEditConfSuccessHandler:^{
            @strongify(self)
            [self loadData];
        }];
        [self.customNavigationController pushViewController:book animated:YES];
    }
}

- (void)cancelConf {
    
    if (self.detailModel.conferenceType == HWMSDKConfTypeCycle) {
        // 取消周期会议
        HWMSDKCancelCycleConfParamModel *model = [[HWMSDKCancelCycleConfParamModel alloc] init];
        model.confId = self.detailModel.confId;
        model.endOnlineConf = YES;
        [[HWMBizSdk getBizOpenApi] cancelCycleConf:model callback:^(NSError * _Nullable error, id  _Nullable result) {
            if (error) {
                [HWMConsoleManager shareInstance].error = error;
            } else {
                [HWMConsoleManager shareInstance].console = @"cancel cycle conf successful";
                [self.customNavigationController popViewControllerAnimated:YES];
            }
        }];
        
    } else {
        
        NSString *startTime = [NSString timeStringFromTimeInterval:self.detailModel.startTimeStamp];
        if ([self isOverTime: startTime]) {
            [HWMConsoleManager shareInstance].console = @"会议已开始，无法取消";
            return;
        }
        
        [[HWMBizSdk getBizOpenApi] cancelConf:self.detailModel.confId callback:^(NSError *_Nullable error, id _Nullable result) {
            if (error) {
                [HWMConsoleManager shareInstance].error = error;
            } else {
                [HWMConsoleManager shareInstance].console = @"cancel conf successful";
                [self.customNavigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

- (BOOL)isOverTime:(NSString *)dateTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *startDate = [formatter dateFromString:dateTime];
    NSDate *currentDate = [NSDate date];
    NSComparisonResult result = [startDate compare:currentDate];

    if (result ==  NSOrderedAscending) {
        return YES;
    } else if (result == NSOrderedDescending) {
        return NO;
    } else {
        // result == NSOrderedSame 也算是超时
        return YES;
    }
}

#pragma mark - Delegate
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    if (self.detailModel.conferenceType == HWMSDKConfTypeCycle) {
        return self.dataArr.count + 1;
    }
    return self.dataArr.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    if (row == self.dataArr.count) {
        HWMSubCycleConfCountCell *subCell = [HWMSubCycleConfCountCell initSubCycleConfCountCell:tableView ower:self];
        subCell.subConfCount = self.detailModel.subConfParam.count;
        @weakify(self)
        [subCell setSubCycleConfSelectHandler:^{
            @strongify(self)
            HWMSubConfListViewController *listVC = [[HWMSubConfListViewController alloc] init];
            listVC.detailModel = self.detailModel;
            listVC.backBlock = ^{
                [self loadData];
            };
            [self.customNavigationController pushViewController:listVC animated:YES];
        }];
        
        return subCell;
    }
    HWMConfDetailCell *cell = [HWMConfDetailCell confDetailCell:tableView ower:self];
    cell.model = self.dataArr[row];
    return cell;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 45.0;
}

#pragma mark - Lazy

- (NSMutableArray<HWMConfDetailItemModel *> *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSButton *)editBtn {
    if (!_editBtn) {
        _editBtn = [NSButton buttonWithTitle:@"编辑会议" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(editConf)];
        _editBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _editBtn.layer.cornerRadius = 4.0;
        _editBtn.layer.masksToBounds = YES;
    }
    return _editBtn;
}

- (NSButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [NSButton buttonWithTitle:@"取消会议" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(cancelConf)];
        _cancelBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _cancelBtn.layer.cornerRadius = 4.0;
        _cancelBtn.layer.masksToBounds = YES;
    }
    return _cancelBtn;
}

@end
