//
//  HomeViewController.m
//  YBEducation
//
//  Created by IOS1 on 2020/2/21.
//  Copyright © 2020 IOS1. All rights reserved.
//

#import "HomeViewController.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "homeCell.h"
#import "homeTeacherView.h"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>{
    UITableView *homeTableV;
    NSArray *dataArray;
    NSArray *course;//好课推荐
    NSArray *packs;//精选套餐
    NSArray *live;//直播课堂
    NSArray *list;//精选内容
    UIButton *classBtn;
    UILabel *numForCarL;
}
@property (nonatomic,strong) SDCycleScrollView *cycleScrollView;//轮播图
@property (nonatomic,strong) NSArray *sliderArray;//轮播图数组
@property (nonatomic,strong) UIScrollView *subjectView;
@property (nonatomic,strong) NSArray *subjectArray;
@property (nonatomic,strong) UIView *teacherView;
@property (nonatomic,strong) NSArray *teacherArray;

@end

@implementation HomeViewController
#pragma mark -- 前往购物车
- (void)carNumChange:(NSNotification *)not{
    NSString *numStr = [not object];
    if (numStr && [numStr intValue] > 0) {
        numForCarL.hidden = NO;
        numForCarL.text = numStr;
    }else{
        numForCarL.hidden = YES;
    }

}

- (void)doCar{
    if (![Config getOwnID] || [[Config getOwnID] intValue] == 0) {
        [[WYToolClass sharedInstance] showLoginView];
        return;
    }
}
#pragma mark -- 选择分类
- (void)doAllClassSelect:(UIButton *)sender{

}


-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
}

- (void)doSearch{
}
- (void)creatSearchView{
    UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 64 + statusbarHeight)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    NSDictionary *classDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectClassIteam"];

    classBtn = [UIButton buttonWithType:0];
    classBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [classBtn setTitleColor:color32 forState:0];
    [classBtn setTitle:[NSString stringWithFormat:@"%@ ",minstr([classDic valueForKey:@"name"])] forState:0];
    [classBtn addTarget:self action:@selector(doAllClassSelect:) forControlEvents:UIControlEventTouchUpInside];
    [classBtn setImage:[UIImage imageNamed:@"分类下拉"] forState:0];

    [view addSubview:classBtn];
    [classBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(10);
        make.top.equalTo(view).offset(24+statusbarHeight);
        make.height.mas_equalTo(40);
    }];
    [classBtn layoutIfNeeded];
    [classBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,-classBtn.imageView.size.width, 0, classBtn.imageView.size.width)];
    [classBtn setImageEdgeInsets:UIEdgeInsetsMake(0, classBtn.titleLabel.bounds.size.width, 0, -classBtn.titleLabel.bounds.size.width)];

    UIButton *searchBtn = [UIButton buttonWithType:0];
    searchBtn.frame = CGRectMake(_window_width-90, 24+ statusbarHeight, 40, 40);
    [searchBtn setImage:[UIImage imageNamed:@"搜索"] forState:0];
    [searchBtn addTarget:self action:@selector(doSearch) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:searchBtn];
    UIButton *carBtn = [UIButton buttonWithType:0];
    carBtn.frame = CGRectMake(_window_width-50, 24+ statusbarHeight, 40, 40);
    [carBtn setImage:[UIImage imageNamed:@"购物车"] forState:0];
    [carBtn addTarget:self action:@selector(doCar) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:carBtn];
    numForCarL = [[UILabel alloc]init];
    numForCarL.font = SYS_Font(7);
    numForCarL.textColor = [UIColor whiteColor];
    numForCarL.backgroundColor = [UIColor redColor];
    numForCarL.textAlignment = NSTextAlignmentCenter;
    numForCarL.layer.cornerRadius = 5;
    numForCarL.layer.masksToBounds = YES;
    numForCarL.hidden = YES;
    [carBtn addSubview:numForCarL];
    [numForCarL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(carBtn.mas_centerY);
        make.right.equalTo(carBtn).offset(-3);
        make.height.mas_equalTo(10);
        make.width.mas_greaterThanOrEqualTo(10);
    }];
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"unReadNum"];
    if (str && [str intValue] > 0) {
        numForCarL.text = str;
        numForCarL.hidden = NO;
    }

//    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
//    imgV.image = [UIImage imageNamed:@"left_search.png"];
//    [btn addSubview:imgV];
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imgV.right+5, 0, _window_width-80, 30)];
//    label.text = @"搜索课程，老师";
//    label.textColor = RGB_COLOR(@"#c7c7c7", 1);
//    label.font = SYS_Font(15);
//    [btn addSubview:label];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    [self creatSearchView];
    homeTableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height- (64+statusbarHeight+48+ShowDiff)) style:0];
    homeTableV.delegate = self;
    homeTableV.dataSource = self;
    homeTableV.separatorStyle = 0;
    [self.view addSubview:homeTableV];
    homeTableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requeestData];
    }];
    [self creatTableHedaerView];
    [self requeestData];

}
- (void)creatTableHedaerView{
    UIView *tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 370)];
    tableHeaderView.backgroundColor = [UIColor whiteColor];
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(10, 5, _window_width-20, 120) delegate:self placeholderImage:[UIImage new]];
    _cycleScrollView.layer.cornerRadius = 7.5;
    _cycleScrollView.layer.masksToBounds = YES;
    [tableHeaderView addSubview:_cycleScrollView];
    
    _subjectView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _cycleScrollView.bottom + 5, _window_width, 110)];
    _subjectView.bounces = NO;
    _subjectView.pagingEnabled = YES;
    [tableHeaderView addSubview:_subjectView];
    
    _teacherView = [[UIView alloc]initWithFrame:CGRectMake(0, _subjectView.bottom, _window_width, 130)];
    [tableHeaderView addSubview:_teacherView];
    homeTableV.tableHeaderView = tableHeaderView;
    
    
}
- (void)requeestData{
    NSDictionary *classDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectClassIteam"];

    [WYToolClass postNetworkWithUrl:@"Home.GetIndex" andParameter:@{@"gradeid":minstr([classDic valueForKey:@"id"])} success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
        [homeTableV.mj_header endRefreshing];
        [MBProgressHUD hideHUD];
        if (code == 0) {
            NSDictionary *subDic = [info firstObject];
            
            NSString *cartnums = minstr([subDic valueForKey:@"cartnums"]);
            if (cartnums && [cartnums intValue] > 0) {
                numForCarL.hidden = NO;
                numForCarL.text = cartnums;
            }else{
                numForCarL.hidden = YES;
            }
            _sliderArray = [subDic valueForKey:@"silide"];
            NSMutableArray *imageArray = [NSMutableArray array];
            for (NSDictionary *dic in _sliderArray) {
                [imageArray addObject:minstr([dic valueForKey:@"image"])];
            }
            _cycleScrollView.imageURLStringsGroup = imageArray;
            
            _subjectArray = [subDic valueForKey:@"courseclass"];
            _teacherArray = [subDic valueForKey:@"teacher"];

            [self creatAllSubject];
            [self creatAllTeacher];
            packs = [subDic valueForKey:@"packs"];
            course = [subDic valueForKey:@"course"];
            live = [subDic valueForKey:@"live"];
            list = [subDic valueForKey:@"list"];
            [homeTableV reloadData];
        }
    } fail:^{
        [MBProgressHUD hideHUD];
        [homeTableV.mj_header endRefreshing];

    }];

}
- (void)creatAllSubject{
    [_subjectView removeAllSubViews];
    CGFloat width = _window_width/5;
    for (int i = 0; i < _subjectArray.count; i ++) {
        NSDictionary *dic = _subjectArray[i];
        UIButton *btn = [UIButton buttonWithType:0];
        btn.tag = 1000 + i;
        [btn addTarget:self action:@selector(subjectClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(i*width, 0, width, 110);
        [_subjectView addSubview:btn];
        UIImageView *imgV = [[UIImageView alloc]init];//WithFrame:CGRectMake(15, 20.5, 45, 45)
        [imgV sd_setImageWithURL:[NSURL URLWithString:minstr([dic valueForKey:@"thumb"])]];
        [btn addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btn);
            make.top.equalTo(btn).offset(20.5);
            make.width.equalTo(btn.mas_width).multipliedBy(0.6);
            make.height.equalTo(imgV.mas_width);
        }];
        UILabel *label = [[UILabel alloc]init];//WithFrame:CGRectMake(0, imgV.bottom + 13, 75, 14)
        label.text = minstr([dic valueForKey:@"name"]);
        label.textColor = color32;
        if (IS_IPHONE_5) {
            label.font = SYS_Font(13);
        }else{
            label.font = SYS_Font(15);
        }
        label.textAlignment = NSTextAlignmentCenter;
        [btn addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btn);
            make.top.equalTo(imgV.mas_bottom).offset(13);
        }];

    }
    if (_subjectArray.count % 5 == 0) {
        _subjectView.contentSize = CGSizeMake(_window_width * _subjectArray.count/5, 0);
    }else{
        _subjectView.contentSize = CGSizeMake(_window_width * (_subjectArray.count/5 + 1), 0);
    }
}
- (void)creatAllTeacher{
    [_teacherView removeAllSubViews];
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textColor = color32;
    label.text = @"名师名课";
    [_teacherView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_teacherView).offset(15);
        make.top.equalTo(_teacherView).offset(15);
        make.height.mas_equalTo(35);
    }];
    UIButton *moreBtn = [UIButton buttonWithType:0];
    [moreBtn setImage:[UIImage imageNamed:@"home_more"] forState:0];
    [moreBtn setTitle:@"更多 " forState:0];
    [moreBtn setTitleColor:color96 forState:0];
    moreBtn.titleLabel.font = SYS_Font(11);
    moreBtn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
    [moreBtn addTarget:self action:@selector(doMoreTeacher) forControlEvents:UIControlEventTouchUpInside];
    [_teacherView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(label);
        make.right.equalTo(_teacherView).offset(-10);
        make.height.mas_equalTo(15);
    }];
    UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 50, _window_width, 80)];
    [_teacherView addSubview:scroll];
    for (int i = 0; i < _teacherArray.count; i ++) {
        homeTeacherView *view = [[NSBundle mainBundle] loadNibNamed:@"homeTeacherView" owner:nil options:nil].lastObject;;
        view.tag = 2000 + i;
        view.frame = CGRectMake(10+i*140, 0, 140, 70);
        [scroll addSubview:view];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(homeTearcherClick:)];
        [view addGestureRecognizer:tap];
//        teacherModel *model = [[teacherModel alloc]initWithDic:_teacherArray[i]];
//        view.model = model;
        if (i == _teacherArray.count - 1) {
            scroll.contentSize = CGSizeMake(20+_teacherArray.count*140, 0);
        }
    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return packs.count;
    }else if (section == 1) {
        return course.count;
    }else if (section == 2){
        return live.count;
    }else{
        return list.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    homeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCELL"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"homeCell" owner:nil options:nil] lastObject];
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.typeL.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = cell.typeL.bounds;
        maskLayer.path = maskPath.CGPath;
        cell.typeL.layer.mask = maskLayer;
    }
    if (indexPath.section == 0) {
//        setMealModel *model = [[setMealModel alloc]initWithDic:packs[indexPath.row]];
//        cell.smModel = model;
    }else if (indexPath.section == 1) {
        courseModel *model = [[courseModel alloc]initWithDic:course[indexPath.row]];
        cell.model = model;
    }else if (indexPath.section == 2) {
        courseModel *model = [[courseModel alloc]initWithDic:live[indexPath.row]];
        cell.model = model;
    }else{
        courseModel *model = [[courseModel alloc]initWithDic:list[indexPath.row]];
        cell.model = model;

    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 5)];
    view.backgroundColor = colorf0;
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 60)];
    view.backgroundColor = [UIColor whiteColor];

    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textColor = color32;
    if (section == 0) {
        label.text = @"精选套餐";
    }else if (section == 1) {
        label.text = @"好课推荐";
    }else if (section == 2){
        label.text = @"直播课堂";
    }else{
        label.text = @"精选内容";
    }
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(15);
        make.top.equalTo(view).offset(20);
        make.height.mas_equalTo(35);
    }];
    UIButton *moreBtn = [UIButton buttonWithType:0];
    moreBtn.tag = 8888+section;
    [moreBtn setImage:[UIImage imageNamed:@"home_more"] forState:0];
    [moreBtn setTitle:@"更多 " forState:0];
    [moreBtn setTitleColor:color96 forState:0];
    moreBtn.titleLabel.font = SYS_Font(11);
    moreBtn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
    [moreBtn addTarget:self action:@selector(doMoreCourse:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(label);
        make.right.equalTo(view).offset(-15);
        make.height.mas_equalTo(15);
    }];
    return view;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (![Config getOwnID] || [[Config getOwnID] intValue] == 0) {
        [[WYToolClass sharedInstance] showLoginView];
        return;
    }
}

#pragma mark -- 课程按钮点击
- (void)subjectClick:(UIButton *)sender{
}
#pragma mark -- 更多教师
- (void)doMoreTeacher{
}
#pragma mark -- 点击进入老师主页
- (void)homeTearcherClick:(UITapGestureRecognizer *)tap{
    if (![Config getOwnID] || [[Config getOwnID] intValue] == 0) {
        [[WYToolClass sharedInstance] showLoginView];
        return;
    }

}
#pragma mark -- 更多课程
- (void)doMoreCourse:(UIButton *)sender{
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
