ResourceViewController.swift 8.57 KB
//
//  ResourceViewController.swift
//  YouerLiveVideo
//
//  Created by 左丞 on 2017/5/15.
//  Copyright © 2017年 左丞. All rights reserved.
//

import UIKit

class ResourceViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating {
    @IBOutlet var tableView: UITableView!
    
    @IBOutlet var grayView: UIView!
    @IBOutlet var searchTableView: UITableView!
    @IBOutlet var searchTableHeight: NSLayoutConstraint!
    
    var searchController:UISearchController!
    var dataSetAry:[String]=["葛建军","张道峰","徐晓杰","左承","段合江"]
    var searchAry:[String]=[]
    var currentPage:Int=0 //当前页数,每次取十个数据
    var resourceData:[MicroCourseModel]=[]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configTheme()
        addSearchController()
        addRefresh()
        self.refreshLivesAction(tag: self.currentPage, completionHandler: { (success) in
            if success{
                self.tableView.reloadData()
            }
        })
    }
    func addSearchController(){
        self.definesPresentationContext=true
        searchController=UISearchController(searchResultsController: nil)
        searchController.delegate=self
        searchController.searchResultsUpdater=self
        searchController.searchBar.barTintColor=UIColor.groupTableViewBackground
        searchController.searchBar.placeholder="搜索"
        //设置UISearchController的显示属性,以下3个属性默认为YES
        //搜索时,背景变暗色
        self.searchController.dimsBackgroundDuringPresentation=false
        //搜索时,背景变模糊
        //        self.searchController.obscuresBackgroundDuringPresentation=false
        //点击搜索的时候,是否隐藏导航栏
        //        searchController.hidesNavigationBarDuringPresentation=true
        //位置
        searchController.searchBar.frame=CGRect(x: self.searchController.searchBar.frame.origin.x, y: self.searchController.searchBar.frame.origin.y, width: self.searchController.searchBar.frame.size.width, height: 44.0);
        //        self.view.addSubview(searchController.searchBar)
        searchTableView.tableHeaderView=searchController.searchBar
    }
    func addRefresh(){
        let header=MJRefreshNormalHeader(refreshingBlock: {
            //下拉刷新
            self.currentPage=0
            self.resourceData.removeAll()
            self.refreshLivesAction(tag: self.currentPage, completionHandler: { (success) in
                if success{
                    self.tableView.reloadData()
                }
                self.tableView.mj_header.endRefreshing()
            })
        })
        header?.lastUpdatedTimeLabel.isHidden=true
        tableView.mj_header=header
        tableView.mj_footer=MJRefreshBackNormalFooter(refreshingBlock: {
            //上拉加载更多
            self.refreshLivesAction(tag: self.currentPage, completionHandler: { (success) in
                if success{
                    self.tableView.reloadData()
                }
                self.tableView.mj_footer.endRefreshing()
            })
        })
    }
    // MARK: - 刷新数据接口
    func refreshLivesAction(tag:Int,completionHandler:@escaping (Bool) -> ()){
        let parameters:Dictionary<String,AnyObject>=["type":1 as AnyObject,"pageIndex":tag as AnyObject,"pageSize":1 as AnyObject]
        AppDelegate.instance().httpServer.getHotRescourse(parameters: parameters) { (str, error) in
            var success:Bool=true
            if error==nil {
                if JSON.fromString(jsonString: str)!["status"].intValue == 1{
                    httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                        if JSON.fromString(jsonString: str)!["data"].arrayValue.count>0{
                            self.currentPage+=1
                        }
                        for item in JSON.fromString(jsonString: str)!["data"].arrayValue {
                            self.resourceData.append(MicroCourseModel(j: item))
                        }
                        success=true
                    }, failHandler: { (error) in
                        success=false
                        appRootViewController().view.makeToast("获取资源失败:\(error.localizedDescription)")
                    })
                }else{
                    success=false
                    appRootViewController().view.makeToast("获取资源失败:\(JSON.fromString(jsonString: str)!["message"].stringValue)")
                }
            }else{
                success=false
                appRootViewController().view.makeToast("获取资源失败:\(error!.description)")
            }
            completionHandler(success)
        }
    }
    // MARK: - 跳转到筛选
    @IBAction func jumpFilterVCAction(_ sender: UIButton) {
        let vc = UIStoryboard(name: "Resource", bundle: nil).instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView==searchTableView{
            return searchAry.count
        }else{
            return resourceData.count
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView==searchTableView {
            let cell=tableView.dequeueReusableCell(withIdentifier: "cell")
            cell?.textLabel?.text=searchAry[indexPath.row]
            return cell!
        }else{
            let cell=tableView.dequeueReusableCell(withIdentifier: "identifier") as! ResourceViewControllerTableViewCell
            cell.setUpWith(item: resourceData[indexPath.row])
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView==searchTableView {
            let vc = UIStoryboard(name: "HomePage", bundle: nil).instantiateViewController(withIdentifier: "RankingTableViewController") as! RankingTableViewController
            self.navigationController?.pushViewController(vc, animated: true)
        }else{
            
        }
    }
    //取消键盘输入状态
    @IBAction func cancleSearchActivit(_ sender: UITapGestureRecognizer) {
        searchController.isActive=false
    }
    func willPresentSearchController(_ searchController: UISearchController) {
        grayView.isHidden=false
    }
    func willDismissSearchController(_ searchController: UISearchController) {
        searchTableHeight.constant=44
        grayView.isHidden=true
    }
    //谓词搜索过滤
    func updateSearchResults(for searchController: UISearchController) {
        let searchString=searchController.searchBar.text
        let predicate=NSPredicate(format: "SELF CONTAINS[c] %@", searchString!)
        searchAry=(dataSetAry as NSArray).filtered(using: predicate) as! [String]
        if CGFloat((searchAry.count+1)*44)>(getScreenHeight()-64){
            searchTableHeight.constant=getScreenHeight()-64
        }else{
            searchTableHeight.constant=CGFloat((searchAry.count+1)*44)
        }
        searchTableView.reloadData()
    }

}


extension ResourceViewController:UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ResourceViewControllerCollectionCell
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

}

class ResourceViewControllerTableViewCell:UITableViewCell{
    @IBOutlet var iconImageView: UIImageView!
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var updateTeacherLabel: UILabel!
    @IBOutlet var timeLabel: UILabel!
    @IBOutlet var downLoadCountLabel: UILabel!
    func setUpWith(item: MicroCourseModel){
        iconImageView.sd_setImage(with: URL(string: item.f_Img), placeholderImage: UIImage(named: "icon_course_placeholder"))
        titleLabel.text=item.f_Title
        updateTeacherLabel.text="上传者:\(item.f_CreatorName) 老师"
        timeLabel.text=item.f_CreatorTime
        downLoadCountLabel.text="\(item.f_DownloadSum)"
    }
}


class ResourceViewControllerCollectionCell:UICollectionViewCell{
    
}