//
//  MVHomeController.swift
//  MusicVideoPlus
//
//  Created by ak on 2021/6/2.
//  首界面

import BFFramework
class MVHomeController: MVBaseController {
    // 当前选择的位置
    var lastIndexPath: IndexPath = IndexPath(row: 0, section: 0)
    private var banner: MVBanner = {
        let banner = MVBanner(frame: .zero, margin: 30, lineSpacing: 12, minScale: MVBanner.Scale(scale: 1))
        banner.backgroundColor = UIColor.white

        banner.register(classCellType: MVBannerCell.self)
        return banner
    }()

    // 卡点视频 btn
    lazy var stuckPointBtn: UIButton = {
        let stuckPointBtn = UIButton(type: .custom)
        stuckPointBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        stuckPointBtn.setImage(UIImage(named: "add"), for: .normal)
        stuckPointBtn.adjustsImageWhenHighlighted = false
        stuckPointBtn.tag = 2000
        stuckPointBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#3DC1C1")

        stuckPointBtn.addCorner(corner: 30)

        return stuckPointBtn
    }()

    // 个人中心btn
    lazy var mineBtn: UIButton = {
        let mineBtn = UIButton(type: .custom)
        mineBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        mineBtn.setBackgroundImage(UIImage(named: "wode"), for: .normal)
        mineBtn.adjustsImageWhenHighlighted = false
        mineBtn.tag = 1000
        return mineBtn
    }()

    // 设置btn
    lazy var settingBtn: UIButton = {
        let settingBtn = UIButton(type: .custom)
        settingBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        settingBtn.setBackgroundImage(UIImage(named: "set"), for: .normal)
        settingBtn.adjustsImageWhenHighlighted = false
        settingBtn.tag = 3000
        return settingBtn
    }()
 
    // 标签分类
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets.zero
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 35), collectionViewLayout: flowLayout)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.clear
        collectionView.register(MVTagsCell.self, forCellWithReuseIdentifier: String(describing: MVTagsCell.self))
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        // 延迟scrollView上子视图的响应，所以当直接拖动UISlider时，如果此时touch时间在150ms以内，UIScrollView会认为是拖动自己，从而拦截了event，导致UISlider接收不到滑动的event
        collectionView.delaysContentTouches = false
        return collectionView
    }()
    
    var mVideos:Array = Array<MVHotVideoModel>.init()
    
    var mAllVideos:Array = Array<PQVideoListModel>.init()

    override func viewDidLoad() {
        super.viewDidLoad()
//        view.addSubview(mineBtn)
        view.addSubview(stuckPointBtn)
        view.addSubview(settingBtn)
        view.addSubview(banner)
        view.addSubview(collectionView)
        banner.dataSource = self
        banner.delegate = self
        banner.isShowPageControl = false
        banner.reloadData()

        addLayout()
 
        MVHomeViewModel.getHomeHotVideos {[weak self] hotVideos, _ in
            BFLog(message: "hotVideos count is :\(hotVideos.count)")
            
            self?.mVideos = hotVideos
            
            self?.collectionView.reloadData()
            if((self?.mVideos.count ?? 0) > 0 ){
                
                self?.mVideos[0].isSelected = true
                for hotModel in  self!.mVideos{
                    for video in hotModel.videos {
                        self?.mAllVideos.append(video)
                    }
                }
                BFLog(message: " self?.mAllVideos count is \(String(describing: self?.mAllVideos.count))")
            }
            
            self?.banner.reloadData()
        
            
            
        }
        
        
     
        
        PQSingletoVideoPlayer.shared.progressBloc = { [weak self] loadProgress, playProgress, duration in
        
            BFLog(message: "loadProgress \(loadProgress) playProgress\(playProgress) \(duration)")
 
        }
        PQSingletoVideoPlayer.shared.playStatusBloc = { [weak self] status in

            if(status == .PQVIDEO_PLAY_STATUS_END){
                PQSingletoVideoPlayer.shared.resetPlayer()
            }
        }
    }
    

    func addLayout() {
//        mineBtn.snp.remakeConstraints { make in
//            make.width.equalTo(60)
//            make.height.equalTo(60)
//            make.left.equalToSuperview().offset(16)
//            make.bottom.equalToSuperview().offset(-50)
//        }
        stuckPointBtn.snp.remakeConstraints { make in
            make.width.equalTo(60)
            make.height.equalTo(60)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
        }

        settingBtn.snp.remakeConstraints { make in
            make.width.equalTo(60)
            make.height.equalTo(60)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-50)
        }

        banner.snp.remakeConstraints { make in
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(560)
            make.left.equalToSuperview().offset(0)
            make.bottom.equalToSuperview().offset(-136)
        }

        collectionView.snp.remakeConstraints { make in
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(35)
            make.left.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(cDevice_iPhoneStatusBarHei)
        }
    }

    @objc func btnClick(sender: UIButton) {
        // 先判断是否登录
        if !BFLoginUserInfo.shared.isLogin() && sender.tag != 3000 {
            let vc = MVLoginController()
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true, completion: nil)
            return
        }

        switch sender.tag {
        case 1000:
            navigationController?.pushViewController(MVMineController(), animated: true)
            break
        case 2000:
            navigationController?.pushViewController(PQStuckPointMaterialController(), animated: true)
            break

        case 3000:
            navigationController?.pushViewController(MVSettingController(), animated: true)
            break

        default:
            break
        }
    }
}

// MARK: - MVBannerDataSource

extension MVHomeController: MVBannerDataSource, MVBannerDelegate {
    func numberOfItems() -> Int {
        return mAllVideos.count
    }

    func banner(_ banner: MVBanner, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MVBannerCell = banner.dequeueReusableCell(for: indexPath)
        cell.contentView.layer.masksToBounds = true
        cell.contentView.layer.cornerRadius = 10
        cell.contentView.backgroundColor = UIColor.white
 
        cell.videoData = mAllVideos[indexPath.row]
        cell.reCreateBtnClicHandle = { [weak self] _, _ in
            BFLog(message: "点击了创同款")
            PQSingletoVideoPlayer.shared.stopPlayer(isRemove: false)
        }
 

        return cell
    }

    // MARK: - GXBannerDelegate

    func banner(_: MVBanner, didSelectItemAt indexPath: IndexPath) {
        NSLog("didSelectItemAt %d", indexPath.row)
        
        let cell: MVBannerCell?  =  banner.collectionView.cellForItem(at: indexPath) as? MVBannerCell
        
        if(PQSingletoVideoPlayer.shared.player.isPlaying()){
            cell?.pauseView.isHidden = false
            PQSingletoVideoPlayer.shared.stopPlayer(isRemove: false)
        
        }else{
            PQSingletoVideoPlayer.shared.resetPlayer()
            cell?.pauseView.isHidden = true
        }

    }
    
    func pageControl(currentPage page: Int) {
        BFLog(message: "page is \(page)")
        
        let cell: MVBannerCell?  =  banner.collectionView.cellForItem(at: IndexPath.init(row: page, section: 0)) as? MVBannerCell
        
       
        if (mVideos.count > 0  && cell != nil) {
            cell?.pauseView.isHidden = true
            PQSingletoVideoPlayer.shared.configPlyer(videoData:  mAllVideos[page], controllerView: cell!.iconIView)
        }
        
    
    }
}

// MARK: - 卡点音乐相关代理

/// 卡点音乐相关代理
extension MVHomeController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return mVideos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let itemData: MVHotVideoModel = mVideos[indexPath.item]
        let cell = MVTagsCell.tagsCell(collectionView: collectionView, indexPath: indexPath)
        cell.bgmData = itemData
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemData: MVHotVideoModel = mVideos[indexPath.item]
        let width:CGFloat = CGFloat(CGFloat((itemData.categoryName ).ga_widthForComment(font:UIFont.boldSystemFont(ofSize: 17),height:17.0)) + 36.0 + 20.0)
 
        return CGSize(width: width, height: collectionView.frame.height)
    }
  

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let itemData: MVHotVideoModel = mVideos[lastIndexPath.item]
        itemData.isSelected = false
        lastIndexPath = indexPath
        let itemDataNew: MVHotVideoModel = mVideos[lastIndexPath.item]
        itemDataNew.isSelected = true
        collectionView.reloadData()
    }

 

    func collectionView(_: UICollectionView, willDisplay _: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let itemData: Any = mVideos[indexPath.item]
    }
}
