//
//  SortView.m
//  ALand
//
//  Created by Z on 16/3/24.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "SortView.h"
#import "CoverShadowView.h"
#import "IBTUIViewController.h"
@interface SortView ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) CGFloat clickCount;
@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) NSMutableArray *arrSelectedMark;
@property (nonatomic, assign) BOOL isTableOpen;
@end

@implementation SortView


- (instancetype)customNew {
    //SortView *sortView = [SortView new];
    
    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;
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:leftButton];
    self.leftBtn = leftButton;
    [leftButton setTitle:@"综合排序          " 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 setNormalStateWithTitle:@"销量优先" titleColor:kTextColorBlack image:nil];
    
    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;
}

- (void)rightBtnAction {
    
    self.rightAction();
    
    [self.rightBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
    [self.leftBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
    if (self.isTableOpen == YES) {
        [self iconAnimate];
        [self hideTableView];
    }
}

- (CoverShadowView *)coverView {
    if (!_coverView) {
        _coverView = [[CoverShadowView alloc] initWithSpaceToTop:self.bottom + 64];
        [self.window addSubview:_coverView];
        WS(weakSelf)
        _coverView.tapAction = ^{
            [weakSelf leftAction:nil];
        };
        
        
        
        
    }
    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;
        _arrTitles = @[@"综合排序",
                       @"价格从高到低",
                       @"价格从低到高",
                       @"佣金从高到低",
                       @"佣金从低到高",
                       @"点击量从高到低",
                       @"点击量从低到高"];
        _arrSelectedMark = [NSMutableArray array];
        for (int i = 0; i < self.arrTitles.count; i++) {
            [self.arrSelectedMark addObject:@"NO"];
        }
        
        [_arrSelectedMark replaceObjectAtIndex:0 withObject:@"YES"];
        
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
        [self.window addSubview:_tableView];
        
        [self showTableView];
    }
    return _tableView;
}


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

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


#pragma mark ==============table delegate==============
- (void)resetMark {
    for (int i = 0; i  < self.arrTitles.count; i++) {
        [self.arrSelectedMark replaceObjectAtIndex:i withObject:@"NO"];
    }
}

#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];
    [self resetMark];
    [self.arrSelectedMark replaceObjectAtIndex:indexPath.row withObject:@"YES"];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    [tableView reloadData];
    [self leftAction:nil];
    self.selecedBlock(indexPath.row);
    [self setLeftBtnTitle:self.arrTitles[indexPath.row]];
    [self.leftBtn setTitleColor:kCustomGreenColor forState:UIControlStateNormal];
    [self.rightBtn setTitleColor:kTextColorBlack forState:UIControlStateNormal];
}

- (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.arrSelectedMark[indexPath.row] isEqualToString:@"YES"]) {
        cell.textLabel.textColor = kCustomGreenColor;
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    }else{
        cell.textLabel.textColor = [UIColor blackColor];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    return cell;
}

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

- (void)leftAction:(UIButton *)btn {
    if (self.clickCount != M_PI) {
        [self showTableView];
        
    }else{
        [self hideTableView];
        
    }
    [self iconAnimate];
}

- (void)iconAnimate {
    self.clickCount = self.clickCount + M_PI;
    if (self.clickCount > M_PI * 2 ) {
        self.clickCount = M_PI;
    }
    WS(weakSelf)
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.leftBtn.imageView.transform = CGAffineTransformMakeRotation(weakSelf.clickCount);
        
    }];
}

- (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) {
        [self leftAction:nil];
    }
}


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

@end
