ExcellentTVViewController.swift 15.9 KB
//
//  ExcellentTVViewController.swift
//  YouerLiveVideo
//
//  Created by 左丞 on 2017/5/20.
//  Copyright © 2017年 左丞. All rights reserved.
//

import UIKit
import AVKit
class ExcellentTVViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    var isForbidScrollDelegate:Bool = true
    var startOffsetX:CGFloat = 0
    var TVStationClasses:[TVSubjectInfor] = []
    var allDataSet:[TVStationSubject] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        AppDelegate.instance().httpServer.getTelevisionStationCatagory(parameters: nil) { (str, error) in
            httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                for item in json.contentData().arrayValue{
                    self.TVStationClasses.append(TVSubjectInfor(json: item))
                }
                self.collectionView.reloadData()
            }, failHandler: { (error) in
                
            })
        }
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


//下方的所有电视节目所在的collcetionView
extension ExcellentTVViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
//    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//        startOffsetX = scrollView.contentOffset.x
//        isForbidScrollDelegate = false
//    }

//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        if isForbidScrollDelegate { return }
//        NSLog("\(scrollView.contentOffset.x)")
//        var btn:UIButton!
//        var num:CGFloat!
//        let btnIndex = scrollView.contentOffset.x/getScreenWidth()
//        let view = TVStationClass.viewWithTag(2000+titleSelectBtn)! as! UIScrollView
//        if view.contentSize.width > getScreenWidth(){
//            if scrollView.contentOffset.x > startOffsetX{
//                if scrollView.contentOffset.x - startOffsetX == getScreenWidth(){
//                    num = btnIndex
//                }else{
//                    num = btnIndex+1
//                }
//                if Int(num) >= TVStationClasses[titleSelectBtn].ch.count {
//                    return
//                }
//                btn = view.viewWithTag(1000+100*titleSelectBtn+Int(num))! as! UIButton
//                let TVStationContentOffset = btn.frame.origin.x+btn.frame.width/2
//                if TVStationContentOffset < view.contentSize.width-getScreenWidth()/2 && TVStationContentOffset >= getScreenWidth()/2{
//                    view.contentOffset.x = TVStationContentOffset - getScreenWidth()/2
//                }
//                if TVStationContentOffset >= view.contentSize.width-getScreenWidth()/2{
//                    view.contentOffset.x = view.contentSize.width-getScreenWidth()
//                }
//            }
//            else{
//                let num = btnIndex
//                if num < 0{
//                    return
//                }
//                btn = view.viewWithTag(1000+100*titleSelectBtn+Int(num))! as! UIButton
//                let TVStationContentOffset = btn.frame.origin.x+btn.frame.width/2
//                if TVStationContentOffset < view.contentSize.width-getScreenWidth()/2 && TVStationContentOffset >= getScreenWidth()/2{
//                    view.contentOffset.x = TVStationContentOffset-getScreenWidth()/2
//                }
//                if TVStationContentOffset < getScreenWidth()/2{
//                    view.contentOffset.x = 0
//                }
//            }
//        }else{
//            btn = view.viewWithTag(1000+100*titleSelectBtn+Int(btnIndex))! as! UIButton
//        }
//        for i in 0..<TVStationClasses[titleSelectBtn].ch.count{
//            let item = view.viewWithTag(i+1000+100*titleSelectBtn) as! UIButton
//            item.backgroundColor = UIColor.white
//            item.setTitleColor(UIColor.black, for: .normal)
//        }
//        btn.setTitleColor(UIColor.white, for: .normal)
//        btn.backgroundColor = UIColorFromRGB(0x17B3FF)
//    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! ExcellentTVInforViewCell
        cell.superNavigation = self.navigationController
        cell.model = allDataSet[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allDataSet.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (getScreenWidth()-30)/2, height: 200)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableView:UICollectionReusableView!
        if kind == UICollectionElementKindSectionHeader{
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as! ExcellentTVInforHeaderView
            if headerView.TVStationClasses.count == 0{
                headerView.TVStationClasses = TVStationClasses
                headerView.creatTVStationClassScrollView()
                headerView.settingCarouselView()
                headerView.superViewController = self
            }
            reusableView = headerView
        }
        return reusableView
    }
}

class ExcellentTVInforHeaderView:UICollectionReusableView{
    @IBOutlet weak var AllTitleView: UIView!
    @IBOutlet weak var lunboView: UIView!
    @IBOutlet weak var TVStationClass: UIView!
    var TVStationScrollView:UIScrollView!//第一排目录
    var TVStationClasses:[TVSubjectInfor] = []
    var titleSelectBtn:Int = 0
    var classSelectBtn:Int = 0
    var superViewController:ExcellentTVViewController!
    
    func settingCarouselView(){
        AppDelegate.instance().httpServer.getLunboList(parameters: ["type": 1 as AnyObject]) { (str, error) in
            if error==nil {
                if JSON.fromString(jsonString: str)!["status"].intValue == 1{
                    httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                        var lineAry:[String]=[]
                        var lineModelAry:[InLineModel]=[]
                        for item in JSON.fromString(jsonString: str)!["data"].arrayValue {
                            lineModelAry.append(InLineModel(j: item))
                            lineAry.append(item["f_Img"].stringValue)
                        }
                        if lineModelAry.count>0{
                            let jyScrollViews=JYScrollView(frame: CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenWidth()/12*5))
                            jyScrollViews.banner(with: lineAry, imageType: JYImageType.urlType, placeHolder: "default") { (index) in
                                
                                NSLog("点击了轮播图   图片ID:\(lineModelAry[index].f_Id)")
                            }
                            jyScrollViews.timeInterval=2
                            self.lunboView.addSubview(jyScrollViews)
                        }
                    }, failHandler: { (error) in
                        self.superViewController.view.makeToast("获取轮播图失败:\(error.localizedDescription)")
                    })
                }else{
                    self.superViewController.view.makeToast("获取轮播图失败:\(JSON.fromString(jsonString: str)!["message"].stringValue)")
                }
            }else{
                self.superViewController.view.makeToast("获取轮播图失败:\(error!.description)")
            }
        }
    }
    
    func creatTVStationClassScrollView(){
        TVStationScrollView = UIScrollView(frame: CGRect(origin: CGPointZero, size: TVStationClass.frame.size))
        TVStationScrollView.showsHorizontalScrollIndicator = false
        TVStationScrollView.showsVerticalScrollIndicator = false
        TVStationScrollView.bounces = false
        var x:CGFloat = 0
        for (index,item) in TVStationClasses.enumerated() {
            let TVStationClassScrollView = UIScrollView(frame: CGRect(origin: CGPointZero, size: AllTitleView.frame.size))
            
            let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: TVStationClass.frame.size.height))
            btn.backgroundColor = UIColor.white
            btn.setTitleColor(UIColor.black, for: .normal)
            btn.setTitle(item.name, for: .normal)
            btn.sizeToFit()
            if index != 0{
                x = TVStationScrollView.viewWithTag(200+index-1)!.frame.maxX
                TVStationClassScrollView.isHidden = true
            }else{
                x = 0
                TVStationClassScrollView.isHidden = false
                btn.backgroundColor = UIColorFromRGB(0x17B3FF)
                btn.setTitleColor(UIColor.white, for: .normal)
            }
            btn.frame.origin.x = x
            btn.frame.size = CGSize(width: btn.frame.size.width+20, height: TVStationClass.frame.size.height)
            btn.tag = 200+index
            TVStationScrollView.contentSize = CGSize(width: btn.frame.maxX, height: 0)
            btn.addTarget(self, action: #selector(ExcellentTVInforHeaderView.TVStationBtnClick(btn:)), for: .touchUpInside)
            TVStationScrollView.addSubview(btn)
            
            TVStationClassScrollView.showsHorizontalScrollIndicator = false
            TVStationClassScrollView.showsVerticalScrollIndicator = false
            TVStationClassScrollView.bounces = false
            TVStationClassScrollView.tag = 2000+index
            for (ind,it) in item.ch.enumerated() {
                let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: TVStationClass.frame.size.height))
                button.backgroundColor = UIColor.white
                button.setTitleColor(UIColor.black, for: .normal)
                button.setTitle(it.name, for: .normal)
                button.sizeToFit()
                if ind != 0{
                    x = TVStationClassScrollView.viewWithTag(1000+index*100+ind-1)!.frame.maxX
                }else{
                    x = 0
                    
                    button.backgroundColor = UIColorFromRGB(0x17B3FF)
                    button.setTitleColor(UIColor.white, for: .normal)
                }
                button.frame.origin.x = x
                button.frame.size = CGSize(width: button.frame.size.width+20, height: TVStationClass.frame.size.height)
                button.tag = 1000+index*100+ind
                TVStationClassScrollView.contentSize = CGSize(width: button.frame.maxX, height: 0)
                button.addTarget(self, action: #selector(ExcellentTVInforHeaderView.TVStationClassBtnClick(btn:)), for: .touchUpInside)
                TVStationClassScrollView.addSubview(button)
            }
            TVStationClass.addSubview(TVStationClassScrollView)
        }
        AllTitleView.addSubview(TVStationScrollView)
    }
    
    func TVStationBtnClick(btn:UIButton){
        titleSelectBtn = btn.tag%10
        classSelectBtn = 0
        getData()
        for i in 0..<TVStationClasses.count{
            let item = AllTitleView.viewWithTag(200+i) as! UIButton
            item.backgroundColor = UIColor.white
            item.setTitleColor(UIColor.black, for: .normal)
            TVStationClass.viewWithTag(2000+i)?.isHidden = true
        }
        for i in 0..<TVStationClasses[titleSelectBtn].ch.count{
            let item = TVStationClass.viewWithTag(2000+titleSelectBtn)!.viewWithTag(1000+100*titleSelectBtn+i) as! UIButton
            if i == 0{
                item.backgroundColor = UIColorFromRGB(0x17B3FF)
                item.setTitleColor(UIColor.white, for: .normal)
                
            }else{
                item.backgroundColor = UIColor.white
                item.setTitleColor(UIColor.black, for: .normal)
                
            }
        }
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = UIColorFromRGB(0x17B3FF)
        TVStationClass.viewWithTag(2000+btn.tag%10)?.isHidden = false
    }
    func TVStationClassBtnClick(btn:UIButton){
        classSelectBtn = btn.tag%10
        let index = btn.tag%1000/100
        getData()
        for i in 0..<TVStationClasses[index].ch.count{
            let item = TVStationClass.viewWithTag(2000+titleSelectBtn)!.viewWithTag(1000+100*index+i) as! UIButton
            item.backgroundColor = UIColor.white
            item.setTitleColor(UIColor.black, for: .normal)
        }
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = UIColorFromRGB(0x17B3FF)
    }
    
    func getData(){
        if TVStationClasses.count == 0{
            return
        }
        superViewController.allDataSet.removeAll()
        AppDelegate.instance().httpServer.postExcellentProgram(parameters: ["f_TelevisionId":TVStationClasses[titleSelectBtn].ch[classSelectBtn].id as AnyObject,"pageIndex":1 as AnyObject]) { (str, error) in
            httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                for item in json.contentData()["resultData"].arrayValue{
                    self.superViewController.allDataSet.append(TVStationSubject(json: item))
                }
                self.superViewController.collectionView.reloadData()
            }, failHandler: { (error) in
                
            })
        }
    }
}


class ExcellentTVInforViewCell: UICollectionViewCell{
    
    @IBOutlet weak var tvStationLogo: UIImageView!
    @IBOutlet weak var subjectType: UILabel!
    @IBOutlet weak var playCount: UILabel!
    var superNavigation:UINavigationController!
    var model:TVStationSubject? {
        didSet{
            self.tvStationLogo.sd_setImage(with: URL(string: model!.f_Img), placeholderImage: #imageLiteral(resourceName: "placeholder"))
            self.playCount.text = "播放次数:" + "\(model!.f_Pv!)"
            self.subjectType.text = model!.f_Title
        }
    }
    
    @IBAction func playBtnClick(_ sender: UIButton) {
        AppDelegate.instance().httpServer.addHistoryView(parameters: ["f_ViewType":self.model!.f_ResourceType as AnyObject,"f_ViewId":self.model!.f_Id as AnyObject,"f_ViewName":self.model!.f_Title as AnyObject]) { (str, error) in
        }
        let url = URL(string:self.model!.f_ResourceUrl)
        let player = AVPlayerViewController()
        player.player = AVPlayer(url: url!)
        player.videoGravity = AVLayerVideoGravityResizeAspect
        superNavigation.present(player, animated: true, completion: nil)
    }
}

class TVSubjectInfor{
    var id:String!
    var name:String!
    var text:String!
    var open:Bool!
    var ch:[TVSubjectInfor]=[]
    init(json:JSON){
        id = json["id"].stringValue
        name = json["name"].stringValue
        text = json["text"].stringValue
        name = json["name"].stringValue
        for item in json["children"].arrayValue {
            ch.append(TVSubjectInfor(json: item))
        }
    }
}