


#import "SLDatePickView.h"

@interface SLDatePickView()

@property(nonatomic, strong) UIView *toolView;

@property (nonatomic, strong) UILabel *titleLabel;

@property(nonatomic, strong) UIButton *cancelBtn;

@property(nonatomic, strong) UIButton *sureBtn;

@property(nonatomic, strong) UIDatePicker *datePicker;

@property(nonatomic, strong) SLCustDatePickView *custDatePickView;
@end

@implementation SLDatePickView

-(nonnull id)initWithStyle:(SLDatePickerStyle)dateStyle pickerData:(nonnull SLDatePickerDO *)pickerDO
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT);
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        self.dateStyle = dateStyle;
        self.pickerDO = pickerDO;
        [self confignUI];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenDatePickView)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

- (void)setTitleLabelText:(NSString *)text {
    self.titleLabel.text = text;
}

- (void)cancelBtnClick
{
    [self hiddenDatePickView];
}

- (void)sureBtnClick
{
    if ([self.delegate respondsToSelector:@selector(datePick:result:)]) {
        if (self.dateStyle == SLDatePickerYM) {
            NSString *dateString = [NSString stringWithFormat:@"%ld.%02ld", self.custDatePickView.selectedYear, self.custDatePickView.selectedMonth];
            NSDate *selectedDate = [self.custDatePickView.dateFormatter dateFromString:dateString];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//返回一个日期格式对象
            dateFormatter.dateFormat = self.pickerDO.format;
            [self.delegate datePick:self result:[dateFormatter stringFromDate:selectedDate]];
        }else {
            NSDate *theDate = self.datePicker.date;//该属性返回选中的时间
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//返回一个日期格式对象
            dateFormatter.dateFormat = self.pickerDO.format;
            [self.delegate datePick:self result:[dateFormatter stringFromDate:theDate]];
        }
    }
    if (self.resultBlock) {
        NSDate *theDate = self.datePicker.date;//该属性返回选中的时间
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//返回一个日期格式对象
        dateFormatter.dateFormat = self.pickerDO.format;
        self.resultBlock([dateFormatter stringFromDate:theDate]);
    }
    [self removeFromSuperview];
}

- (void)hiddenDatePickView
{
    if (self.cancleBtnClickBlock) {
        self.cancleBtnClickBlock();
    }
    [self removeFromSuperview];
}

- (void)show
{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}

- (void)drawRect:(CGRect)rect {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.toolView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(8 , 8)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.toolView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.toolView.layer.mask = maskLayer;
}

- (void)confignUI
{
    
    [self.datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.mas_bottom).offset(-kSafeAreaBottom);
        make.height.equalTo(@(216));
    }];
    
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(self.datePicker.mas_top).offset(0);
        make.height.equalTo(@(44));
    }];
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.toolView);
        make.left.equalTo(self.toolView.mas_left).offset(6);
        make.width.equalTo(@(63));
    }];
    
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.toolView);
        make.right.equalTo(self.toolView.mas_right).offset(-6);
        make.width.equalTo(@(63));
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.toolView);
    }];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectZero];
    lineView.backgroundColor = SLColor(@"#F2F3F7");
    [self.toolView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.toolView);
        make.bottom.equalTo(self.toolView.mas_bottom).offset(-1);
        make.height.mas_equalTo(1);
    }];
    self.datePicker.maximumDate = [self timeFromFormatter:self.pickerDO.format timeString:self.pickerDO.maxDateString];
    self.datePicker.minimumDate = [self timeFromFormatter:self.pickerDO.format timeString:self.pickerDO.minDateString];
    self.datePicker.date = [self timeFromFormatter:self.pickerDO.format timeString:self.pickerDO.strText] ?: [NSDate date];
    if (self.dateStyle == SLDatePickerHM) {
        self.datePicker.datePickerMode = UIDatePickerModeTime;
    }
    
    if (self.dateStyle == SLDatePickerYM) {
        [self.custDatePickView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self.mas_bottom).offset(-kSafeAreaBottom);
            make.height.equalTo(@(216));
        }];
        self.custDatePickView.maximumDate = self.datePicker.maximumDate;
        self.custDatePickView.minimumDate = self.datePicker.minimumDate;
        self.custDatePickView.defaultDate = self.datePicker.date;
        self.custDatePickView.hidden = NO;
    }else {
        if (_custDatePickView) {
            [_custDatePickView removeFromSuperview];
            _custDatePickView = nil;
        }
    }
}

- (NSDate *)timeFromFormatter:(NSString *)fomatter timeString:(NSString *)string {
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    dateformatter.dateFormat = fomatter ?: @"yyyy-MM-dd";;
    return [dateformatter dateFromString:string];
}


- (UIView *)toolView
{
    if (!_toolView) {
        _toolView = [[UIView alloc] initWithFrame:CGRectZero];
        _toolView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_toolView];
    }
    return _toolView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [self.toolView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.toolView addSubview:_cancelBtn];
    }
    return _cancelBtn;
}

- (UIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_sureBtn setTitle:@"保存" forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.toolView addSubview:_sureBtn];
    }
    return _sureBtn;
}

- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.datePickerMode = UIDatePickerModeDate;
#ifdef __IPHONE_13_4
        if (@available(iOS 13.4, *)) {
            _datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
        }
#endif
        _datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        _datePicker.backgroundColor = [UIColor whiteColor];
        [self addSubview:_datePicker];
    }
    return _datePicker;
}

- (SLCustDatePickView *)custDatePickView
{
    if (!_custDatePickView) {
        _custDatePickView = [[SLCustDatePickView alloc] initWithFrame:CGRectZero];
        _custDatePickView.hidden = YES;
        [self addSubview:_custDatePickView];
    }
    return _custDatePickView;
}

@end


@implementation SLDatePickerDO

+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
    return @{@"callbackString" : @"callback", @"maxDateString" : @"max", @"minDateString" : @"min", @"strText" : @"text"};
}

@end



@interface SLCustDatePickView()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, assign) NSInteger yearCount;
@property (nonatomic, assign) NSInteger monthCount;
@property (nonatomic, assign) NSInteger thisYear;
@property (nonatomic, assign) NSInteger thisMonth;
@property (nonatomic, assign) NSInteger thisDay;
@property (nonatomic, assign) NSInteger maximumYear;
@property (nonatomic, assign) NSInteger minimumYear;
@property (nonatomic, assign) NSInteger maximumMonth;
@property (nonatomic, assign) NSInteger minimumMonth;
@property (nonatomic, getter=isHideMonth) BOOL hideMonth;

@property (strong, nonatomic) UIPickerView *pickerView;

@end

@implementation SLCustDatePickView

@synthesize yearCount = _yearCount;

static NSInteger maxCount = 1000;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _showToday = NO;
        _monthCount = 12;
        [self.pickerView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}

- (void)refreshData {
    
    if (self.showToday && self.selectedYear == self.thisYear && self.selectedYear == self.thisYear) {
        self.hideMonth = YES;
    } else {
        self.hideMonth = NO;
    }
    
    [self.pickerView reloadAllComponents];
    [self setDefaultYear:_defaultYear];
    [self setDefaultMonth:_defaultMonth];
}

#pragma mark - Delegate Collectioin
#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return maxCount;
}

#pragma mark - UIPickerViewDelegate

- (nullable NSString *)pickerView:(UIPickerView *)pickerView
                      titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        NSInteger index = row % self.yearCount;
        NSString *text = [NSString stringWithFormat:@"%ld年", self.minimumYear+index];
        if (self.isShowToday &&
            text.integerValue == self.thisYear &&
            self.selectedYear == self.thisYear &&
            self.selectedMonth == self.thisMonth) {
            text = @"至今";
        }
        return text;
    } else {
        NSInteger index = row % self.monthCount+1;
        if (self.isHideMonth &&
            index == self.thisMonth &&
            self.selectedMonth == self.thisMonth &&
            self.selectedYear == self.thisYear) {
            return @"--";
        }
        return [NSString stringWithFormat:@"%02ld月", index];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.selectedYear = row%self.yearCount+self.minimumYear;
        if (row<maxCount/4 || row > maxCount/4*3) {
            [self setDefaultYear:self.selectedYear];
        }
    } else {
        self.selectedMonth = row%self.monthCount+1;
        if (row<maxCount/4 || row > maxCount/4*3) {
            [self setDefaultMonth:self.selectedMonth];
        }
    }
    
    if (self.selectedYear == self.maximumYear &&
        self.selectedMonth > self.maximumMonth) {
        self.defaultMonth = self.maximumMonth;
    }
    
    if (self.selectedYear == self.minimumYear &&
        self.selectedMonth < self.minimumMonth) {
        self.defaultMonth = self.minimumMonth;
    }
    
    if (self.isShowToday) {
        if ((self.selectedYear != self.thisYear &&
             self.selectedMonth == self.thisMonth) ||
            (self.selectedYear == self.thisYear &&
             self.selectedMonth != self.thisMonth)) {
                self.hideMonth = NO;
                [self.pickerView reloadAllComponents];
            }
        
        if ( self.selectedYear == self.thisYear &&
            self.selectedMonth == self.thisMonth) {
            self.hideMonth = YES;
            [self.pickerView reloadAllComponents];
        }
    }
}


#pragma mark - Custom Accessors
#pragma mark -

- (void)setDefaultYear:(NSInteger)defaultYear {
    if (defaultYear> self.maximumYear) {
        _defaultYear = self.maximumYear;
    } else if (defaultYear < self.minimumYear) {
        _defaultYear = self.minimumYear;
    } else {
        _defaultYear = defaultYear;
    }
    
    NSInteger selctRow = (maxCount/2)/self.yearCount*self.yearCount+ self.defaultYear- self.minimumYear;
    self.selectedYear = defaultYear;
    [self.pickerView reloadComponent:0];
    [self.pickerView selectRow:selctRow inComponent:0 animated:NO];
}

- (void)setDefaultMonth:(NSInteger)defaultMonth {
    if (defaultMonth> 12) {
        _defaultMonth = 12;
    } else if (defaultMonth < 1) {
        _defaultYear = 1;
    } else {
        _defaultMonth = defaultMonth;
    }
    
    _defaultMonth = defaultMonth;
    NSInteger selectRow = (maxCount/2)/self.monthCount*self.monthCount+ self.defaultMonth-1;
    self.selectedMonth = defaultMonth;
    [self.pickerView reloadComponent:1];
    [self.pickerView selectRow:selectRow inComponent:1 animated:NO];
}

- (void)setShowToday:(BOOL)showToday {
    _showToday = showToday;
}

- (void)setMinimumYear:(NSInteger)minimumYear {
    _minimumYear = minimumYear;
    self.yearCount = _maximumYear - _minimumYear+1;
}

- (void)setMaximumYear:(NSInteger)maximumYear {
    _maximumYear = maximumYear;
    self.yearCount = _maximumYear - _minimumYear+1;
}


- (void)setYearCount:(NSInteger)yearCount {
    _yearCount = yearCount;
}

- (NSInteger)yearCount {
    return _yearCount;
}

- (void)setMaximumDate:(NSDate *)maximumDate {
    
    if (maximumDate == nil) {
        maximumDate = [self.dateFormatter dateFromString:@"2100.12"];
    }
    _maximumDate = [maximumDate copy];
    
    kITLocalDate(_maximumDate);
    
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:_maximumDate];
    self.maximumYear = [components year];
    self.maximumMonth = [components month];
}

- (void)setMinimumDate:(NSDate *)minimumDate {
    
    if (minimumDate == nil) {
        minimumDate = [self.dateFormatter dateFromString:@"1900.01"];
    }
    
    _minimumDate = [minimumDate copy];
    
    kITLocalDate(_minimumDate);
    
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:_minimumDate];
    self.minimumYear = [components year];
    self.minimumMonth = [components month];
}

- (void)setDefaultDate:(NSDate *)defaultDate {
    
    if (defaultDate == nil) {
        defaultDate = [NSDate date];
    }
    
    _defaultDate = [defaultDate copy];
    
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:_defaultDate];
    NSInteger year = [components year];
    NSInteger month = [components month];
    [self setDefaultYear:year];
    [self setDefaultMonth:month];
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.dateFormat = @"yyyy.MM";
    }
    return _dateFormatter;
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:self.bounds];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        [self addSubview:self.pickerView];
    }
    return _pickerView;
}

@end
