//
//  JavenSortView.m
//  ALand
//
//  Created by Z on 16/4/15.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "JavenSortView.h"
#import "CoverShadowView.h"
#import "IBTUIViewController.h"

@interface JavenSortView ()
<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) CGFloat clickCount;
@property (nonatomic, assign) CGFloat rightClickCount;
@property (nonatomic, strong) CoverShadowView *coverView;
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *arrTitles;
@property (nonatomic, strong) NSArray *arrLeft;
@property (nonatomic, strong) NSArray *arrRight;
@property (nonatomic, assign) NSInteger selectedMark;
@property (nonatomic, strong) CoverShadowView *viewTopCover;
@property (nonatomic, assign) BOOL isTableOpen;
@property (nonatomic, assign) BOOL isLeft;
@property (nonatomic, assign) BOOL isLeftOpen;
@property (nonatomic, assign) CGFloat PI;


@end
@implementation JavenSortView
+ (instancetype)sortViewLeftTitles:(NSArray *)leftTitles rightTitles:(NSArray *)rightTitles
{
    JavenSortView *sortView = [[JavenSortView alloc] initSortViewLeftTitles:leftTitles rightTitles:rightTitles];
    return sortView;
}

- (instancetype)initSortViewLeftTitles:(NSArray *)leftTitles rightTitles:(NSArray *)rightTitles {
     self = [super init];
    self.PI = 3.143;
    self.arrLeft = leftTitles;
    self.arrRight = rightTitles;
    
    UIView *grayLine = [UIView new];
    [self addSubview:grayLine];
    grayLine.sd_layout.topSpaceToView(self, 5).bottomSpaceToView(self, 5).centerXEqualToView(self).centerYEqualToView(self).widthIs(1);
    grayLine.backgroundColor = kBacroundColor;
    self.backgroundColor = kSysWhite;
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:leftButton];
    self.leftBtn = leftButton;
    [leftButton setTitle:[NSString stringWithFormat:@"%@          ", leftTitles[0]] forState:UIControlStateNormal];
    [leftButton setTitleColor:kTextColorBlack forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"downIcon"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    leftButton.imageView.tintColor = kTextColorGray;
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, 115, 0, 0);
    leftButton.sd_layout.topEqualToView(self).leftEqualToView(self).rightSpaceToView(grayLine,0).bottomEqualToView(self);
    [leftButton updateLayout];
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:self.rightBtn];
    [self.rightBtn setTitle:[NSString stringWithFormat:@"%@          ", rightTitles[0]] forState:UIControlStateNormal];
    [self.rightBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
    [self.rightBtn setImage:[UIImage imageNamed:@"downIcon"] forState:UIControlStateNormal];
    
    self.rightBtn.imageView.tintColor = kTextColorGray;
    self.rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 115, 0, 0);    self.rightBtn.sd_layout.leftSpaceToView(grayLine,0).topEqualToView(self).bottomEqualToView(self).rightEqualToView(self);
    [self.rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIView *viewGrayBottom = [UIView new];
    viewGrayBottom.backgroundColor = kCutLineColorLiteGray;
    [self addSubview:viewGrayBottom];
    viewGrayBottom.sd_layout.bottomEqualToView(self).leftEqualToView(self).rightEqualToView(self).heightIs(1);
    
    
    
    return self;
}


- (CoverShadowView *)coverView {
    if (!_coverView) {
        _coverView = [[CoverShadowView alloc] initWithSpaceToTop:self.bottom + 64];
        [self.window addSubview:_coverView];
        WS(weakSelf)
        _coverView.tapAction = ^{
            [weakSelf hide];
        };
        
        
        
        
    }
    return _coverView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.bottom + 64, ScreenSize.width, 0) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
        [self.window addSubview:_tableView];
        
        [self showTableView];
    }
    return _tableView;
}


#pragma mark ==============animate==============
- (void)showTableView {
    [self.coverView show];
    [self setOtherUserInteraction:NO];
    
    WS(weakSelf)
    self.isTableOpen = YES;
    [UIView animateWithDuration:0.3 delay:0 options:(UIViewAnimationOptionCurveEaseIn) animations:^{
        weakSelf.tableView.height = 44 * weakSelf.arrTitles.count;
        [weakSelf.tableView reloadData];
    } completion:nil];
}

- (void)hideTableView {
    [self.coverView hide];
    [self setOtherUserInteraction:YES];
    
    self.isTableOpen = NO;
    WS(weakSelf)
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.tableView.height = 0;
    }];
}

//设置界面上其它的按钮是否可以点击
- (void)setOtherUserInteraction:(BOOL)state {
    //    [self viewController].navigationItem.leftBarButtonItem.enabled = state;
    //    [self viewController].navigationItem.rightBarButtonItem.enabled = state;
    //[self viewController].view.userInteractionEnabled = state;
    
}



#pragma mark ==============table delegate==============


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.arrTitles.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    self.selectedMark = indexPath.row;
    [tableView reloadData];
    
    
    NSString *space;
    if (self.arrTitles == self.arrLeft) {
        space = @"left";
        [self leftAction:nil];
        [self setBtn:self.leftBtn Title:self.arrTitles[indexPath.row]];
        CLog(@"%@", self.arrTitles[indexPath.row]);
        [self.leftBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
        [self.rightBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
        self.leftTableSelect(indexPath.row);
        self.isLeft = YES;
    }else{
        space = @"right";
        [self rightBtnAction];
        [self setBtn:self.rightBtn Title:self.arrTitles[indexPath.row]];
        [self.leftBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
        [self.rightBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
        self.rightTableSelect(indexPath.row);
        self.isLeft = NO;
    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    cell.textLabel.text = self.arrTitles[indexPath.row];
    // Configure the cell...
    cell.tintColor = kCustomGreenColor;
    
    if (self.isLeft == self.isLeftOpen) {
        
        if (self.selectedMark == indexPath.row) {
            cell.textLabel.textColor = kCustomGreenColor;
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        }else{
            cell.textLabel.textColor = [UIColor blackColor];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
    }else{
        cell.textLabel.textColor = [UIColor blackColor];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    
    return cell;
}

- (void)setBtn:(UIButton *)btn Title:(NSString *)str {
    
    //只是为了让标题位置正确
    [btn setTitle:[NSString stringWithFormat:@"%@            ",str] forState:UIControlStateNormal];
    
    if (str.length > 6) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 135, 0, 0);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    }else if (str.length > 4) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 130, 0, 0);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 115, 0, 0);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }

    NSLog(@"%f", self.leftBtn.titleLabel.frame.size.width);
}

- (void)leftAction:(UIButton *)btn {
    [self rightIconAnimateToDefault];
    _arrTitles = _arrLeft;
    if (self.clickCount != self.PI) {
        [self showTableView];
        self.isLeftOpen = YES;
        
    }else{
        [self hideTableView];
        self.isLeftOpen = NO;
        
    }
    [self iconAnimate];
}

- (void)rightBtnAction {
    [self leftIconAnimateToDefault];
    _arrTitles = _arrRight;
    if (self.rightClickCount != self.PI) {
        [self showTableView];
        self.isLeftOpen = NO;
    }else{
        [self hideTableView];
        self.isLeftOpen = NO;
        
    }
    [self rightIconAnimate];
}


#pragma mark =========== animate ===========

//控制左边的按钮上的剪头动画
- (void)iconAnimate {
    self.clickCount = self.clickCount + self.PI;
    if (self.clickCount > self.PI * 2 ) {
        self.clickCount = self.PI;
    }
    WS(weakSelf)
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.leftBtn.imageView.transform = CGAffineTransformMakeRotation(weakSelf.clickCount);
        
    }];
}

- (void)leftIconAnimateToDefault {
    self.leftBtn.imageView.transform = CGAffineTransformMakeRotation(0);
    self.isLeftOpen = NO;
    self.clickCount = 0;


}

- (void)rightIconAnimateToDefault {
    self.rightBtn.imageView.transform = CGAffineTransformMakeRotation(0);
    self.isLeftOpen = YES;
    self.rightClickCount = 0;
}



- (void)rightIconAnimate {
    self.rightClickCount = self.rightClickCount + self.PI;
    if (self.rightClickCount > self.PI * 2 ) {
        self.rightClickCount = self.PI;
    }
    WS(weakSelf)
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.rightBtn.imageView.transform = CGAffineTransformMakeRotation(weakSelf.rightClickCount);
        
    }];
}

- (UIViewController *)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[IBTUIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

- (void)hide {
    if (self.isTableOpen == YES) {
        if (_arrTitles == _arrLeft) {
            [self leftAction:nil];
        }else{
            [self rightBtnAction];
        }
    }
}


- (void)defaultSelectISLeft:(BOOL)isLeft row:(NSInteger)row
{
    self.selectedMark = row;
    if (isLeft) {
        self.isLeft = YES;
        self.arrTitles = self.arrLeft;
        [self setBtn:self.leftBtn Title:self.arrTitles[row]];
        [self.leftBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
        [self.rightBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
        
        self.isLeft = YES;
    }else{
        self.isLeft = NO;
        self.arrTitles = self.arrRight;
        [self setBtn:self.rightBtn Title:self.arrTitles[row]];
        [self.leftBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
        [self.rightBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
        self.isLeft = NO;
        
    }
}

- (NSArray *)getCurrentTitles {
    NSArray *array = [NSArray arrayWithArray:self.arrTitles];
    return array;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
