//
//  FinishTimeView.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/11/2.
//  Copyright © 2015年 Xummer. All rights reserved.
//

#import "FinishTimeView.h"
// 起始年数
#define kStartYear 1980
// 总年数
#define kYearCount 200
#define  DateViewHeight 246

@interface FinishTimeView ()
{
    UIView *_bgView;

}
// 定义数据属性
// 1. 年数组
@property (strong, nonatomic) NSArray *yearList;
// 2. 月数组
@property (strong, nonatomic) NSMutableArray *monthList;
// 3. 日数组
@property (strong, nonatomic) NSMutableArray *dayList;
// 时
@property (strong,nonatomic) NSArray *hourList;
// 分
@property (strong,nonatomic) NSArray *minuteList;
// 4. 选中的年数
@property (assign, nonatomic) NSInteger selectedYear;
// 5. 选中的月数
@property (assign, nonatomic) NSInteger selectedMonth;
@property (assign,nonatomic) NSInteger currentYear;
@property (assign,nonatomic) NSInteger currentMonth;
@property (assign,nonatomic) NSInteger currentDay;
@property (assign,nonatomic) NSInteger currentHour;
@property (assign,nonatomic) NSInteger currentMinute;

@property (nonatomic,strong) UIPickerView *pickerView;
@property (nonatomic,strong) NSString *dateStr;
@property (nonatomic,strong) NSString *typeStr;

@end

@implementation FinishTimeView

- (instancetype)initWithFrame:(CGRect)frame withDate:(NSString *)dateStr
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dateStr = dateStr;
        self.typeStr = @"all";
        [self buildLayout];
    }
    self.backgroundColor = [UIColor whiteColor];
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame withDate:(NSString *)dateStr type:(NSString *)type{
    self = [super initWithFrame:frame];
    if (self) {
        self.dateStr = dateStr;
        self.typeStr = type;
        [self buildLayout];
    }
    self.backgroundColor = [UIColor whiteColor];
    return self;
}

- (void)buildLayout
{
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - DateViewHeight, ScreenSize.width, DateViewHeight)];
    _bgView.backgroundColor        = RGBA(239, 239, 239 ,1);
    [self addSubview:_bgView];
    
    UIButton *okBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(ScreenSize.width - 62, 0, 62, 28) target:self sel:@selector(okClick) tag:0 image:nil title:@"确定" titleColor:[UIColor blackColor] isCorner:NO corner:0 bgColor:RGBA(239, 239, 239 ,1)];
    [_bgView addSubview:okBtn];
    
    UIButton *cancelBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(0, 0, 62, 28) target:self sel:@selector(cancelClick) tag:0 image:nil title:@"取消" titleColor:[UIColor blackColor] isCorner:NO corner:0 bgColor:RGBA(239, 239, 239 ,1)];
    [_bgView addSubview:cancelBtn];

    UIPickerView *pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30,ScreenSize.width, DateViewHeight - 30)];
    pickerView.backgroundColor = [UIColor whiteColor];
    // 指定数据源
    [pickerView setDataSource:self];
    // 指定代理
    [pickerView setDelegate:self];
    // PickerView默认是没有选中标示的
    [pickerView setShowsSelectionIndicator:YES];
    self.pickerView = pickerView;
    [_bgView addSubview:pickerView];
    
    CLog(@"====%@",self.dateStr);

    if ([self.typeStr isEqualToString:@"all"]) {
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        self.currentDay = [[self.dateStr substringWithRange:NSMakeRange(8,2)] intValue];
        self.currentHour = [[self.dateStr substringWithRange:NSMakeRange(11,2)] intValue];
        self.currentMinute = [[self.dateStr substringWithRange:NSMakeRange(14,2)] intValue];
        // 3. 初始化数据
        // 1) 年数据
        NSMutableArray *yearArray = [NSMutableArray arrayWithCapacity:kYearCount];
        for (int i = 0; i < kYearCount; i++) {
            NSString *str = [NSString stringWithFormat:@"%d年", i + kStartYear];
            
            [yearArray addObject:str];
        }
        self.yearList = yearArray;
        
        // 2) 月数据
        NSMutableArray *monthArray = [NSMutableArray arrayWithCapacity:12];
        for (int i = 1; i <= 12; i++) {
            NSString *str = [NSString stringWithFormat:@"%d月", i];
            
            [monthArray addObject:str];
        }
        self.monthList = monthArray;
        
        // 时
        NSMutableArray *hourArray = [NSMutableArray arrayWithCapacity:24];
        for (int i = 0; i < 24; i++) {
            NSString *str = [NSString stringWithFormat:@"%d时",i];
            [hourArray addObject:str];
        }
        self.hourList = hourArray;
        
        // 分
        NSMutableArray *minuteArray = [NSMutableArray arrayWithCapacity:60];
        for (int i = 0; i < 60; i++) {
            NSString *str = [NSString stringWithFormat:@"%d分",i];
            [minuteArray addObject:str];
        }
        self.minuteList = minuteArray;
        
        // 初始化选中年、月
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        self.currentDay = [[self.dateStr substringWithRange:NSMakeRange(8,2)] intValue];
        self.currentHour = [[self.dateStr substringWithRange:NSMakeRange(11,2)] intValue];
        
        [pickerView selectRow:(self.currentYear - kStartYear) inComponent:0 animated:YES];
        [pickerView selectRow:(self.currentMonth - 1) inComponent:1 animated:YES];
        [pickerView selectRow:(self.currentDay - 1) inComponent:2 animated:YES];
        [pickerView selectRow:self.currentHour inComponent:3 animated:YES];
        [pickerView selectRow:(self.currentMinute) inComponent:4 animated:YES];
        
        [self pickerView:pickerView didSelectRow:self.currentYear - kStartYear inComponent:0];
        [self pickerView:pickerView didSelectRow:(self.currentMonth - 1) inComponent:1];
        [self pickerView:pickerView didSelectRow:(self.currentDay - 1) inComponent:2];
        [self pickerView:pickerView didSelectRow:(self.currentHour - 1) inComponent:3];
        [self pickerView:pickerView didSelectRow:(self.currentMinute -1) inComponent:4];

    }else if([self.typeStr isEqualToString:@"month"]){
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        
        NSMutableArray *yearArray = [NSMutableArray arrayWithCapacity:kYearCount];
        for (int i = 0; i < kYearCount; i++) {
            NSString *str = [NSString stringWithFormat:@"%d年", i + kStartYear];
            
            [yearArray addObject:str];
        }
        self.yearList = yearArray;
        
        // 2) 月数据
        NSMutableArray *monthArray = [NSMutableArray arrayWithCapacity:12];
        for (int i = 1; i <= 12; i++) {
            NSString *str = [NSString stringWithFormat:@"%d月", i];
            
            [monthArray addObject:str];
        }
        self.monthList = monthArray;
        // 初始化选中年、月
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        
        
        [pickerView selectRow:(self.currentYear - kStartYear) inComponent:0 animated:YES];
        [pickerView selectRow:(self.currentMonth - 1) inComponent:1 animated:YES];
        
        [self pickerView:pickerView didSelectRow:self.currentYear - kStartYear inComponent:0];
        [self pickerView:pickerView didSelectRow:(self.currentMonth - 1) inComponent:1];
        
    }else if([self.typeStr isEqualToString:@"day"]){
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        self.currentDay = [[self.dateStr substringWithRange:NSMakeRange(8,2)] intValue];
        
        NSMutableArray *yearArray = [NSMutableArray arrayWithCapacity:kYearCount];
        for (int i = 0; i < kYearCount; i++) {
            NSString *str = [NSString stringWithFormat:@"%d年", i + kStartYear];
            
            [yearArray addObject:str];
        }
        self.yearList = yearArray;
        
        // 2) 月数据
        NSMutableArray *monthArray = [NSMutableArray arrayWithCapacity:12];
        for (int i = 1; i <= 12; i++) {
            NSString *str = [NSString stringWithFormat:@"%d月", i];
            
            [monthArray addObject:str];
        }
        self.monthList = monthArray;
        // 初始化选中年、月
        // 初始化选中年、月
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        self.currentDay = [[self.dateStr substringWithRange:NSMakeRange(8,2)] intValue];

        
        [pickerView selectRow:(self.currentYear - kStartYear) inComponent:0 animated:YES];
        [pickerView selectRow:(self.currentMonth - 1) inComponent:1 animated:YES];
        [pickerView selectRow:(self.currentDay - 1) inComponent:2 animated:YES];

        [self pickerView:pickerView didSelectRow:self.currentYear - kStartYear inComponent:0];
        [self pickerView:pickerView didSelectRow:(self.currentMonth - 1) inComponent:1];
        [self pickerView:pickerView didSelectRow:(self.currentDay - 1) inComponent:2];
    }else if ([self.typeStr isEqualToString:@"week"]){
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];

        
        NSMutableArray *yearArray = [NSMutableArray arrayWithCapacity:kYearCount];
        for (int i = 0; i < kYearCount; i++) {
            NSString *str = [NSString stringWithFormat:@"%d年", i + kStartYear];
            
            [yearArray addObject:str];
        }
        self.yearList = yearArray;
        
        self.currentYear = [[self.dateStr substringWithRange:NSMakeRange(0,4)] intValue];
        self.selectedYear = self.currentYear;
        self.currentMonth = [[self.dateStr substringWithRange:NSMakeRange(5,2)] intValue];
        
        
        [pickerView selectRow:(self.currentYear - kStartYear) inComponent:0 animated:YES];
        [pickerView selectRow:(self.currentMonth - 1) inComponent:1 animated:YES];
        
        [self pickerView:pickerView didSelectRow:self.currentYear - kStartYear inComponent:0];
        [self pickerView:pickerView didSelectRow:(self.currentMonth - 1) inComponent:1];

    }

    
}

#pragma mark - 私有方法
#pragma mark 判断闰年
- (BOOL)isLeapYear:(NSInteger)year
{
    // 如果年数能被4整除,同时不能被100整除
    // 能被400整除的是闰年
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

#pragma mark 创建日数组
// 此方法的返回值是void,是为了不改变dayList的指针
- (void)createDayListWithYear:(NSInteger)year month:(NSInteger)month
{
    // 日数组是懒加载,需要时在创建
    if (self.dayList == nil) {
        // 在开发时尽可能要去控制NSMutableArray的容量
        self.dayList = [NSMutableArray arrayWithCapacity:31];
    } else {
        [self.dayList removeAllObjects];
    }
    
    // 初始化日数组
    /**
     年:是否是闰年
     月:大月,小月
     */
    NSInteger days = 31;
    if ([self isLeapYear:year] && month == 2) {
        // 闰年的2月
        days = 29;
    } else if (2 == month) {
        // 非闰年的2月
        days = 28;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        // 小月
        days = 30;
    }
    
    for (int i = 1; i <= days; i++) {
        NSString *str = [NSString stringWithFormat:@"%d日", i];
        
        [self.dayList addObject:str];
    }
}
- (void)getWeekByYear:(NSInteger)year{
    // 日数组是懒加载,需要时在创建
    if (self.monthList == nil) {
        // 在开发时尽可能要去控制NSMutableArray的容量
        self.monthList = [NSMutableArray arrayWithCapacity:53];
    } else {
        [self.monthList removeAllObjects];
    }
    
    NSInteger weeks = [IBTCommon getWeeks:year];
    for (int i = 1; i <= weeks; i++) {
        NSString *str = [NSString stringWithFormat:@"第%d周", i];
        [self.monthList addObject:str];
    }
}


#pragma mark - PickerView的数据源方法
#pragma mark 指定列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if([self.typeStr isEqualToString:@"all"]){
        return 5;

    }else if([self.typeStr isEqualToString:SaleEnMonth]|| [self.typeStr isEqualToString:SaleEnWeek]){
        return 2;
    }else{
        return 3;
    }
}

#pragma mark 指定行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([self.typeStr isEqualToString:@"all"]) {
        if (0 == component) {
            // 年
            return self.yearList.count;
        } else if (1 == component) {
            // 月
            return self.monthList.count;
        } else if (2 == component) {
            // 日
            // 需要创建日数组-懒加载
            [self createDayListWithYear:self.selectedYear month:self.selectedMonth];
            
            return self.dayList.count;
        }
        else if (3 == component) {
            // 时
            return self.hourList.count;
        } else // 分
        {
            return self.minuteList.count;
        }

    }else if([self.typeStr isEqualToString:SaleEnMonth]){
        if (component == 0) {
            // 年
            return self.yearList.count;
        } else {
            // 月
            return self.monthList.count;
        }
    }else if([self.typeStr isEqualToString:SaleEnDay]){
        if (0 == component) {
            // 年
            return self.yearList.count;
        } else if (1 == component) {
            // 月
            return self.monthList.count;
        } else{
            // 日
            // 需要创建日数组-懒加载
            [self createDayListWithYear:self.selectedYear month:self.selectedMonth];
            
            return self.dayList.count;
        }
    }else{
        if (0 == component) {
            // 年
            return self.yearList.count;
        } else{
            // 月
            [self getWeekByYear:self.selectedYear];
            return self.monthList.count;
        }

    }
}

#pragma mark - UIPickerViewDelegate
#pragma mark 指定component列row行的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([self.typeStr isEqualToString:@"all"]) {
        if (0 == component) {
            return self.yearList[row];
        } else if (1 == component) {
            return self.monthList[row];
        } else if (2 == component){
            return self.dayList[row];
        }
        else if (3 == component) {
            return self.hourList[row];
        } else {
            return self.minuteList[row];
        }
    }else if([self.typeStr isEqualToString:SaleEnMonth]|| [self.typeStr isEqualToString:SaleEnWeek] ){
        if (0 == component) {
            return self.yearList[row];
        }else{
            return self.monthList[row];
        }
    }else{
        if (0 == component) {
            return self.yearList[row];
        } else if (1 == component) {
            return self.monthList[row];
        } else{
            return self.dayList[row];
        }
    }
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 0) {
        return 80;
    }
    return 50;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([self.typeStr isEqualToString:@"all"] || [self.typeStr isEqualToString:@"day"]) {
        // 当用户在月份列选择数值时,需要刷新日期的数组
        self.selectedYear = [pickerView selectedRowInComponent:0] + kStartYear;
        self.selectedMonth = [pickerView selectedRowInComponent:1] + 1;
        NSInteger resetRow = [pickerView selectedRowInComponent:2];
        if (component == 1) {
            [pickerView reloadComponent:2];
            [self pickerView:pickerView didSelectRow:resetRow inComponent:2];
        } else if (component == 0 && self.selectedMonth == 2) {
            // 如果用户是在年列选择的数值,同时月份中的当前数值是2月,需要刷新数据
            [pickerView reloadComponent:2];
            [self pickerView:pickerView didSelectRow:resetRow inComponent:2];
        }
    }else if ([self.typeStr isEqualToString:SaleEnWeek]) {
        // 当用户在月份列选择数值时,需要刷新日期的数组
        self.selectedYear = [pickerView selectedRowInComponent:0] + kStartYear;
        NSInteger resetRow = [pickerView selectedRowInComponent:1];
        if (component == 0) {
            [pickerView reloadComponent:1];
            [self pickerView:pickerView didSelectRow:resetRow inComponent:1];
        }
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 330, 30)];
    myView.textAlignment = NSTextAlignmentCenter;
    myView.font = [UIFont systemFontOfSize:16];
    switch (component) {
        case 0:
            myView.text = self.yearList[row];
            break;
        case 1:
            myView.text = self.monthList[row];
            break;
        case 2:
            myView.text = self.dayList[row];
            break;
        case 3:
            myView.text = self.hourList[row];
            break;
        case 4:
            myView.text = self.minuteList[row];
            break;
        default:
            break;
    }
    return myView;
}

- (NSString *)getDate
{
    NSInteger yearRow = [_pickerView selectedRowInComponent:0];
    NSString *year = [self.yearList[yearRow] stringByReplacingOccurrencesOfString:@"年" withString:@""];
    NSInteger monthRow = [_pickerView selectedRowInComponent:1];
    NSString *month = [self.monthList[monthRow] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSInteger dayRow = [_pickerView selectedRowInComponent:2];
    NSString *day = [self.dayList[dayRow] stringByReplacingOccurrencesOfString:@"日" withString:@""];
    NSInteger hourRow = [_pickerView selectedRowInComponent:3];
    NSString *hour = [self.hourList[hourRow] stringByReplacingOccurrencesOfString:@"时" withString:@""];
    NSInteger minuteRow = [_pickerView selectedRowInComponent:4];
    NSString *minute = [self.minuteList[minuteRow] stringByReplacingOccurrencesOfString:@"分" withString:@""];
    NSArray *array1 = [NSArray arrayWithObjects:year,month,day, nil];
    NSArray *array2 = [NSArray arrayWithObjects:hour,minute, nil];
    NSString *date1 = [array1 componentsJoinedByString:@"-"];
    NSString *date2 = [array2 componentsJoinedByString:@":"];
    NSString *date = [NSString stringWithFormat:@"%@ %@:00",date1,date2];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    return [formatter stringFromDate:[formatter dateFromString:date]];
    
}

- (void)okClick{
    if ([self.typeStr isEqualToString:@"all"]) {
        NSString *dateStr = [self getDate];
        [self.delegate okTimeView:dateStr withType:@"all"];
    }else if([self.typeStr isEqualToString:SaleEnMonth]){
        NSString *dateStr = [self getDateByMonth];
        [self.delegate okTimeView:dateStr withType:SaleEnMonth];
    }else if([self.typeStr isEqualToString:SaleEnDay]){
        NSString *dateStr = [self getDateByDay];
        [self.delegate okTimeView:dateStr withType:SaleEnDay];
    }else if([self.typeStr isEqualToString:SaleEnWeek]){
        NSString *dateStr = [self getDateByWeek];
        [self.delegate okTimeView:dateStr withType:SaleEnWeek];
    }
}

- (NSString *)getDateByMonth{
    NSInteger yearRow = [_pickerView selectedRowInComponent:0];
    NSString *year = [self.yearList[yearRow] stringByReplacingOccurrencesOfString:@"年" withString:@""];
    NSInteger monthRow = [_pickerView selectedRowInComponent:1];
    NSString *month = [self.monthList[monthRow] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    
    NSArray *array1 = [NSArray arrayWithObjects:year,month, nil];
    NSString *date1 = [array1 componentsJoinedByString:@"-"];
    NSString *date = [NSString stringWithFormat:@"%@",date1];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM";
    
    return [formatter stringFromDate:[formatter dateFromString:date]];
}

- (NSString *)getDateByDay{
    NSInteger yearRow = [_pickerView selectedRowInComponent:0];
    NSString *year = [self.yearList[yearRow] stringByReplacingOccurrencesOfString:@"年" withString:@""];
    NSInteger monthRow = [_pickerView selectedRowInComponent:1];
    NSString *month = [self.monthList[monthRow] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSInteger dayRow = [_pickerView selectedRowInComponent:2];
    NSString *day = [self.dayList[dayRow] stringByReplacingOccurrencesOfString:@"日" withString:@""];
    
    NSArray *array1 = [NSArray arrayWithObjects:year,month,day, nil];
    NSString *date1 = [array1 componentsJoinedByString:@"-"];
    NSString *date = [NSString stringWithFormat:@"%@",date1];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd";
    
    return [formatter stringFromDate:[formatter dateFromString:date]];
}

- (NSString *)getDateByWeek{
    NSInteger yearRow = [_pickerView selectedRowInComponent:0];
    NSString *year = [self.yearList[yearRow] stringByReplacingOccurrencesOfString:@"年" withString:@""];
    NSInteger monthRow = [_pickerView selectedRowInComponent:1];
    
    NSString *month = [[self.monthList[monthRow] stringByReplacingOccurrencesOfString:@"第" withString:@""] stringByReplacingOccurrencesOfString:@"周" withString:@""];
    
    NSArray *array1 = [NSArray arrayWithObjects:year,month.length == 1 ?[NSString stringWithFormat:@"0%@",month]:month, nil];
    NSString *date1 = [array1 componentsJoinedByString:@"-"];
   
    
    return date1;
}
- (void)cancelClick{
    [self.delegate cancelTimeView];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.delegate cancelTimeView];
}
@end