//
//  CustomMenuViewController.m
//  HWMSDKDemo
//
//

#import "CustomMenuViewController.h"
#import <HWMUISDK/HWMUISDK.h>
#import "CustomInMeetingUIManager.h"
#import "UIUtil.h"
#import "CustomInMeetingUIManager.h"
@interface CustomMenuViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) CustomUIType customType;
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, copy) NSString *titleString;
@end

@implementation CustomMenuViewController

- (instancetype)initWithType:(CustomUIType)type title:(NSString *)title {
    if (self = [super init]) {
        self.customType = type;
        self.titleString = title;
    }
    return self;
}

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

- (void)initTitle {
    self.title = self.titleString;
    [self addEditButton];
}

- (void)edit {
    [self.tableView setEditing:YES animated:YES];
    [self addFinishedButton];
}

- (void)finished {
    [self addEditButton];
    [self.tableView setEditing:NO animated:YES];
}

- (void)addEditButton {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit)];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)addFinishedButton {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finished)];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)initTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"CustomMenuCellIdentifier"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)loadData {
    CustomInMeetingUIManager *manager = [CustomInMeetingUIManager sharedInstance];
    self.items = [manager getCustomMenuItems:self.customType].mutableCopy;
    [self.tableView reloadData];
}

- (BOOL)isGroupMode {
    // 设置是两级菜单
    return self.customType == CustomUITypeVideoCallSetting || self.customType == CustomUITypeVideoConfSetting || self.customType == CustomUITypeAudioConfSetting;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self isGroupMode]) {
        return 30;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[section];
        UILabel *groupTitle = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, [UIScreen mainScreen].bounds.size.width - 32, 20)];
        groupTitle.font = [UIFont systemFontOfSize:12.0];
        groupTitle.textColor = [UIColor grayColor];
        groupTitle.text = group.title;
        return groupTitle;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54.f;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self isGroupMode]) {
        return self.items.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[section];
        return group.items.count + 1;
    } else {
        return self.items.count + 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomMenuCellIdentifier"];
    cell.selectTypeSwitch.hidden = YES;
    cell.titleLabel.hidden = YES;
    NSInteger row = indexPath.row;
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[indexPath.section];
        if (row == group.items.count) {
            cell.textLabel.text = @"增加一个菜单项";
        } else {
            if (row < group.items.count) {
                HWMConfMenuItem *item = group.items[indexPath.row];
                cell.textLabel.text = item.text;
            }
        }
    } else {
        if (row == self.items.count) {
            cell.textLabel.text = @"增加一个菜单项";
            cell.imageView.image = nil;
        } else {
            if (row < self.items.count) {
                HWMConfMenuItem *item = self.items[indexPath.row];
                if ([item isKindOfClass:HWMConfMenuItem.class]) {
                    cell.textLabel.text = item.text;
                } else if ([item isKindOfClass:HWMSideListMenuItem.class]) {
                    cell.imageView.image = ((HWMSideListMenuItem *)item).image;
                    cell.imageView.backgroundColor = UIColor.lightGrayColor;
                }
            }
        }
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[indexPath.section];
        return row != group.items.count;
        return NO;
    } else {
        return row != self.items.count;
    }
}

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    NSInteger rowCount = 0;
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[sourceIndexPath.section];
        rowCount = group.items.count;
    } else {
        rowCount = self.items.count;
    }
    if (proposedDestinationIndexPath.row >= rowCount) {
        // 禁止最后一行移动
        return [NSIndexPath indexPathForRow:rowCount - 1 inSection:sourceIndexPath.section];
    }
    if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
        //禁止跨区
        return sourceIndexPath;
    }
    return proposedDestinationIndexPath;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    NSInteger addRow = 0;
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[destinationIndexPath.section];
        addRow = group.items.count;
    } else {
        addRow = self.items.count;
    }
    if (addRow != destinationIndexPath.row) {
        [self exchangeItemsAtIndexPath:destinationIndexPath withIndexPath:sourceIndexPath];
        [tableView exchangeSubviewAtIndex:sourceIndexPath.row withSubviewAtIndex:destinationIndexPath.row];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[indexPath.section];
        return group.items.count == indexPath.row ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
    } else {
        return indexPath.row == self.items.count ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (editingStyle) {
        case UITableViewCellEditingStyleDelete: {
            [self removeItemAtIndexPath:indexPath];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        break;
        case UITableViewCellEditingStyleInsert: {
            if ([self addItemAtIndexPath:indexPath]) {
                [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
        }
        break;

        default:
            break;
    }
}

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

- (HWMConfMenuItem *)createTestItem {
    NSInteger newCtrlType = [[CustomInMeetingUIManager sharedInstance] generateCtrlType];
    switch (self.customType) {
        case CustomUITypeConfTitleInfo: {
            HWMInMeetingCellModel *item = [[HWMInMeetingCellModel alloc] initWithCellType:newCtrlType title:[NSString stringWithFormat:@"自定义菜单：%ld", (long)newCtrlType]];
            item.delegate = [CustomInMeetingUIManager sharedInstance];
            return item;
        }
        break;
        case CustomUITypeAudioCallToolBar:
        case CustomUITypeAudioConfToolBar:
        case CustomUITypeVideoCallToolBar:
        case CustomUITypeVideoConfToolBar:
        case CustomUITypeMemberListTitleBar:
        case CustomUITypeMemberListToolBar:
        case CustomUITypeWaitingListToolBar:
        case CustomUITypeOfflineListToolBar:{
            HWMConfToolBarMenuItem *item = [[HWMConfToolBarMenuItem alloc] initWithType:newCtrlType
                                                                                   text:[NSString stringWithFormat:@"菜单：%ld", (long)newCtrlType]
                                                                                  image:[UIImage imageNamed:@"custom_conf_setting"]];
            if (self.customType == CustomUITypeMemberListTitleBar) {
                item.clickEvent = ^(HWMConfCtrlType type) {
                    [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义菜单%lu", (unsigned long)type]];
                };
            } else {
                item.menuClickEvent = ^(HWMConfCtrlType type, UIButton *_Nonnull menuItemBtn) {
                    [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义菜单%lu", (unsigned long)type]];
                };
            }
            return item;
        }
        break;
        case CustomUITypeAudioConfMore:
        case CustomUITypeVideoCallMore:
        case CustomUITypeVideoConfMore: {
            HWMConfMenuListItem *item = [[HWMConfMenuListItem alloc] initEnterItemWithType:newCtrlType
                                                                                      text:[NSString stringWithFormat:@"菜单：%ld", newCtrlType]
                                                                                     image:[UIImage imageNamed:@"custom_conf_setting"]];
            item.clickEvent = ^(HWMConfCtrlType type) {
                [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义菜单%lu", (unsigned long)type]];
            };
            return item;
        }
        break;
        case CustomUITypeAudioConfSetting:
        case CustomUITypeVideoCallSetting:
        case CustomUITypeVideoConfSetting:
        {
            if (newCtrlType%2 == 0) {
                HWMConfSettingItem *item = [[HWMConfSettingItem alloc] initItemWithType:newCtrlType text:[NSString stringWithFormat:@"自定义菜单：%ld", (long)newCtrlType] viewType:HWMConfSettingViewTypeEnter];
                item.clickEvent = ^(HWMConfCtrlType type) {
                    [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义菜单%lu", (unsigned long)type]];
                };
                return item;
            }else{
                HWMConfSettingItem *item = [[HWMConfSettingItem alloc] initSwitchItemWithType:newCtrlType text:[NSString stringWithFormat:@"自定义菜单：%ld", (long)newCtrlType]];
                item.switchEvent = ^(HWMConfCtrlType type, UISwitch * _Nonnull actionSwitch) {
                    [UIUtil showMessage:[NSString stringWithFormat:@"切换了自定义菜单%lu，是否打开？%d", (unsigned long)type, actionSwitch.isOn]];
                };
                return item;
            }
        }
        break;
        case CustomUITypeMemberListActionSheet: {
            HWMConfParticipantActionMenuItem *item = [[HWMConfParticipantActionMenuItem alloc] initWithType:newCtrlType text:[NSString stringWithFormat:@"自定义菜单：%ld", (long)newCtrlType]];
            item.actionClickEvent = ^(HWMConfCtrlType type, HWMConfParticipant * _Nonnull participant) {
                [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义菜单%lu", (unsigned long)type]];
            };
            return item;
        }
        break;
        default: {
            HWMConfMenuItem *item = [[HWMConfMenuItem alloc] initWithType:newCtrlType text:[NSString stringWithFormat:@"自定义菜单：%ld", (long)newCtrlType]];
            return item;
        }
        break;
    }
}

- (HWMSideListMenuItem *)createTestSideListMenuItem {
    HWMSideListMenuType newType = [[CustomInMeetingUIManager sharedInstance] generateSideListMenuType];
    HWMSideListMenuItem *item = [[HWMSideListMenuItem alloc] init];
    item.type = newType;
    item.image = [UIImage imageNamed:@"custom_conf_setting"];
    item.actionEvent = ^(HWMSideListMenuType type, UIButton * _Nonnull btn) {
        [UIUtil showMessage:[NSString stringWithFormat:@"点击了自定义按钮%ld", type]];
    };
    return item;
}

- (BOOL)addItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[indexPath.section];
        NSMutableArray *items = [group.items mutableCopy];
        HWMConfMenuItem *item = [self createTestItem];
        [items addObject:item];
        group.items = items;
    } else if (self.customType == CustomUITypeSideListMenu) {
        NSMutableArray *items = [self.items mutableCopy];
        HWMSideListMenuItem *item = [self createTestSideListMenuItem];
        [items addObject:item];
        self.items = items;
    } else {
        NSMutableArray *items = [self.items mutableCopy];
        if (items.count > [self getItemsMaxLimit]) {
            [UIUtil showMessage:@"定制菜单超过最大限制"];
            return NO;
        }
        HWMConfMenuItem *item = [self createTestItem];
        [items addObject:item];
        self.items = items;
    }
    [[CustomInMeetingUIManager sharedInstance] updateCustomMenuItems:self.customType items:self.items];
    return YES;
}

- (NSInteger)getItemsMaxLimit {
    if (self.customType == CustomUITypeAudioCallToolBar
        || self.customType == CustomUITypeAudioConfMore
        || self.customType == CustomUITypeVideoConfMore
        || self.customType == CustomUITypeVideoCallMore
        || self.customType == CustomUITypeAudioConfToolBar
        || self.customType == CustomUITypeVideoCallToolBar
        || self.customType == CustomUITypeVideoConfToolBar) {
        return 6;
    } else if (self.customType == CustomUITypeMemberListTitleBar) {
        return 3;
    } else if (self.customType == CustomUITypeMemberListToolBar) {
        return 4;
    } else {
        return NSIntegerMax;
    }
}

- (void)removeItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isGroupMode]) {
        HWMConfSettingGroup *group = self.items[indexPath.section];
        NSMutableArray *items = [group.items mutableCopy];
        [items removeObjectAtIndex:indexPath.row];
        group.items = items;
    } else {
        [self.items removeObjectAtIndex:indexPath.row];
    }
    [[CustomInMeetingUIManager sharedInstance] updateCustomMenuItems:self.customType items:self.items];
}

- (void)exchangeItemsAtIndexPath:(NSIndexPath *)toIndexPath withIndexPath:(NSIndexPath *)fromIndexPath {
    if ([self isGroupMode]) {
        if (toIndexPath.section == fromIndexPath.section) {
            HWMConfSettingGroup *toGroup = self.items[toIndexPath.section];
            NSMutableArray *items = [toGroup.items mutableCopy];
            [items exchangeObjectAtIndex:toIndexPath.row withObjectAtIndex:fromIndexPath.row];
            toGroup.items = items;
        } else {
            // 跨group移动
            HWMConfSettingGroup *toGroup = self.items[toIndexPath.section];
            NSMutableArray *toItems = [toGroup.items mutableCopy];
            HWMConfSettingGroup *fromGroup = self.items[fromIndexPath.section];
            NSMutableArray *fromItems = [fromGroup.items mutableCopy];
            HWMConfSettingItem *moveItem = fromItems[fromIndexPath.row];
            [toItems insertObject:moveItem atIndex:toIndexPath.row];
            [fromItems removeObjectAtIndex:fromIndexPath.row];
            toGroup.items = toItems;
            fromGroup.items = fromItems;
        }
    } else {
        [self.items exchangeObjectAtIndex:toIndexPath.row withObjectAtIndex:fromIndexPath.row];
    }
    [[CustomInMeetingUIManager sharedInstance] updateCustomMenuItems:self.customType items:self.items];
}

@end
