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

import BFFramework
class MVHomeController: MVBaseController {
    // 视频播放列表
    public let margin: CGFloat = cDefaultMargin * 3
    public let maxHeight: CGFloat = cScreenHeigth - (cDevice_iPhoneStatusBarHei + 45 + 60 + (cDefaultMargin * 2 + cSafeAreaHeight) + cDefaultMargin * 3)
    lazy var viewListView: MVBanner = {
        let maxWidth: CGFloat = 9.0 / 16.0 * maxHeight
        let margin = (cScreenWidth - maxWidth) / 2
        let lineSpacing = margin - cDefaultMargin * 3
        let videoListView = MVBanner(frame: .zero, margin: margin, lineSpacing: 15, minScale: MVBanner.Scale(scale: 1))
        videoListView.backgroundColor = UIColor.white
        videoListView.register(classCellType: MVBannerCell.self)
        return videoListView
    }()

    // 卡点视频 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 categoryCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 45), 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
    }()
    //网络错误提示
    lazy var emptyRemindView: PQEmptyRemindView = {
        let emptyRemindView = PQEmptyRemindView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth - 120 - cAKSafeAreaHeight))
        emptyRemindView.fullRefreshBloc = { [weak self] _, _ in
            self?.getData()
            
        }
        return emptyRemindView
    }()

    var mVideos: Array = Array<MVHotVideoModel>.init()

    var mAllVideos: Array = Array<PQVideoListModel>.init()
    var lastBnnerSelectIndex: IndexPath = IndexPath(row: 0, section: 0)
    // 是否点击的再创作
    var isCreateVideo: Bool = false
    deinit {
        PQNotification.removeObserver(self)
    }

    // 登录成功后自动跳转到系统相册
    @objc func loginSuccesss() {
        if isCreateVideo {
            isCreateVideo = false
            let videoListModel = mAllVideos[lastBnnerSelectIndex.row]
            jumpToDetailVc(type: 2, videoData: videoListModel)
        } else {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
                self?.jumpToDetailVc(type: 3)
            }
        }
    }

    @objc func enterBackground() {
        BFLog(message: "进入到后台")
        controlPlayrPasueOrResume(isPause: true)
    }

    @objc func willEnterForeground() {
        BFLog(message: "进入到前台")
        controlPlayrPasueOrResume(isPause: false)
    }

    override func viewWillAppear(_: Bool) {
        super.viewWillAppear(true)

        controlPlayrPasueOrResume(isPause: false)

        PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        controlPlayrPasueOrResume(isPause: true)
    }

    func getData() {
        if mVideos.count > 0 {
            BFLog(message: "已经请求过数据")
            return
        }
      
        PQLoadingHUB.shared.showHUB(superView:view)
        MVHomeViewModel.getHomeHotVideos { [weak self] hotVideos, msg in
            if(msg == nil){
                BFLog(message: "hotVideos count is :\(hotVideos.count)")
                PQLoadingHUB.shared.dismissHUB(superView:(self?.view)!)
                self?.showNetworkError(isHidden: true)
                self?.refreshData(hotVideos: hotVideos)
            }else{
                BFLog(message: "请求数据出错 :\(String(describing: msg))")
                self?.showNetworkError(isHidden: false)
            }
          
            
 
        }
    }
    
    //显示网络未连接提示
    func showNetworkError(isHidden:Bool) {
    
        emptyRemindView.isHidden = isHidden
    
        emptyRemindView.remindLab.textColor = .black
        emptyRemindView.remindLab.text = "网络错误"
        emptyRemindView.remindLab.font = UIFont.boldSystemFont(ofSize: 20)
        emptyRemindView.imageView.image = nil
        emptyRemindView.remindSubLab.text = "请检查网络后重试"
        emptyRemindView.remindSubLab.isHidden = false
        emptyRemindView.refreshBtn.isHidden = false
        emptyRemindView.refreshBtn.backgroundColor =   UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        emptyRemindView.refreshBtn.setTitle("重试", for: .normal)
        if(isHidden){
            emptyRemindView.removeFromSuperview()
        }else{
            view.addSubview(emptyRemindView)
        }
      
    }
    
    func refreshData( hotVideos:Array<MVHotVideoModel>) {
         
        mVideos = hotVideos
        categoryCollectionView.reloadData()
        if mVideos.count > 0 {
            mVideos[0].isSelected = true
            for hotModel in mVideos {
                for video in hotModel.videos {
                    mAllVideos.append(video)
                }
            }
            BFLog(message: " self?.mAllVideos count is \(String(describing: mAllVideos.count))")
        }
        viewListView.reloadData()
        // 自动播放第一个视频 确保 reloaddata 完成
        playVideo(page: 0)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        addNotification(self, selector: #selector(loginSuccesss), name: cLoginSuccesssNotiKey, object: nil)
        addNotification(self, selector: #selector(loginSuccesss), name: cBandingPhoneSuccessKey, object: nil)
        addNotification(self, selector: #selector(stuckPointDismiss), name: cFinishedPublishedNotiKey, object: nil)

//        view.addSubview(mineBtn)
        view.addSubview(stuckPointBtn)
        view.addSubview(settingBtn)
        view.addSubview(viewListView)
        view.addSubview(categoryCollectionView)
        viewListView.dataSource = self
        viewListView.delegate = self
        viewListView.isShowPageControl = false
        viewListView.reloadData()

        addLayout()
        // 请求用户状态
        getUserInfo()
        // 网络监听有网后取一次数据
        manager?.startListening()
        manager?.listener = { [weak self] status in
            if status == .reachable(.wwan) || status == .reachable(.ethernetOrWiFi) {
                BFLog(message: "来网了")
                self?.showNetworkError(isHidden: true)

                self?.getData()
            } else {
                if(MVHotVideoModel.getCacheData().count == 0){
                    self?.showNetworkError(isHidden: false)
                }
               
            }
        }
        
        let cacheData = MVHotVideoModel.getCacheData()
        if(cacheData.count > 0){
            BFLog(message: "有缓存数据 ")
            refreshData(hotVideos: cacheData)
        }

        // 播放器进度和状态回调
        PQSingletoVideoPlayer.shared.progressBloc = { [weak self] _, playProgress, duration in

            BFLog(message: "duration \(duration) playProgress\(playProgress) \(duration) 进度\(playProgress / duration)")
            let cell: MVBannerCell? = self?.viewListView.collectionView.cellForItem(at: self?.lastBnnerSelectIndex ?? IndexPath()) as? MVBannerCell
            cell?.progressView.progress = playProgress / duration
        }
        PQSingletoVideoPlayer.shared.playStatusBloc = { [weak self] status in

            // 播放完成 自动播放下一个
            if status == .PQVIDEO_PLAY_STATUS_END {
                PQSingletoVideoPlayer.shared.playVideoData!.playProgress = 0
                if (self?.lastBnnerSelectIndex.row ?? 0) < (self?.mAllVideos.count ?? 0) - 1 {
                    self?.lastBnnerSelectIndex = IndexPath(row: (self?.lastBnnerSelectIndex.row ?? 0) + 1, section: 0)
                    self?.playVideo(page: (self?.lastBnnerSelectIndex ?? IndexPath(row: 0, section: 0)).row)

                    // 视频列表跳转
                    self?.viewListView.currentIndex = (self?.lastBnnerSelectIndex ?? IndexPath(row: 0, section: 0)).row
                    self?.viewListView.scrollToItem(at: (self?.lastBnnerSelectIndex ?? IndexPath(row: 0, section: 0)).row, animated: false)

                } else { BFLog(message: "已经是最后一个视频。") }
            }
        }
        // 添加协议
        let showProtocal: String? = getUserDefaults(key: cShowProtocal) as? String
        if showProtocal == nil || showProtocal?.count ?? 0 <= 0 || showProtocal != "1" {
            let protocalView: PQServerProtocalView = PQServerProtocalView(frame: view.frame)
            protocalView.tag = cProtocalViewTag
            protocalView.remindBlock = { [weak self] sender, webUrl in
                if sender == nil, webUrl != nil {
                    let detail = PQBaseWebViewController()
                    detail.baseUrl = webUrl
                    self?.navigationController?.pushViewController(detail, animated: true)
                }
                // 移除继续播放
                if sender != nil {
                    self?.playVideo(page: 0)
                }
            }
            UIApplication.shared.keyWindow?.addSubview(protocalView)
        }
    }

    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)
//        }
        categoryCollectionView.snp.remakeConstraints { make in
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(45)
            make.left.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(cDevice_iPhoneStatusBarHei)
        }

        stuckPointBtn.snp.remakeConstraints { make in
            make.width.height.equalTo(60)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-(cDefaultMargin +  cAKSafeAreaHeight))
        }

        settingBtn.snp.remakeConstraints { make in
            make.width.height.equalTo(60)
            make.right.equalToSuperview().offset(-cDefaultMargin * 3)
            make.centerY.equalTo(stuckPointBtn)
        }

        viewListView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(categoryCollectionView.snp_bottom).offset(cDefaultMargin)
            make.bottom.equalTo(stuckPointBtn.snp_top).offset(-cDefaultMargin * 2)
        }
    }

    @objc func btnClick(sender: UIButton) {
        switch sender.tag {
        case 1000: // 个人中心
            jumpToDetailVc(type: 1)
        case 2000: // 系统相册
            jumpToDetailVc(type: 3)
        case 3000: // 设置
            navigationController?.pushViewController(MVSettingController(), animated: true)
        default:
            break
        }
    }

    /// 判断是否可进入对就界面
    /// - Parameters:
    ///   - type: 进入界面  1， 个人中心 2，再创作进入相册 PQVideoListModel 不能为空要使用音乐数据  3，直接创作进入相机
    ///   - videoData: type == 2 时必传
    func jumpToDetailVc(type: Int, videoData: PQVideoListModel? = nil) {
        // 无网
        if !isNetConnected() {
            let remindData: PQBaseModel = PQBaseModel()
            remindData.title = "似乎已断开与互联网的连接"
            let remindView = PQRemindView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
            UIApplication.shared.keyWindow?.addSubview(remindView)
            remindView.remindData = remindData
            remindView.remindBlock = { [weak self] sender, _ in
                if sender.tag == 2 {
                    openAppSetting()
                }
            }
            return
        }
        // 先判断是否登录
        if !BFLoginUserInfo.shared.isLogin() {
            let vc = MVLoginController()
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true, completion: nil)
            return
        }

        // 用户被封禁
        BFLog(message: "userStatus is \(BFLoginUserInfo.shared.userStatus)")
        if BFLoginUserInfo.shared.userStatus == "3" {
            PQBandingPhoneRemindView.accountBlockRemindView(remindTitle: "无法上传视频")
            return
        }

        // 未绑定手机号
        BFLog(message: "phoneNumber is \(BFLoginUserInfo.shared.phoneNumber)")
        if BFLoginUserInfo.shared.phoneNumber.count <= 0 || BFLoginUserInfo.shared.phoneNumber == "<null>" {
            let remindView = PQBandingPhoneRemindView(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
            remindView.tag = cBandinPhoneTag
            remindView.bandingPhoneRemindHandle = { [weak self] sender in
                if sender.tag == 2 {
                    self?.navigationController?.pushViewController(PQBandingPhoneController(), animated: true)
                }
            }
            remindView.remindBlock = { [weak self] _, webUrl in
                let detail = PQBaseWebViewController()
                detail.baseUrl = webUrl
                self?.navigationController?.pushViewController(detail, animated: true)
            }
            view.addSubview(remindView)

            return
        }

        // 条件都满足转换到对就界面
        switch type {
        case 1:
            navigationController?.pushViewController(MVMineController(), animated: true)
        case 2:

            PQStuckPointViewModel.stuckPointProjectMusicInfo(projectId: videoData?.reCreateVideoData?.projectId ?? "") { [weak self] musicData, _ in
                if musicData != nil {
                    let vc = PQStuckPointMaterialController()
                    vc.reCreateMusicData = musicData
                    self?.navigationController?.pushViewController(vc, animated: true)
                    // 关闭视频播放
                    self?.controlPlayrPasueOrResume(isPause: true)
                } else { BFLog(message: "musicData is ni") }
            }

        case 3:
            let nav = UINavigationController(rootViewController: PQStuckPointMaterialController())
            nav.modalPresentationStyle = .overFullScreen
            present(nav, animated: true, completion: nil)
            // 关闭视频播放
            controlPlayrPasueOrResume(isPause: true)
        default:
            break
        }
    }

    // 再创作视频
    func createVideo(indexPath: IndexPath) {
        if mAllVideos.count > indexPath.row {
            isCreateVideo = true
            let videoListModel = mAllVideos[indexPath.row]
            jumpToDetailVc(type: 2, videoData: videoListModel)
        } else {
            BFLog(message: "数据出错越界！！！ mAllVideos.count: \(mAllVideos.count) indexPath.row: \(indexPath.row)")
        }
    }

    // 卡点模块消失
    @objc func stuckPointDismiss() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { [weak self] in
            self?.controlPlayrPasueOrResume(isPause: false)
        }
    }

    /// 获取用户状态信息
    /// - Returns: description
    func getUserInfo() {
        PQMineViewModel.userStatus { _, _ in
        }
    }
}

// MARK: - 播放器操作相关方法

extension MVHomeController {
    /// 播放指定位置的视频
    /// - Parameter page: 视频数据位置
    func playVideo(page: Int) {
        DispatchQueue.main.async {
            let cell: MVBannerCell? = self.viewListView.collectionView.cellForItem(at: IndexPath(row: page, section: 0)) as? MVBannerCell
            let showProtocal: String? = getUserDefaults(key: cShowProtocal) as? String
            if self.mVideos.count > 0, cell != nil, showProtocal != nil, showProtocal == "1" {
                cell?.pauseView.isHidden = true
                cell?.progressView.progress = 0
                let videoInfo = self.mAllVideos[page]
                videoInfo.playProgress = 0
        
                let hotVideoIndex = self.mVideos.firstIndex(where: { (items) -> Bool in
                    items.categoryName == videoInfo.categoryName
                })

                BFLog(message: "播放的视频分类为:\(String(describing: self.mVideos[hotVideoIndex ?? 0].categoryName)) hotVideoIndex :\(String(describing: hotVideoIndex)) page is \(page)")
                // 设置选中状态
                for hot in self.mVideos {
                    hot.isSelected = false
                }
                self.mVideos[hotVideoIndex ?? 0].isSelected = true

                self.categoryCollectionView.reloadData()
                self.categoryCollectionView.scrollToItem(at: IndexPath(row: hotVideoIndex ?? 0, section: 0), at: .centeredHorizontally, animated: true)

                self.lastBnnerSelectIndex = IndexPath(row: page, section: 0)
                
                PQSingletoVideoPlayer.shared.configPlyer(videoData: videoInfo, controllerView: cell!.converView)
                PQSingletoVideoPlayer.shared.startPlayr()
        

            } else {
                BFLog(message: "播放不成功: cell:\(String(describing: cell)) mVideos:\(self.mVideos.count) showProtocal: is \(String(describing: showProtocal))")
            }
        }
    }

    // 控制播放器的暂停或恢复
    func controlPlayrPasueOrResume(isPause: Bool) {
        let cell: MVBannerCell? = viewListView.collectionView.cellForItem(at: lastBnnerSelectIndex) as? MVBannerCell
        BFLog(message: " player isPause is \(isPause)")
        if isPause {
            cell?.pauseView.isHidden = false
            PQSingletoVideoPlayer.shared.pausePlayer()
        } else {
            var rootViewController = UIApplication.shared.keyWindow?.rootViewController
            if rootViewController is UINavigationController {
                rootViewController = (rootViewController as? UINavigationController)?.visibleViewController
            }
            BFLog(message: "rootViewController is \(rootViewController)")
            if rootViewController is MVHomeController {
                cell?.pauseView.isHidden = true
                PQSingletoVideoPlayer.shared.resumePlayer()
            }
        }
    }
}

// MARK: - 视频列表相关代理

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.videoData = mAllVideos[indexPath.row]
        cell.reCreateBtnClicHandle = { [weak self] _, _ in
            BFLog(message: "点击了创同款")
            self?.createVideo(indexPath: indexPath)
        }

        return cell
    }

    // MARK: - GXBannerDelegate

    func banner(_: MVBanner, didSelectItemAt indexPath: IndexPath) {
        NSLog("didSelectItemAt %d", indexPath.row)
        lastBnnerSelectIndex = indexPath

        controlPlayrPasueOrResume(isPause: PQSingletoVideoPlayer.shared.isPlaying)
    }

    func pageControl(currentPage page: Int) {
        BFLog(message: "page is \(page)")
        playVideo(page: page)
    }
}

// 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)) + 43)

        return CGSize(width: width, height: collectionView.frame.height - 14)
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        for hot in mVideos {
            hot.isSelected = false
        }

        let itemDataNew: MVHotVideoModel = mVideos[indexPath.item]
        itemDataNew.isSelected = true
        categoryCollectionView.reloadData()

        // 找出当前选择分类之前的视频数量和
        var videosCount: Int = 0
        if indexPath.row != 0 {
            for i in 0 ... indexPath.row - 1 {
                videosCount = videosCount + mVideos[i].videos.count
            }
            BFLog(message: "indexPath 选择\(indexPath.item) 之前的视频合\(videosCount)")
        }
        viewListView.currentIndex = videosCount
        viewListView.scrollToItem(at: videosCount, animated: false)

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.05) {
            self.playVideo(page: videosCount)
        }
    }
}
