
//
//  ConfListViewController.m
//  HWMSDKDemo
//
//

#import "ConfListViewController.h"
#import "BookConfViewController.h"
#import "ConfListTableViewCell.h"
#import "DateUtil.h"
#import <HWMUISDK/HWMSdk.h>
#import "CycleConfViewController.h"
#import "SubCycleConfListViewController.h"

@interface ConfListViewController ()
@property (nonatomic, strong) NSArray <HWMBaseConfDetailParam *> *confList;
@end

@implementation ConfListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"会议列表";
    [self initData];

    [self setupTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConfList) name:@"onReceiveConfList" object:nil];
}

- (void)initData {
    self.confList = [[HWMBizSdk getBizOpenApi] getConfList];
}

- (void)setupTableView {
    [super setupTableView];
    [self.tableView registerClass:[ConfListTableViewCell class] forCellReuseIdentifier:@"ConfListTableViewCell"];
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HWMBaseConfDetailParam *model = self.confList[indexPath.row];
    ConfListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConfListTableViewCell"];
    cell.titleLabel.numberOfLines = 0;
    NSLog(@"isCycleConf : %d, startTime:%f confSubject:%@",(model.conferenceType == HWMSDKConfTypeCycle), model.startTimeStamp, model.confSubject);
    NSString *title = (model.conferenceType == HWMSDKConfTypeCycle)  ? @"周期会议主题" : @"会议主题";
    cell.titleLabel.text = [NSString stringWithFormat:@"%@：%@ \n会议ID：%@ \n会议密码：%@  \n主席密码：%@ \n开始时间：%@",title, model.confSubject, model.vmrConferenceId.length > 0 ? model.vmrConferenceId : model.confId, model.generalPwd, model.chairmanPwd, [DateUtil formatTimeStringWithTimeInterval:model.startTimeStamp isHasTimeZoneInterval:NO]];
    weakify(self)
    cell.clickEvent = ^(BtnType type) {
        strongify(self)
        if (type == BtnTypeCancelConf) {
            [self cancelConfClick:model];
        } else if (type == BtnTypeEditConf) {
            [self editConfClick:model.confId];
        } else if (type == BtnTypeSubCycleConf) {
            [self openSubCycleConfList:model.confId];
        }
    };
    
    if (model.conferenceType == HWMSDKConfTypeCycle) {
        if (model.chairmanPwd.length == 0) {
            [cell.cancelBtn setHidden:YES];
            [cell.editBtn setHidden:YES];
        }else{
            [cell.cancelBtn setHidden:NO];
            [cell.editBtn setHidden:NO];
        }
        cell.subCycleConfBtn.hidden = NO;
    }else{
        NSDate *startTime =  [DateUtil formatDateWithTimeInterval:model.startTime isHasTimeZoneInterval:YES];
        if ([startTime laterDate:[NSDate date]] != startTime || model.chairmanPwd.length == 0) {
            NSLog(@"HWMConf_ not future conf, can't show cancel");
            [cell.cancelBtn setHidden:YES];
            [cell.editBtn setHidden:YES];
        } else {
            NSLog(@"HWMConf_ future conf, can show cancel");
            [cell.cancelBtn setHidden:NO];
            [cell.editBtn setHidden:NO];
        }
        cell.subCycleConfBtn.hidden = YES;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HWMBaseConfDetailParam *model = self.confList[indexPath.row];
    [[HWMBizSdk getBizOpenApi] getConfDetail:model.confId completeHandler:^(NSError * _Nullable error, HWMConfDetail * _Nullable result) {
        if (error) {
            [UIUtil showMessageWithError:error];
        } else {
            __block NSMutableString *info = [[NSMutableString alloc] initWithString:result.confSubject];
            [info appendFormat:@"\ncustomInfo:%@,\n最大与会方数:%ld",result.customInfo, result.concurrentParticipants];
            [result.attendee enumerateObjectsUsingBlock:^(HWMAttendeeInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [info appendFormat:@"\nthirdUserId:%@, number:%@, name:%@, aliasCN:%@, aliasEN:%@", obj.thirdUserId, obj.number, obj.name, obj.aliasCN, obj.aliasEN];
            }];
            [info appendFormat:@"\n时区:%@", result.timeZone];
            [info appendFormat:@"\n会议纪要:%ld", result.defaultSummaryState];
            [info appendFormat:@"\n自动发布会议纪要:%d", result.autoPublishSummary];
            [UIUtil showMessage:info];
        }
    }];
}

- (void)editConfClick:(NSString *)confId {
    [[HWMBizSdk getBizOpenApi] getConfDetail:confId completeHandler:^(NSError * _Nullable error, HWMConfDetail * _Nullable result) {
        NSLog(@"getConfDetail:%@", result);
        if (error) {
            [UIUtil showMessageWithError:error];
        } else {
            if (result.conferenceType == HWMSDKConfTypeCycle) {
                [self pushEditCycleConfVc:result];
            }else{
                [self pushEditVc: [self creatOrderConfParam:result]];
            }
        }
    }];
}

- (void)openSubCycleConfList:(NSString *)confId {
    [[HWMBizSdk getBizOpenApi] getConfDetail:confId completeHandler:^(NSError * _Nullable error, HWMConfDetail * _Nullable result) {
        NSLog(@"getConfDetail:%@", result);
        if (error) {
            [UIUtil showMessageWithError:error];
        } else {
            SubCycleConfListViewController *subConfListVC = [[SubCycleConfListViewController alloc] initWithCycleConfDetail:result];
            [self.navigationController pushViewController:subConfListVC animated:YES];
        }
    }];
}

- (void)pushEditVc:(HWMOrderConfParam *)orderConfParam {
    BookConfViewController *vc = [[BookConfViewController alloc] init];
    vc.confInfo = orderConfParam;
    vc.isEditConf = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushEditCycleConfVc:(HWMConfDetail *)confDetail{
    CycleConfViewController *cycleVC = [[CycleConfViewController alloc] init];
    cycleVC.operationType = HWMCycleConfOperationTypeEdit;
    cycleVC.confDetail = confDetail;
    cycleVC.cycleConfInfo.orderConfParam = [self creatOrderConfParam:confDetail];
    [self.navigationController pushViewController:cycleVC animated:YES];
}

- (void)cancelConfClick:(HWMBaseConfDetailParam *)baseConfDetail {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定取消会议吗" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancelConf:baseConfDetail];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)cancelConf:(HWMBaseConfDetailParam *)baseConfDetail {
    if (baseConfDetail.conferenceType == HWMSDKConfTypeCycle) {
        HWMSDKCancelCycleConfParamModel *cancelParam = [[HWMSDKCancelCycleConfParamModel alloc] init];
        cancelParam.confId = baseConfDetail.confId;
        cancelParam.endOnlineConf = YES;
        [[HWMBizSdk getBizOpenApi] cancelCycleConfWithParam:cancelParam callback:^(NSError * _Nullable error, id  _Nullable result) {
            [UIUtil showMessage:@"取消周期会议成功" error:error];

        }];
    }else{
        [[HWMBizSdk getBizOpenApi] cancelConf:baseConfDetail.confId callback:^(NSError *_Nullable error, id _Nullable result) {
            [UIUtil showMessage:@"取消会议成功" error:error];
        }];
    }
}

- (HWMOrderConfParam *)creatOrderConfParam:(HWMConfDetail *)confDetail {
    HWMOrderConfParam * orderConfParam = [[HWMOrderConfParam alloc] init];
    orderConfParam.confSubject = confDetail.confSubject;
    orderConfParam.startTimeStamp = confDetail.startTimeStamp;
    orderConfParam.isSmsOn = confDetail.isSendSms;
    orderConfParam.isMailOn = confDetail.isSendNotify;
    orderConfParam.isEmailCalenderOn = confDetail.isSendCalendarNotify;
    orderConfParam.isRecordOn = confDetail.recordType == 2;
    orderConfParam.isAutoRecord = confDetail.isAutoRecord;
    orderConfParam.confType = confDetail.isVideo ? OrderConfTypeVideo : OrderConfTypeAudio;
    orderConfParam.vmrId = confDetail.vmrId;
    orderConfParam.confId = confDetail.confId;
    NSDate *start = [self timestampToDate:confDetail.startTimeStamp];
    NSDate *end = [self timestampToDate:confDetail.endTimeStamp];
    orderConfParam.duration = [self minutesBetweenFromDate:start ToDate:end];
    orderConfParam.attendee = confDetail.attendee;
    orderConfParam.isNeedConfPwd = !confDetail.isGuestFreePwd;
    orderConfParam.guestPwd = confDetail.generalPwd;
    orderConfParam.callInRestrictionType = (HWMJoinConfRestrictionType)confDetail.callInRestriction;
    orderConfParam.vmrIdType = confDetail.vmrConferenceId.length > 0 ? HWMVmrIdTypeFixed : HWMVmrIdTypeRandom;
    orderConfParam.allowGuestStartConf = confDetail.allowGuestStartConf;
    orderConfParam.allowGuestStartConfTime = confDetail.allowGuestStartConfTime;
    orderConfParam.customInfo = confDetail.customInfo;
    orderConfParam.concurrentParticipants = confDetail.concurrentParticipants;
    orderConfParam.timeZone = [confDetail.timeZone integerValue];
    orderConfParam.autoMuteMode = confDetail.autoMuteMode;
    orderConfParam.hardTerminalAutoMuteMode = confDetail.hardTerminalAutoMuteMode;
    orderConfParam.supportWatermark = confDetail.supportWatermark;
    orderConfParam.defaultSummaryState = confDetail.defaultSummaryState;
    orderConfParam.autoPublishSummary = confDetail.autoPublishSummary;
    return orderConfParam;
}

- (void)updateConfList {
    [self initData];
    [self.tableView reloadData];
}

- (NSDate *)timestampToDate:(NSTimeInterval)time {
    return [[NSDate alloc] initWithTimeIntervalSince1970:time];
}

- (int)minutesBetweenFromDate:(NSDate *)fromDate ToDate:(NSDate *)toDate
{
    NSDate *mFromDate, *mToDate;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar rangeOfUnit:NSCalendarUnitMinute startDate:&mFromDate
                 interval:NULL forDate:fromDate];
    [calendar rangeOfUnit:NSCalendarUnitMinute startDate:&mToDate
                 interval:NULL forDate:toDate];
    NSDateComponents *diHC = [calendar components:NSCalendarUnitMinute
                                         fromDate:mFromDate
                                           toDate:mToDate
                                          options:0];
    return (int)diHC.minute;
}

@end
