//
//  MVPlayViewController.swift
//  MusicVideoPlus
//
//  Created by SanW on 2021/6/22.
//


import UIKit
import BFUIKit
import WechatOpenSDK
import BFStuckPointKit

class MVPlayViewController: BFBaseViewController {
    var itemsList: [PQVideoListModel] = Array<PQVideoListModel>.init()
    var pageNum: Int = 1
    var currentIndex: IndexPath?
    var currentActionBtn: UIButton? // 记录上次点击按钮
    var currentVideoData: PQVideoListModel? // 记录上次点击数据
    var isRequesting: Bool = false // 是否正在请求数据
    var isPlayEnd: Bool = false // 是否播放结束
    lazy var leftBtn: UIButton = {
        let leftBtn = UIButton(type: .custom)
        leftBtn.frame = CGRect(x: 0, y: cDevice_iPhoneStatusBarHei, width: cDefaultMargin * 4, height: cDefaultMargin * 4)
        leftBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -5, right: 0)
        leftBtn.tintColor = UIColor.white
        leftBtn.setImage((imageInUIKit(by: "icon_detail_back") ?? UIImage()).withRenderingMode(.alwaysTemplate), for: .normal)
        leftBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
        return leftBtn
    }()

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsets.zero
        layout.minimumInteritemSpacing = 0
        layout.itemSize = view.frame.size
        let collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView.scrollsToTop = false
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(MVPlayControlViewCell.self, forCellWithReuseIdentifier: String(describing: MVPlayControlViewCell.self))
        collectionView.delegate = self
        collectionView.dataSource = self
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        collectionView.addRefreshView(type: .REFRESH_TYPE_HEADER) { [weak self] _ in
            self?.loadRequestData(isRefresh: true)
        }
        // MJRefreshAutoNormalFooter,MJRefreshAutoFooter,MJRefreshBackFooter
        // MJRefreshFooter 无法显示noMoreData文字
        let footer = MJRefreshAutoStateFooter.init { [weak self] in
            self?.loadRequestData(isRefresh: false)
        }
        footer.setTitle("暂时没有更多了", for: .noMoreData)
        footer.setTitle("精彩内容正在加载中...", for: .refreshing)
        collectionView.mj_footer = footer
        return collectionView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        PQSingletoVideoPlayer.shared.stopPlayer()
        view.addSubview(collectionView)
        view.addSubview(leftBtn)
        if itemsList.count <= 0 {
            loadRequestData()
        }
        if currentIndex != nil, itemsList.count > (currentIndex?.item ?? 0) {
            collectionView.contentOffset = CGPoint(x: 0, y: CGFloat(currentIndex?.item ?? 0) * view.frame.size.height)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
                self?.scrollViewDidEndDecelerating(self!.collectionView)
            }
        }

        PQSingletoVideoPlayer.shared.playStatusBloc = { [weak self] status in
            switch status {
            case .PQVIDEO_PLAY_STATUS_BEGIN:
                self?.isPlayEnd = false
            case .PQVIDEO_PLAY_STATUS_END:
                self?.isPlayEnd = true
                if ((self?.currentIndex?.item ?? 0) + 1) < (self?.itemsList.count ?? 0) {
                    self?.collectionView.contentOffset = CGPoint(x: 0, y: CGFloat((self?.currentIndex?.item ?? 0) + 1) * (self!.collectionView.frame.height))
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
                        self?.scrollViewDidEndDecelerating(self!.collectionView)
                    }
                } else {
                    (self?.collectionView.visibleCell() as? MVPlayControlViewCell)?.tagClick()
                    self?.loadRequestData(isRefresh: false)
                }
                if (self?.currentIndex?.item ?? 0) >= ((self?.itemsList.count ?? 0) - 2) {
                    self?.loadRequestData(isRefresh: false)
                }
            case .PQVIDEO_PLAY_STATUS_RECONNECT:
                cShowHUB(superView: self?.view, msg: "当前网络不佳，尝试重新连接")
            case .PQVIDEO_PLAY_STATUS_DISCONNECT:
                cShowHUB(superView: self?.view, msg: "重新连接失败，请点击重试")
                (self?.collectionView.visibleCell() as? MVPlayControlViewCell)?.pauseClick(isHidden: false, isSelected: true)
            default:
                break
            }
        }

        PQSingletoVideoPlayer.shared.progressBloc = { [weak self] _, playProgress, duration in
            (self?.collectionView.visibleCell() as? MVPlayControlViewCell)?.updateProgress(progress: playProgress / duration)
        }
        PQNotification.addObserver(self, selector: #selector(didBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil)
        PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        PQSingletoVideoPlayer.shared.resumePlayer()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        PQSingletoVideoPlayer.shared.pausePlayer()
    }

    /// 请求网络数据
    /// - Parameter isRefresh: <#isRefresh description#>
    /// - Returns: <#description#>
    func loadRequestData(isRefresh: Bool = true, isAutoPlay _: Bool = false) {
        if !isNetConnected() {
            cShowHUB(superView: view, msg: "没有网络连接")
            collectionView.mj_footer?.endRefreshing(completionBlock: { [weak self] in
                self?.collectionView.setContentOffset(CGPoint(x: 0, y: (self?.collectionView.contentSize.height ?? 0) - (self?.collectionView.frame.height ?? 0)), animated: false)
            })
            return
        }
        if isRequesting {
            return
        }
        isRequesting = true
        if isRefresh {
            pageNum = 1
        } else {
            pageNum = pageNum + 1
        }
        MVMineViewModel.userVideoListData(pageNum: pageNum) { [weak self] videoList, _ in
            self?.isRequesting = false
            if videoList != nil, (videoList?.count ?? 0) > 0 {
                if isRefresh {
                    self?.itemsList = videoList!
                } else {
                    self?.itemsList = self!.itemsList + videoList!
                }
                self?.collectionView.reloadData()
                if self?.currentIndex == nil {
                    self?.scrollViewDidEndDecelerating(self!.collectionView)
                } else if self?.isPlayEnd ?? false, ((self?.currentIndex?.item ?? 0) + 1) < (self?.itemsList.count ?? 0) {
                    self?.collectionView.contentOffset = CGPoint(x: 0, y: CGFloat((self?.currentIndex?.item ?? 0) + 1) * (self!.collectionView.frame.height))
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
                        self?.scrollViewDidEndDecelerating(self!.collectionView)
                    }
                }
            } else {
                self?.pageNum = (self?.pageNum ?? 1) - 1
            }
            if isRefresh {
                self?.collectionView.mj_header?.endRefreshing()
                self?.collectionView.mj_footer?.resetNoMoreData()
            } else {
                self?.collectionView.mj_footer?.endRefreshing()
            }
            if (videoList?.count ?? 0) < 20, videoList != nil {
                self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }
        }
    }

    deinit {
        PQNotification.removeObserver(self)
        PQSingletoVideoPlayer.shared.progressBloc = nil
        PQSingletoVideoPlayer.shared.playStatusBloc = nil
        PQSingletoVideoPlayer.shared.stopPlayer()
    }
}

extension MVPlayViewController: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return itemsList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let itemData = itemsList[indexPath.item]
        let cell = MVPlayControlViewCell.playControlCell(collectionView: collectionView, indexPath: indexPath)
        cell.videoData = itemData
        cell.btnClickHandle = { [weak self] sender, videoData in
            self?.btnClickHandle(sender: sender, videoData: videoData)
        }
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt _: IndexPath) {}

    func scrollViewDidEndDecelerating(_: UIScrollView) {
        if itemsList.count <= 0 {
            PQSingletoVideoPlayer.shared.stopPlayer()
            return
        }
        let cell: MVPlayControlViewCell? = collectionView.visibleCell() as? MVPlayControlViewCell
        cell?.pauseClick()
        if cell == nil {
            return
        }
        let indexPath = collectionView.indexPath(for: cell!)
        let itemData = itemsList[indexPath?.item ?? 0]
        if currentIndex != nil, currentIndex?.item == indexPath?.item, PQSingletoVideoPlayer.shared.playControllerView != nil {
            PQSingletoVideoPlayer.shared.configPlyer(videoData: itemData, controllerView: cell!.coverImageView, renderMode: itemData.height <= itemData.width ? .RENDER_MODE_FILL_EDGE : .RENDER_MODE_FILL_SCREEN)
            PQSingletoVideoPlayer.shared.resetPlayer()
            return
        }
        currentIndex = indexPath
        itemData.playProgress = 0
        PQSingletoVideoPlayer.shared.configPlyer(videoData: itemData, controllerView: cell!.coverImageView, renderMode: itemData.height <= itemData.width ? .RENDER_MODE_FILL_EDGE : .RENDER_MODE_FILL_SCREEN)
        PQSingletoVideoPlayer.shared.resetPlayer()
        if (indexPath?.item ?? 0) >= itemsList.count - 2 {
            loadRequestData(isRefresh: false)
        }
    }

    /// 按钮点击处理
    /// - Parameters:
    ///   - sender: <#sender description#>
    ///   - videoData: <#videoData description#>
    /// - Returns: <#description#>
    func btnClickHandle(sender: UIButton, videoData: PQVideoListModel?) {
        switch sender.tag {
        case 1: // 暂停/播放
            if sender.isHidden {
                PQSingletoVideoPlayer.shared.startPlayr()
            } else {
                PQSingletoVideoPlayer.shared.pausePlayer()
            }
        case 2: // 昵称

            break
        case 3: // 做同款
            let navVc: UINavigationController? = (UIApplication.shared.keyWindow?.rootViewController) as? UINavigationController
            (navVc?.viewControllers.first as? MVHomeController)?.jumpToDetailVc(type: 2, videoData: videoData)
        case 4: // 分享好友
            if !isNetConnected() {
                cShowHUB(superView: view, msg: "没有网络连接")
                return
            }
            if !PQSingletoWXApiUtil.shared.isInstallWX() {
                cShowHUB(superView: view, msg: "您还未安装微信客户端！")
                return
            }
            cShowHUB(superView: nil, msg: nil)
            let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
            PQBaseViewModel.wxFriendShareInfo(videoId: (videoData?.uniqueId)!) { [weak self] imagePath, title, shareWeappRawId, msg in
                if msg != nil {
                    cShowHUB(superView: self?.view, msg: "网络不佳哦")
                    return
                }
                PQSingletoWXApiUtil.shared.share(type: 3, scene: Int32(WXSceneSession.rawValue), shareWeappRawId: shareWeappRawId, title: title, description: title, imageUrl: imagePath, path: videoData?.videoPath, videoId: (videoData?.uniqueId)!, pageSource: videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
                    self?.currentActionBtn = sender
                    self?.currentVideoData = videoData
                }
                cHiddenHUB(superView: nil)
            }
            // 分享好友上报
            reportUpload(isFriend: true, openId: "", shareId: shareId, videoData: videoData)
        case 5: // 分享朋友圈
            if !isNetConnected() {
                cShowHUB(superView: view, msg: "没有网络连接")
                return
            }
            if !PQSingletoWXApiUtil.shared.isInstallWX() {
                cShowHUB(superView: view, msg: "您还未安装微信客户端！")
                return
            }
            let shareId = getUniqueId(desc: "\(videoData?.uniqueId ?? "")shareId")
            PQBaseViewModel.h5ShareLinkInfo(videoId: videoData?.uniqueId ?? "", pageSource: videoData?.pageSource ?? .sp_category) { [weak self] path, _ in
                cHiddenHUB(superView: nil)
                if path != nil {
                    
                    //判断shareText是否有效
                    var shareText = ""
                    shareText =  videoData?.title?.replacingOccurrences(of: "\n", with: "") ?? ""
                    shareText = shareText.replacingOccurrences(of: " ", with: "")
                    if(shareText.count == 0){
                        shareText = "\(BFLoginUserInfo.shared.nickName)made a music video for you"
                    }
                    
                    PQSingletoWXApiUtil.shared.share(type: 1, scene: Int32(WXSceneTimeline.rawValue), title:shareText , description: "", imageUrl: videoData?.shareImgPath, path: path, videoId: (videoData?.uniqueId)!, pageSource: videoData?.pageSource ?? .sp_category, shareId: shareId).wxApiUtilHander = { _, _ in
                        self?.currentActionBtn = sender
                        self?.currentVideoData = videoData
                    }
                } else {
                    cShowHUB(superView: self?.view, msg: "没有网络连接")
                }
            }
            // 分享朋友圈上报
            reportUpload(isFriend: false, openId: "", shareId: shareId, videoData: videoData)
        default:
            break
        }
    }

    func reportUpload(isFriend: Bool, openId _: String, shareId: String, videoData: PQVideoListModel?) {
        // 分享上报
        BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: videoData, pageSource: nil, businessType: isFriend ? .bt_videoShareFriend : .bt_videoShareH5, objectType: nil, extParams: nil, shareId: shareId, videoIds: nil, playId: PQSingletoVideoPlayer.shared.playId)
        if isFriend {
            BFEventTrackAdaptor.shareReportUpload(videoId: videoData?.uniqueId ?? "0", pageSource: videoData!.pageSource, recommendId: videoData?.recommendId, recommendLogVO: videoData?.recommendLogVO, flowPool: nil, abInfoData: videoData?.abInfoData, measureType: videoData?.measureType, measureId: videoData?.measureId, businessType: isFriend ? .bt_videoShareFriend : .bt_videoShareH5, targetUid: videoData?.userInfo?.uid, shareId: shareId)
            BFEventTrackAdaptor.shareReportUpload(screenType: 3, videoId: videoData?.uniqueId ?? "0", pageSource: videoData!.pageSource, recommendId: videoData?.recommendId, recommendLogVO: videoData?.recommendLogVO, flowPool: nil, abInfoData: videoData?.abInfoData, measureType: videoData?.measureType, measureId: videoData?.measureId, businessType: isFriend ? .bt_videoShareFriend : .bt_videoShareH5, targetUid: videoData?.userInfo?.uid, shareId: shareId)
        } else {
            BFEventTrackAdaptor.shareReportUpload(screenType: 2, videoId: videoData?.uniqueId ?? "0", pageSource: videoData!.pageSource, recommendId: videoData?.recommendId, recommendLogVO: videoData?.recommendLogVO, flowPool: nil, abInfoData: videoData?.abInfoData, measureType: videoData?.measureType, measureId: videoData?.measureId, businessType: isFriend ? .bt_videoShareFriend : .bt_videoShareH5, targetUid: videoData?.userInfo?.uid, shareId: shareId)
        }
    }

    @objc func didBecomeActiveNotification() {
        if currentActionBtn != nil {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                cShowHUB(superView: nil, msg: "分享成功")
            }
            if currentActionBtn?.tag == 4 {
                if currentVideoData?.shareCountFriend != nil, currentVideoData?.shareCountFriend ?? 0 > 0 {
                    currentVideoData?.shareCountFriend = (currentVideoData?.shareCountFriend ?? 0) + 1
                } else {
                    currentVideoData?.shareCountFriend = 1
                }
            } else if currentActionBtn?.tag == 5 {
                if currentVideoData?.shareCount != nil, currentVideoData?.shareCount ?? 0 > 0 {
                    currentVideoData?.shareCount = (currentVideoData?.shareCount ?? 0) + 1
                } else {
                    currentVideoData?.shareCount = 1
                }
            }
            currentActionBtn = nil
            currentVideoData = nil
            (collectionView.visibleCell() as? MVPlayControlViewCell)?.addData()
//            collectionView.reloadData()
        }
        let navVc: UINavigationController? = (UIApplication.shared.keyWindow?.rootViewController) as? UINavigationController
        if navVc?.visibleViewController is MVPlayViewController {
            scrollViewDidEndDecelerating(collectionView)
        }
    }

    @objc func enterBackground() {
        BFLog(message: "进入到后台")
        let navVc: UINavigationController? = (UIApplication.shared.keyWindow?.rootViewController) as? UINavigationController
        if navVc?.visibleViewController is MVPlayViewController {
            (collectionView.visibleCell() as? MVPlayControlViewCell)?.pauseClick(isHidden: false)
            PQSingletoVideoPlayer.shared.stopPlayer(isRemove: false)
        }
    }

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

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
