CNLiveShortVideoViewController.swift 18.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
//
//  CNLiveVideoViewController.swift
//  metaCode
//
//  Created by open on 2024/1/5.
//

import Foundation
import ZFPlayer
import APButton
import EmptyDataSet_Swift
import MJRefresh
import CNLiveBusinessTools
import CNLiveShareToolKit

class CNLiveShortVideoViewController : CNLiveBaseViewController, UITableViewDelegate, UITableViewDataSource, CNLiveShortVideoListTableViewCellDelegate, EmptyDataSetSource, EmptyDataSetDelegate {
    
    var player: ZFPlayerController!
    let kVideoBodyListViewCellIdentifier = "kVideoBodyListViewCellIdentifier"
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        tableView.isPagingEnabled = true
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.frame = view.bounds
        tableView.rowHeight = tableView.frame.size.height
        tableView.backgroundColor = .black
        tableView.tableFooterView = UIView.init()
        tableView.separatorStyle = .none
        tableView.scrollsToTop = false
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never;
        } else {
            self.automaticallyAdjustsScrollViewInsets = false;
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(CNLiveShortVideoListTableViewCell.self, forCellReuseIdentifier: kVideoBodyListViewCellIdentifier)
        return tableView
    }()
    
    lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "short_video_close"), for: .normal)
        button.addTarget(self, action: #selector(backClick(_:)), for: .touchUpInside)
        return button
    }()
    
    lazy var controlView: CNLiveShortVideoControlView = {
        let controlView = CNLiveShortVideoControlView.init(frame: CGRectZero)
        return controlView
    }()
    
    lazy var headerRefreshView: UIRefreshControl = {
        let headerRefreshView = UIRefreshControl()
        headerRefreshView.tintColor = .white
        headerRefreshView.addTarget(self, action: #selector(headerRefresh), for: .valueChanged)
        return headerRefreshView
    }()
    
    lazy var dataArray: NSMutableArray = {
        let dataArray = NSMutableArray.init()
        return dataArray
    }()
    lazy var dataURLArray: NSMutableArray = {
        let dataArray = NSMutableArray.init()
        return dataArray
    }()
    

    var aid: String! = ""
    var pageNum: NSInteger! = 1
    var isSelectable: Bool! = false
    var currentIndex: NSInteger! = 0
    var footerRefreshView: CNLiveFooterRefresh!
    var playerManager = ZFIJKPlayerManager.init()
//    var playerManager = ZFAVPlayerManager.init()
    
    /// 初始化播放器
    /// - Parameters:
    ///   - aid: 专辑 id
    ///   - page: 当前页数
    ///   - currentIndex: 当前点击的索引
    ///   - dataArray: 当前请求的数据
    init(aid: String,page: NSInteger, currentIndex: NSInteger, dataArray: [CNLiveAlbumListModel]) {
        self.aid = aid
        self.pageNum = page
        self.isSelectable = true
        self.currentIndex = currentIndex
        super.init(nibName:nil, bundle:nil)
        self.dataArray.addObjects(from: dataArray)
        dataArray.forEach {[weak self] listModel in
            guard let self = self else { return }
            self.dataURLArray.add(listModel.videoUrl)
        }
    }
    
    /// 初始化播放器
    /// - Parameter aid: 专辑 id
    init(aid: String) {
        self.aid = aid
        self.isSelectable = false
        super.init(nibName:nil, bundle:nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.dataArray.count > 0 && self.isSelectable {
            self.playTheIndex(index: self.currentIndex)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.player.currentPlayerManager.play()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.player.currentPlayerManager.pause()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        view.addSubview(tableView)
        view.addSubview(backBtn)
        
        if self.dataArray.count == 0 {
            requestData {}
        }

        addRefreshView()

        player = ZFPlayerController(scrollView: tableView, playerManager: playerManager, containerViewTag: 100)
        player.disableGestureTypes = [.pan, .pinch]
        player.controlView = controlView
        player.allowOrentitaionRotation = false
        player.isWWANAutoPlay = true
        player.playerDisapperaPercent = 1.0
        player.playerDidToEnd = { [weak self] asset in
            guard let self = self else { return }
            self.player.currentPlayerManager.replay()
        }
        player.playerReadyToPlay = {[weak self] asset, assetURL in
            guard let self = self else { return }
            self.controlView.videoPlayer((self.player)!, currentTime: self.player.currentTime, totalTime: self.player.totalTime)
            let index = self.dataURLArray.index(of: assetURL.absoluteString)
            let homeModel = self.dataArray[index] as! CNLiveAlbumListModel
            self.currentIndex = index
            if homeModel.product?.check == false {
                if homeModel.product?.productType == "4" {
                    //这里表示可以进行试听
                } else {
                    (self.player)!.stopCurrentPlayingCell()
                }
            }
        }
        // 更新另一个控制层的时间
        player.playerPlayTimeChanged = { [weak self] asset, currentTime, duration in
            guard let self = self else { return }
            self.controlView.videoPlayer((self.player)!, currentTime: currentTime, totalTime: duration)
        }
        // 更新另一个控制层的缓冲时间
        player.playerBufferTimeChanged = { [weak self] asset, bufferTime in
            guard let self = self else { return }
            self.controlView.videoPlayer((self.player)!, bufferTime: bufferTime)
        }
        // 停止的时候找出最合适的播放
        player.zf_scrollViewDidEndScrollingCallback = { [weak self] indexPath in
            guard let self = self else { return }
            if self.player.playingIndexPath != nil {
                return
            }
            self.playVideo(at: indexPath)
        }
        player.playerDidToEnd = {[weak self] asset in
            guard let self = self else { return }
            self.controlView.videoPlayer((self.player)!)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(removePlayerAction), name: Notification.Name.PlayerManage.kPlayerDestroyNotification, object: nil)
    }
    
    func addRefreshView() {
        self.tableView.refreshControl = headerRefreshView
        footerRefreshView = CNLiveFooterRefresh(refreshingBlock: { [weak self] in
            guard let self = self else { return }
            self.player.stopCurrentPlayingCell()
            self.currentIndex = 0
            self.pageNum += 1
            self.requestData {}
        })
        //预加载下
        CNLiveQQEmotionManager.emotionsForQQ()
    }
    
    @objc func headerRefresh() {
        self.pageNum = 1
        self.requestData {}
    }
    
    @objc func removePlayerAction() {
        controlView.removeFromSuperview()
        if player != nil {
            player.stopCurrentPlayingCell()
        }
        if (playerManager.player != nil) {
            playerManager.player.stop()
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.backBtn.frame = CGRectMake(15, KStatusBarHeight + 15, 45, 45)
    }
    
    func requestData(resultBlock: @escaping () -> Void) {
        CNLiveShortVideoViewModel.requstWithShortVideo(aid: self.aid, page: self.pageNum) { [weak self] result, respStatue in
            guard let self = self else { return }
            if respStatue == .success {
                if self.pageNum == 1 {
                    self.dataArray.removeAllObjects()
                    self.dataURLArray.removeAllObjects()
                    if self.currentIndex == 0 {
                        self.tableView.setContentOffset(CGPoint.zero, animated: false)
                    }
                }
                let listArray = (result as! [Any]).first as! [CNLiveAlbumListModel]
                self.dataArray.addObjects(from: listArray)
                let urlArray = (result as! [Any]).last as! [String]
                self.dataURLArray.addObjects(from: urlArray)
                if self.tableView.mj_footer != nil {
                    self.tableView.mj_footer?.endRefreshing()
                }
                self.tableView.refreshControl?.endRefreshing()
                self.tableView.reloadData()
                if self.pageNum == 1 {
                    DispatchQueue.main.async {
                        self.tableView.contentOffset = CGPoint.zero
                    }
                }
                let hasNextPage = (result as! [Any])[1] as! Bool
                if listArray.count == 0 && urlArray.count == 0 {
                    if !hasNextPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        self.tableView.reloadData()
                    }
                } else {
                    if self.tableView.mj_footer == nil  {
                        self.tableView.mj_footer = footerRefreshView
                    }
                }
                if self.pageNum == 1 {
                    self.playTheIndex(index: self.currentIndex)
                } else {
                    self.playTheIndex(index: (self.pageNum - 1)*10)
                }
            } else {
                if self.tableView.mj_footer != nil {
                    self.tableView.mj_footer?.endRefreshing()
                }
                self.tableView.contentOffset = CGPoint.zero
                self.tableView.refreshControl?.endRefreshing()
                if self.dataArray.count == 0 {
                    self.tableView.reloadEmptyDataSet()
                }
            }
        }
    }
    
    open func playTheIndex(index: NSInteger) {
        // 指定到某一行播放
        let indexPath = IndexPath(row: index, section: 0)
        tableView.scrollToRow(at: indexPath, at: .none, animated: false)

        // 使用zf_filterShouldPlayCellWhileScrolled过滤播放
        self.player.zf_filterShouldPlayCellWhileScrolled { [weak self] indexPath in
            guard let self = self else { return }
            self.playVideo(at: indexPath)
        }
    }

    override var shouldAutorotate: Bool {
        return false
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    @objc func backClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    func playVideo(at indexPath: IndexPath) {
        let data: CNLiveAlbumListModel = dataArray[indexPath.row] as! CNLiveAlbumListModel
        self.player.playTheIndexPath(indexPath, assetURL: URL(string: data.videoUrl)!)
        controlView.resetControlView()
        controlView.showCoverView(withUrl: data.poster)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        tableView.delegate = nil
        tableView.dataSource = nil
        controlView.removeFromSuperview()
        player.stopCurrentPlayingCell()
        if (playerManager.player != nil) {
            playerManager.player.stop()
        }
        print("销毁了")
    }
}
extension CNLiveShortVideoViewController {
    
    func likeActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        CNLiveShortVideoViewModel.requestRankWithLike(contentId: viewcell.homeModel.pid, contentTitle: viewcell.homeModel.title, contentSid: viewcell.homeModel.icon!.id, support: viewcell.homeModel.tool!.liked, isShare: false) {result, respStatue in
            if respStatue == .success {
                viewcell.homeModel.tool!.liked = !viewcell.homeModel.tool!.liked
                if viewcell.homeModel.tool!.liked {
                    viewcell.homeModel.tool?.likesNum = "\(Int(viewcell.homeModel.tool!.likesNum)! + 1)"
                } else {
                    viewcell.homeModel.tool?.likesNum = "\(Int(viewcell.homeModel.tool!.likesNum)! - 1)"
                }
                button.setTitle(viewcell.homeModel.tool?.likesNum, for: .normal)
                button.isSelected = viewcell.homeModel.tool!.liked
            }
        }
    }
    func commentActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        CNLiveShortVideoCommentListView.showVideoCommentListView(pid: viewcell.homeModel.pid, contentSid: viewcell.homeModel.icon!.id, result: { commentModel in
            button.setTitle("\(commentModel)", for: .normal)
        })
    }
    func shareActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        CNLiveShareManager.showShareViewWithParam(forShareTitle: viewcell.homeModel.title, shareUrl: viewcell.homeModel.shareUrl, shareDesc: viewcell.homeModel.subTitle, shareImage: viewcell.homeModel.poster, screenFull: false, hiddenWjj: true, hiddenQQ: false, hiddenWB: true, hiddenLifeCircle: true, hiddenWechatCircle: false, hiddenWechat: false, hiddenSafari: true, formVC: self, topImage: [], topTitles: [], platformType: .all) { title in} completerBlock: {resultType, platformType, typeString in
            if resultType == .succ {
                showLoading(message: "")
                CNLiveShortVideoViewModel.requestRankWithLike(contentId: viewcell.homeModel.pid, contentTitle: viewcell.homeModel.title, contentSid: viewcell.homeModel.icon!.id, support: true, isShare: true) {result, respStatue in
                    if respStatue == .success {
                            viewcell.homeModel.tool?.shareNum = "\(Int(viewcell.homeModel.tool!.shareNum)! + 1)"
                        button.setTitle(viewcell.homeModel.tool?.shareNum, for: .normal)
                    }
                }
            }
        }
    }
    func iconActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        self.navigationController?.pushViewController(CNLivePlayletHomePageController(aid: aid), animated: true)
    }
    func faviActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: APButton) {
        button.startAnimating()
        CNLiveShortVideoViewModel.requestCollect(aid: aid, type: viewcell.homeModel.tool!.collectioned) { result, respStatue in
            if respStatue == .success {
                showMessage(message: result as! String)
                viewcell.homeModel.tool!.collectioned = !viewcell.homeModel.tool!.collectioned
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    button.isHidden = true
                }
            }
        }
    }
    func listActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        CNLiveShortVideoContentListView.showVideoContentListView(title: viewcell.homeModel.albumMsgModel!.albumName,dataArray: dataArray, result: {[weak self] listModel in
            guard let self = self else { return }
            let index = self.dataArray.index(of: listModel) as NSInteger
            self.playTheIndex(index: index)
        })
    }
    func payActionMethod(viewcell: CNLiveShortVideoListTableViewCell, button: UIButton) {
        let payButton = button as! APButton
        payButton.startAnimating()
        CNLiveIntegralAlertTool.shared.showIntegralAlert(title: "\(viewcell.homeModel.albumMsgModel?.albumName ?? "")\(viewcell.homeModel.albumMsgModel?.episodeNow ?? "1")集", integralCount: viewcell.homeModel.albumMsgModel?.product?.point ?? "0", productId: viewcell.homeModel.product?.productId ?? "")
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            payButton.stopAnimating()
        }
        CNLiveIntegralAlertTool.shared.homePageNeedReloadActionBlock = {[weak self] in
            guard let self = self else { return }
            payButton.stopAnimating()
            for item in self.dataArray {
                let homeModel = item as! CNLiveAlbumListModel
                homeModel.product!.check = true
                self.tableView.reloadData()
            }
            let index = self.dataArray.index(of: viewcell.homeModel as Any)
            self.playTheIndex(index: index)
        }
        CNLiveIntegralAlertTool.shared.integralStatusChangedBlock = {[weak self] integralPayStatus in
            if integralPayStatus == .integralNotEnough{
                //取消刷新
            }
        }
    }
}

extension CNLiveShortVideoViewController {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: kVideoBodyListViewCellIdentifier) as? CNLiveShortVideoListTableViewCell else {
            return CNLiveShortVideoListTableViewCell()
        }
        cell.delegate = self
        cell.setupWithData(model: dataArray[indexPath.row] as! CNLiveAlbumListModel)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.playVideo(at: indexPath)
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "short_video_default")
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScroll()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
    
    func zf_playTheVideo(at indexPath: IndexPath) {
        self.playVideo(at: indexPath)
    }
}