//
//  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"
#import "homeNothingCell.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

- (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 setImage:[UIImage imageNamed:@"分类下拉"] forState:0];

    [view addSubview:classBtn];
    CGFloat widddd = [[WYToolClass sharedInstance] widthOfString:minstr([classDic valueForKey:@"name"]) andFont:[UIFont boldSystemFontOfSize:16] andHeight:40];
    [classBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(10);
        make.top.equalTo(view).offset(24+statusbarHeight);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(widddd+20);
    }];
    [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 *carBtn = [UIButton buttonWithType:0];
    carBtn.frame = CGRectMake(_window_width-50, 24+ statusbarHeight, 40, 40);
    [carBtn setImage:[UIImage imageNamed:@"购物车"] forState:0];
    
    [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;
    }
    UIButton *searchBtn = [UIButton buttonWithType:0];
    searchBtn.frame = CGRectMake(_window_width-90, 24+ statusbarHeight, 40, 40);
    [searchBtn setImage:[UIImage imageNamed:@"left_search"] forState:0];
    [searchBtn setTitle:@"  搜索课程，老师" forState:0];
    [searchBtn setTitleColor:RGB_COLOR(@"#C7C7C7", 1) forState:0];
    [searchBtn setBackgroundColor:RGB_COLOR(@"#000000", 0.05)];
    [searchBtn setCornerRadius:15];
    searchBtn.titleLabel.font = SYS_Font(14);
    searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(carBtn);
        make.height.mas_equalTo(30);
        make.right.equalTo(carBtn.mas_left).offset(-20);
        make.left.equalTo(classBtn.mas_right).offset(20);
    }];
}

- (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:1];
    homeTableV.delegate = self;
    homeTableV.dataSource = self;
    homeTableV.separatorStyle = 0;
    homeTableV.showsVerticalScrollIndicator = NO;
    [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, 320)];
    tableHeaderView.backgroundColor = [UIColor whiteColor];
    homeTableV.tableHeaderView = tableHeaderView;

    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(10, 5, _window_width-20, 120) delegate:self placeholderImage:[UIImage new]];
    _cycleScrollView.layer.cornerRadius = 7.5;
    _cycleScrollView.layer.masksToBounds = YES;
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    [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, 80)];
    [tableHeaderView addSubview:_teacherView];
    NSArray *array = @[@"名师名课",@"作业中心"];
    for (int i = 0 ; i < array.count; i ++) {
        UIImageView *backimgV = [[UIImageView alloc]initWithFrame:CGRectMake(10+i*(_window_width/2-5), 10, _window_width/2-15, 60)];
        backimgV.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@_back",array[i]]];
        backimgV.contentMode = UIViewContentModeScaleToFill;
        backimgV.layer.masksToBounds = YES;
        backimgV.layer.cornerRadius = 8;
      //  backimgV.clipsToBounds = YES;
//        [backimgV setBorderColor:[UIColor redColor]];
//        [backimgV setBorderWidth:1];
        [_teacherView addSubview:backimgV];
//        [[WYToolClass sharedInstance] addGradientWithFromColor:RGB_COLOR(@"#49F7BC", 1) andEndColor:RGB_COLOR(@"#14D087", 1) andView:backimgV];

//        [backimgV mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.width.height.equalTo(btn);
//        }];

        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(10+i*(_window_width/2-5), 10, _window_width/2-15, 60);
        [_teacherView addSubview:btn];
        UILabel *label = [[UILabel alloc]init];
        label.font = SYS_Font(14);
        label.textColor = [UIColor whiteColor];
        label.text = array[i];
        [btn addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(btn).offset(20);
            make.centerY.equalTo(btn);
        }];
        
        UIImageView *imgV = [[UIImageView alloc]init];
        imgV.image = [UIImage imageNamed:array[i]];
        imgV.contentMode = UIViewContentModeScaleAspectFit;
        [btn addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(btn).offset(-15);
            make.centerY.equalTo(btn);
            make.width.height.mas_equalTo(35);
        }];
    }
}
- (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.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_height).multipliedBy(0.42);
            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;
    [_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];
        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 == 0 ? 1 : packs.count;
    }else if (section == 1) {
        return course.count == 0 ? 1 : course.count;
    }else if (section == 2){
        return live.count == 0 ? 1 : live.count;
    }else{
        return list.count == 0 ? 1 : 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;
    }

    homeNothingCell *moCell = [tableView dequeueReusableCellWithIdentifier:@"homeNothingCELL"];
    if (!moCell) {
        moCell = [[[NSBundle mainBundle] loadNibNamed:@"homeNothingCell" owner:nil options:nil] lastObject];
    }

    if (indexPath.section == 0) {
        if (packs.count == 0) {
            return moCell;;
        }
        setMealModel *model = [[setMealModel alloc]initWithDic:packs[indexPath.row]];
        cell.smModel = model;
    }else if (indexPath.section == 1) {
        if (course.count == 0) {
            return moCell;;
        }
        courseModel *model = [[courseModel alloc]initWithDic:course[indexPath.row]];
        cell.model = model;
    }else if (indexPath.section == 2) {
        if (live.count == 0) {
            return moCell;;
        }
        courseModel *model = [[courseModel alloc]initWithDic:live[indexPath.row]];
        cell.model = model;
    }else{
        if (list.count == 0) {
            return moCell;;
        }
        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;
    [view addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(label);
        make.right.equalTo(view).offset(-15);
        make.height.mas_equalTo(35);
    }];
    return view;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

//是否可以旋转
- (BOOL)shouldAutorotate
{
    return false;
}

@end
