//
//  SubCycleConfListViewController.m
//  HWMSDKDemo
//
//  Created by 付细华 on 2021/10/23.
//  Copyright © 2021 HuaWei. All rights reserved.
//

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



@interface SubCycleConfListViewController ()
@property (nonatomic ,strong) HWMConfDetail *confDetail;
@property (nonatomic ,strong) UILabel *detailLable;


@end

@implementation SubCycleConfListViewController

- (instancetype)initWithCycleConfDetail:(HWMConfDetail *)confDetail{
    if (self = [super init]) {
        _confDetail = confDetail;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupTableView];
    [self setupDetailView];
    self.title = @"周期子会议";
    // Do any additional setup after loading the view.
}

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

- (void)setupDetailView{
    UILabel *detailLable = [[UILabel alloc] init];
    detailLable.numberOfLines = 0;
    [self.view addSubview:detailLable];
    self.detailLable = detailLable;
    [detailLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.top.right.equalTo(self.view);
    }];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(detailLable.mas_bottom).offset(10);
        make.left.right.bottom.equalTo(self.view);
    }];
    [self updateDetailLabelInfo];
}

- (void)updateDetailLabelInfo{
    NSString *cycleText = [self cycleText:self.confDetail.cycleParam];
    NSString *endTime = [DateUtil formatTimeStringWithTimeInterval:self.confDetail.cycleParam.endDate isHasTimeZoneInterval:NO];
    NSString *endDate = [endTime substringWithRange:NSMakeRange(0, 10)];
    NSString *detail = [NSString stringWithFormat:@"会议主题：%@\n重复周期：%@\n结束于%@ 剩余%zd会议\n自定义信息：%@\n最大与会方数:%ld",self.confDetail.confSubject,cycleText,endDate,self.confDetail.subConf.count, self.confDetail.customInfo, self.confDetail.concurrentParticipants];
    self.detailLable.text = detail;
}

- (NSString *)cycleText:(HWMSDKCycleConfParamModel *)param{
    if (param.cycleType == HWMSDKCycleTypeDay) {
        return [NSString stringWithFormat:@"每%zd天",param.interval];
    }else if(param.cycleType == HWMSDKCycleTypeWeek){
        return [NSString stringWithFormat:@"每%zd周（%@）",param.interval,param.listPoints];
    }else{
        return [NSString stringWithFormat:@"每%zd月（%@）",param.interval,param.listPoints];
    }
}


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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HWMSDKSubCycleConfParamModel *model = self.confDetail.subConf[indexPath.row];
    ConfListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubConfListTableViewCell"];
    cell.titleLabel.numberOfLines = 0;
    NSString *startTime =  [DateUtil formatTimeStringWithTimeInterval:model.startTimeStamp isHasTimeZoneInterval:NO];
    NSString *endTime = [DateUtil formatTimeStringWithTimeInterval:model.endTimeStamp isHasTimeZoneInterval:NO];
    NSString *detail = [NSString stringWithFormat:@"开始时间：%@ \n结束时间：%@",startTime,endTime];
    cell.titleLabel.text = detail;
    weakify(self)
    cell.clickEvent = ^(BtnType type) {
        strongify(self)
        if (type == BtnTypeCancelConf) {
            [self cancelSubConf:model];
        } else {
            [self editSubConf:model];
        }
    };
    if (self.confDetail.chairmanPwd.length == 0) {
        [cell.cancelBtn setHidden:YES];
        [cell.editBtn setHidden:YES];
    } else {
        [cell.cancelBtn setHidden:NO];
        [cell.editBtn setHidden:NO];
    }
    cell.subCycleConfBtn.hidden = YES;
    
    return cell;
}

- (void)cancelSubConf:(HWMSDKSubCycleConfParamModel *)subConfInfo{
    
    NSDate *startTime =  [DateUtil formatDateWithTimeInterval:subConfInfo.startTime isHasTimeZoneInterval:YES];
    if ([startTime laterDate:[NSDate date]] != startTime) {
        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 confirmCancelSubConf:subConfInfo];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self confirmCancelSubConf:subConfInfo];
    }
}

- (void)confirmCancelSubConf:(HWMSDKSubCycleConfParamModel *)subConfInfo{
    HWMSDKCancelSubCycleConfParamModel *cancelParma = [[HWMSDKCancelSubCycleConfParamModel alloc] init];
    cancelParma.confId = self.confDetail.confId;
    cancelParma.subConfID = subConfInfo.subConfID;
    cancelParma.endOnlineConf = YES;
    [[HWMBizSdk getBizOpenApi] cancelSubCycleWithParam:cancelParma callback:^(NSError * _Nullable error, id  _Nullable result) {
        NSString *tips = !error ? @"取消会议成功" : @"取消会议失败";
        [UIUtil showMessage:tips error:error];
        if (!error) {
            [self updateSubConfList];
        }
    }];
}

- (void)updateSubConfList{
    [[HWMBizSdk getBizOpenApi] getConfDetail:self.confDetail.confId completeHandler:^(NSError * _Nullable error, HWMConfDetail * _Nullable result) {
        if (!error) {
            self.confDetail = result;
            [self.tableView reloadData];
            [self updateDetailLabelInfo];
        }else {
            [UIUtil showMessageWithError:error];
        }
    }];
}

- (void)editSubConf:(HWMSDKSubCycleConfParamModel *)subConfInfo{
    CycleConfViewController *cycleConfVc = [[CycleConfViewController alloc] init];
    cycleConfVc.operationType = HWMCycleConfOperationTypeEditSubConf;
    cycleConfVc.confDetail = self.confDetail;
    cycleConfVc.subConfInfo = subConfInfo;
    [self.navigationController pushViewController:cycleConfVc animated:YES];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
