//
//  PQSelecteMusic.swift
//  BFFramework
//
//  Created by ak on 2021/8/4.
//  功能：显示编辑界面里的音乐选择界面

import Foundation

class PQSelecteMusicView: UIView {
    // 所有分类数据
    var catageryDatas: [PQStuckPointMusicTagsModel] = Array<PQStuckPointMusicTagsModel>.init()

    // 歌单数据
    var musicDatas: [PQVoiceModel] = Array<PQVoiceModel>.init()
    // 当前页码
    var pageNum: Int = 0
    
    // 当前视频使用的音乐数据
    var currentPlayingInVideoData : PQVoiceModel?
    // 当前试听播放的音乐数据
    var currentPlayData: PQVoiceModel?
    // 当前播放的音频
    var playerItem: AVPlayerItem?
    var playerItemHavObserver: Bool = false
    
    // 按钮点击的回调
    var btnClickHandle: ((_ sender: UIButton, _ bgmData: Any?) -> Void)?
    
    // 点击播放一个歌，回调
    var didSelectItemHandle:((_ statue:voiceStatue) -> Void)?
    // 当前选择的分类
    var currentSelectTag:PQStuckPointMusicTagsModel?
    
    //搜索出来的歌曲要插入到热门的前面 有可能是多个
    var searchMusiceDatas: [PQVoiceModel] = Array<PQVoiceModel>.init()
    
    //第一次进入时自动插入的数据
    var firstInsertVoiceModel:PQVoiceModel?
 
    lazy var avPlayer: AVPlayer = {
        let avPlayer = AVPlayer()
        PQNotification.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem, queue: .main) { [weak self] notify in
            BFLog(message: "AVPlayerItemDidPlayToEndTime = \(notify)")
            avPlayer.seek(to: CMTime(value: CMTimeValue((self?.currentPlayData?.startTime ?? 0) * 1000), timescale: CMTimeScale(playerTimescale)))
            
            if(self?.currentPlayData?.voiceStatue == .isPlaying){
                self?.currentPlayData?.voiceStatue = .isPause
                self?.selectMusicCollection.reloadData()
            }
           
        }
//        PQNotification.addObserver(forName: .AVPlayerItemNewErrorLogEntry, object: avPlayer.currentItem, queue: .main) { notify in
//            BFLog(message: "AVPlayerItemNewErrorLogEntry = \(notify)")
//        }
//        PQNotification.addObserver(forName: .AVPlayerItemFailedToPlayToEndTime, object: avPlayer.currentItem, queue: .main) { notify in
//            BFLog(message: "AVPlayerItemFailedToPlayToEndTime = \(notify)")
//        }
//        PQNotification.addObserver(forName: .AVPlayerItemPlaybackStalled, object: avPlayer.currentItem, queue: .main) { notify in
//            BFLog(message: "AVPlayerItemPlaybackStalled = \(notify)")
//        }
//        avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: CMTimeScale(playerTimescale)), queue: .main) { [weak self] cmTime in
//            BFLog(message: "addPeriodicTimeObserver = \(cmTime)")
//        }
        return avPlayer
    }()
    
    // 音乐分类的
    lazy var categoryCollection: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets.zero
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal

        let categoryCollection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        categoryCollection.showsVerticalScrollIndicator = false
        categoryCollection.showsHorizontalScrollIndicator = false
        categoryCollection.delegate = self
        categoryCollection.dataSource = self
        categoryCollection.backgroundColor = .clear
        categoryCollection.register(PQSelectMusicTagsCell.self, forCellWithReuseIdentifier: "PQSelectMusicTagsCell")
        categoryCollection.delaysContentTouches = false

        return categoryCollection
    }()

    // 每一个分类下所有歌曲
    lazy var selectMusicCollection: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets.zero
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal

        let selectMusicCollection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        selectMusicCollection.showsVerticalScrollIndicator = false
        selectMusicCollection.showsHorizontalScrollIndicator = false
        selectMusicCollection.delegate = self
        selectMusicCollection.dataSource = self
        selectMusicCollection.backgroundColor = .clear
        selectMusicCollection.register(PQSelectMusicCell.self, forCellWithReuseIdentifier: String(describing: PQSelectMusicCell.self))
        selectMusicCollection.delaysContentTouches = false
        selectMusicCollection.contentInset = UIEdgeInsets(top: 0, left: 17, bottom: 0, right: 0)
        return selectMusicCollection
    }()

    // 搜索音乐btn
    lazy var musicSearchBtn: UIButton = {
        let musicSearchBtn = UIButton(type: .custom)
        musicSearchBtn.setTitle("搜索", for: .normal)
        musicSearchBtn.setImage(UIImage().BF_Image(named: "musicSearch"), for: .normal)
        musicSearchBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#959595"), for: .normal)
        musicSearchBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)

        return musicSearchBtn
    }()
    
    deinit {
        PQNotification.removeObserver(self)
        PQNotification.removeObserver(self.avPlayer.currentItem as Any)
        if playerItemHavObserver {
            avPlayer.currentItem?.removeObserver(self, forKeyPath: "status")
            avPlayer.currentItem?.removeObserver(self, forKeyPath: "error")
        }
        avPlayer.pause()
        avPlayer.replaceCurrentItem(with: nil)
        playerItem = nil
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(categoryCollection)
        addSubview(selectMusicCollection)
        addSubview(musicSearchBtn)
    }
    func showData(){
        
        autolayout()

        isHidden = false
        //不是每一次点击都显示数据
        if(musicDatas.count == 0){
            loadRequestTagsList()
        }
     
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //插入数据
    func insertSearchMusic(model:PQVoiceModel) {
      
        for oldModel in musicDatas {
            oldModel.voiceStatue = .isNormal
        }
   
        let musicIndex = musicDatas.firstIndex(where: { (music) -> Bool in
            (music.musicId == model.musicId)
        })
        
        if(musicIndex == nil){
            model.voiceStatue = .isSelected
            searchMusiceDatas.insert(model, at: 0)
            //有搜索的数据
            if(currentSelectTag?.tagId == 425){
                musicDatas.insert(model, at: 0)
            }
        }else{
            
            let selectMusicData = musicDatas[musicIndex!]
            selectMusicData.voiceStatue = .isSelected
            musicDatas.remove(at: musicIndex!)
            musicDatas.insert(selectMusicData, at: 0)
        }
        self.currentPlayingInVideoData = model
        selectMusicCollection.reloadData()
       
        //划动到选择的音乐位置
        selectMusicCollection.scrollToItem(at: IndexPath(row: 0, section: 0), at: .centeredHorizontally, animated: true)
 
    }
    func autolayout() {
        categoryCollection.snp.removeConstraints()
        selectMusicCollection.snp.removeConstraints()
        musicSearchBtn.snp.removeConstraints()

        categoryCollection.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.left.equalToSuperview().offset(91)
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(14)
        }
        selectMusicCollection.snp.makeConstraints { make in
            make.height.equalTo(131)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(54)
        }

        musicSearchBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.top.equalToSuperview().offset(14)
            make.height.equalTo(20)
            make.width.equalTo(60)
        }
        musicSearchBtn.imagePosition(at: PQButtonImageEdgeInsetsStyle.left, space: 8)
    }

    /// 请求标签数据
    /// - Returns: <#description#>
    func loadRequestTagsList() {
        PQStuckPointViewModel.stuckPointMusicCategoryList { [weak self] tags, _, _ in

            if tags.count > 0 {
                // 请求列表数据
                self?.requestPageListData(isRefresh: true, tagId: tags.first?.tagId ?? 0)
                self?.catageryDatas = tags
                self?.currentSelectTag = tags[0]
                self?.categoryCollection.reloadData()
            }
        }
    }

    /// 请求指定分类的歌列表数据
    /// - Returns:
    func requestPageListData(isRefresh: Bool = true, isHotPage _: Bool = false, tagId: Int64) {
        if isRefresh {
            pageNum = 1
            musicDatas = []
        }
        PQStuckPointViewModel.stuckPointMusicPageList(tagId: tagId, pageNum: pageNum, videoCount: 0, imageCount: 0, totalDuration: 0,oldDataMusic: musicDatas) { [weak self] musicInfo, _ in
            BFLog(message: "请求音乐列表 pageNum\(String(describing: self?.pageNum)) tagId \(tagId) 返回条数\(musicInfo.count)")
            if musicInfo.count > 0 {
                self?.pageNum = (self?.pageNum ?? 0) + 1
                
                self?.musicDatas = self!.musicDatas + musicInfo
                
                //有搜索的数据
                if((self?.searchMusiceDatas.count ?? 0) > 0 && self!.musicDatas.first?.cacheTagID == 425 && self?.pageNum == 2){
                    self?.musicDatas.insert(contentsOf: self?.searchMusiceDatas ?? Array.init(), at: 0)
                   
                }
                
                if(self?.musicDatas.count ?? 0 > 0){
                    self?.selectMusicCollection.reloadData()
                }else{
                    BFLog(message: "分类歌曲数据为空！！！！")
                }
         
                if( self?.pageNum == 2){
                    //歌曲列表返回到头部
                    self?.selectMusicCollection.setContentOffset(.zero, animated: false)
                    
                    //第一次进入插入的歌曲，插入后置空 如果 不存在只插入一次 防止重
                    if(self?.firstInsertVoiceModel != nil){
                        self?.insertSearchMusic(model: (self?.firstInsertVoiceModel)!)
                        self?.currentPlayingInVideoData = self?.firstInsertVoiceModel
                        self?.firstInsertVoiceModel = nil
                    }
                    
                    
                }
           
            }

        }
    }
    
    /// 播放音乐
    /// - Parameter itemData: <#itemData description#>
    func playStuckPointMusic(itemData: PQVoiceModel?, isClearCurrentMusic: Bool = false) {
        if itemData != nil, currentPlayData != itemData {
            if !isValidURL(url: itemData?.musicPath ?? "") {
                cShowHUB(superView: nil, msg: "本歌曲暂无伴奏版本哦~")
                return
            }
            avPlayer.pause()
            if playerItemHavObserver {
                playerItem?.removeObserver(self, forKeyPath: "status")
                playerItem?.removeObserver(self, forKeyPath: "error")
                playerItemHavObserver = false
            }

            if itemData!.musicId == currentPlayingInVideoData?.musicId {
                itemData?.voiceStatue = .isSelected
                currentPlayData = itemData
                playerItem = nil
                return
            }
            
            playerItem = AVPlayerItem(url: URL(string: itemData?.musicPath ?? "")!)
            if (itemData?.endTime ?? 0) > 0, (itemData?.endTime ?? 0) > (itemData?.startTime ?? 0) {
                playerItem?.forwardPlaybackEndTime = CMTime(value: CMTimeValue((itemData?.endTime ?? 0) * playerTimescale), timescale: CMTimeScale(playerTimescale))
            }
            avPlayer.replaceCurrentItem(with: playerItem)
            playerItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
            playerItem?.addObserver(self, forKeyPath: "error", options: .new, context: nil)
            playerItemHavObserver = true
            avPlayer.seek(to: CMTime(value: CMTimeValue((itemData?.startTime ?? 0) * playerTimescale), timescale: CMTimeScale(playerTimescale)))
            avPlayer.play()
            itemData?.voiceStatue = .isPlaying

            currentPlayData = itemData
        } else if itemData != nil, avPlayer.rate == 0.0 {
            if itemData?.musicId != currentPlayingInVideoData?.musicId {
                avPlayer.play()
                itemData?.voiceStatue = .isPlaying
            }
        } else {
            avPlayer.pause()
            itemData?.voiceStatue = .isPause
      
        }
        if isClearCurrentMusic {
            avPlayer.pause()
            currentPlayData = nil
        }
    }
    
    //暂停播放音乐 并刷新 UI
    func pausePlayer() {
        avPlayer.pause()
        if(currentPlayData?.voiceStatue == .isPlaying){
            currentPlayData?.voiceStatue = .isPause
            selectMusicCollection.reloadData()
        }

    }
   
}

extension PQSelecteMusicView {
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
        if object is AVPlayerItem, keyPath == "status" {
            BFLog(message: "AVPlayerItem - status = \((object as! AVPlayerItem).status.rawValue)")
            switch (object as! AVPlayerItem).status {
            case .unknown:
                break
            case .readyToPlay:
                break
            case .failed:
                break
            default:
                break
            }
        } else if object is AVPlayerItem, keyPath == "error" {
            BFLog(message: "AVPlayerItem - error = \(String(describing: (object as! AVPlayerItem).error))")
        }
    }
}

/// 卡点音乐相关代理
extension PQSelecteMusicView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        if collectionView == selectMusicCollection {
            return musicDatas.count
        }
        return catageryDatas.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == selectMusicCollection {

            let itemData: Any = musicDatas[indexPath.item]
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQSelectMusicCell.self), for: indexPath) as! PQSelectMusicCell
            if (currentPlayingInVideoData?.musicId != nil && currentPlayingInVideoData?.musicId == (itemData as? PQVoiceModel)?.musicId){
                (itemData as? PQVoiceModel)?.voiceStatue = .isSelected
            }
            cell.bgmData = itemData as? PQVoiceModel
            cell.btnClickHandle = { [weak self] sender, bgmData in
                
                //暂停播放音乐
                self?.pausePlayer()
                self?.currentPlayingInVideoData?.voiceStatue = .isNormal
                self?.currentPlayingInVideoData = bgmData as? PQVoiceModel
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicSelect, pageSource: .sp_shanyinApp_main, extParams: ["musicName":(bgmData as? PQVoiceModel)?.musicName ?? "" ,"musicId":(bgmData as? PQVoiceModel)?.musicId ?? ""], remindmsg: "")
                
                if self?.btnClickHandle != nil {
                    self?.btnClickHandle!(sender, bgmData)
                    
                }
                //恢复原来状态
                if(self?.musicDatas.count != 0){
                    for oldModel in self!.musicDatas {
                        oldModel.voiceStatue = .isNormal
                    }
                }
             
                let musicIndex = self?.musicDatas.firstIndex(where: { (music) -> Bool in
                    (music.musicId == (bgmData as? PQVoiceModel)?.musicId)
                })
                
                self?.musicDatas[musicIndex ?? 0].voiceStatue = .isSelected

                self?.selectMusicCollection.reloadData()
            }
            
            //自动请求下一页数据
            if(indexPath.row == musicDatas.count - 5){
                // 请求这个分类的歌单
                requestPageListData(isRefresh: false, tagId:   currentSelectTag?.tagId ?? 0)
            }
            return cell
        }
        
        
        let itemData: Any = catageryDatas[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQSelectMusicTagsCell.self), for: indexPath) as! PQSelectMusicTagsCell
        cell.tagData = itemData as? PQStuckPointMusicTagsModel

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == selectMusicCollection {
            return CGSize(width: 60 + 20, height: 131)
        }
        // 音乐分类要根据文字自适应宽度
        let textSize = sizeWithText(text: catageryDatas[indexPath.item].tagName ?? "", font: UIFont.systemFont(ofSize: 14, weight: .regular), size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 20.0))

        return CGSize(width: textSize.width + 26, height: collectionView.frame.height)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //歌曲列表
        if (collectionView == selectMusicCollection ){
            musicDatas.forEach { item in
                item.voiceStatue = .isNormal
            }
            let music = musicDatas[indexPath.item]
            music.voiceStatue = .isSelected
//            if music.musicId != currentPlayingInVideoData?.musicId{
            playStuckPointMusic(itemData:music)
//            }else{
//                avPlayer.pause()
//            }
            PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_musicCategorySelect, pageSource: .sp_shanyinApp_main, extParams: ["categoryName":currentSelectTag?.tagName ?? "","categoryId":currentSelectTag?.tagId ?? ""], remindmsg: "")

//            if music.musicId != currentPlayingInVideoData?.musicId{
//                BFLog(1, message: "预览：\(music.musicName) 当前：\(currentPlayingInVideoData?.musicName)")
//            }
            if didSelectItemHandle != nil {
                didSelectItemHandle!(music.voiceStatue)
            }
            selectMusicCollection.reloadData()

         
        }else{
            //停止分类列表的滑动。防止切换分类时 crash
            selectMusicCollection.setContentOffset(selectMusicCollection.contentOffset , animated: false)
            if !isNetConnected() {
                cShowHUB(superView: nil, msg: "请有网时再试")
                return
            }

            catageryDatas.forEach { item in
                item.isSelected = false
            }
            catageryDatas[indexPath.item].isSelected = true
            categoryCollection.reloadData()
            currentSelectTag = catageryDatas[indexPath.item]
            // 请求这个分类的歌单
            requestPageListData(isRefresh: true, tagId:   currentSelectTag?.tagId ?? 0)
        }
   
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay _: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        if (collectionView == selectMusicCollection && musicDatas.count > indexPath.item ){
            let music = musicDatas[indexPath.item]
            
            PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonView, objectType: .ot_shanyinApp_musicVideoPreview_musicView, pageSource: .sp_shanyinApp_main, extParams: ["musicName":music.musicName ?? "" ,"musicId":music.musicId ?? ""], remindmsg: "")
        }
    }
}

// 分类 cell
class PQSelectMusicTagsCell: UICollectionViewCell {
    lazy var titleLab: UILabel = {
        let titleLab = UILabel()
        titleLab.font = UIFont.systemFont(ofSize: 14)
        titleLab.textColor = UIColor.hexColor(hexadecimal: "#959595")
        titleLab.textAlignment = .center
        titleLab.backgroundColor = PQBFConfig.shared.styleBackGroundColor
        return titleLab
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(titleLab)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var tagData: PQStuckPointMusicTagsModel? {
        didSet {
            addData()
            addLayout()
        }
    }

    func addData() {
        titleLab.text = "\(tagData?.tagName ?? "")"
        if tagData?.isSelected ?? false {
            titleLab.textColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
            titleLab.font = UIFont.boldSystemFont(ofSize: 14)

        } else {
            titleLab.textColor = UIColor.hexColor(hexadecimal: "#959595")
            titleLab.font = UIFont.systemFont(ofSize: 14)
        }
    }

    func addLayout() {
        titleLab.snp.makeConstraints { make in
            make.size.equalToSuperview()
            make.left.top.equalToSuperview()
        }
    }
}

// 歌曲cell PQSelectMusicCell
class PQSelectMusicCell: UICollectionViewCell {
    // 按钮点击的回调
    var btnClickHandle: ((_ sender: UIButton, _ bgmData: Any?) -> Void)?
    var contentType: stuckPointMusicContentType = .catagery

    lazy var audioImageView: UIImageView = {
        let audioImageView = UIImageView(image: UIImage().BF_Image(named: "videomk_music_default"))
        audioImageView.addCorner(corner: 4)
        audioImageView.contentMode = .scaleAspectFill
        return audioImageView
    }()

    lazy var imageMaskView: UIView = {
        let imageMaskView = UIView()
        imageMaskView.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue,alpha: 0.76)
        imageMaskView.addCorner(corner: 4)
        return imageMaskView
    }()

    lazy var playImageView: UIImageView = {
        let playImageView = UIImageView()
        playImageView.image = UIImage.moduleImage(named: "stuckPoint_music_pause", moduleName: "BFFramework",isAssets: false)
        playImageView.contentMode = .scaleAspectFit
        return playImageView
    }()

    lazy var titleLab: UILabel = {
        let titleLab = UILabel()
        titleLab.font = UIFont.systemFont(ofSize: 14)
        titleLab.textColor = PQBFConfig.shared.styleTitleColor
        return titleLab
    }()

    /// 音乐歌曲名称
    lazy var musicNameLab: UILabel = {
        let musicNameLab = UILabel()
        musicNameLab.textColor = UIColor.hexColor(hexadecimal: "#959595")
        musicNameLab.font = UIFont.systemFont(ofSize: 12)
        musicNameLab.textAlignment = .center
        musicNameLab.lineBreakMode = .byTruncatingTail
        musicNameLab.numberOfLines = 2
        return musicNameLab
    }()

    // 使用按钮
    lazy var confirmBtn: UIButton = {
        let confirmBtn = UIButton(type: .custom)
        confirmBtn.setTitle("使用", for: .normal)
        confirmBtn.setTitleColor(UIColor.white, for: .normal)
        confirmBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        confirmBtn.addTarget(self, action: #selector(confirmClick(sender:)), for: .touchUpInside)
        confirmBtn.addCorner(corner: 4)
        confirmBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        return confirmBtn
    }()

    lazy var remindView: UIView = {
        let remindView = UIView()
        remindView.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        remindView.addCorner(corner: 3)
        return remindView
    }()

    @objc class func stuckPointMusicContentCell(collectionView: UICollectionView, indexPath: IndexPath) -> PQStuckPointMusicContentCell {
        let cell: PQStuckPointMusicContentCell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQStuckPointMusicContentCell.self), for: indexPath) as! PQStuckPointMusicContentCell
        return cell
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(audioImageView)
        audioImageView.addSubview(imageMaskView)
        audioImageView.addSubview(playImageView)
        contentView.addSubview(titleLab)
        contentView.addSubview(musicNameLab)
        contentView.addSubview(remindView)
        contentView.addSubview(confirmBtn)
        
        
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var bgmData: PQVoiceModel? {
        didSet {
            addData()
            addLayout()
        }
    }

    func addData() {
        audioImageView.setNetImage(url: "\(bgmData?.avatarUrl ?? "")", placeholder: UIImage().BF_Image(named: "videomk_music_default"))
        
        if((bgmData?.musicName ?? "").count <= 4){
            musicNameLab.text = (bgmData?.musicName ?? "").appending("\n ")
        }else{
            musicNameLab.text = (bgmData?.musicName ?? "")
        }
     
        
        if  bgmData?.voiceStatue == .isSelected{
            playImageView.isHidden = false
            imageMaskView.isHidden = false
            playImageView.image = UIImage().BF_Image(named: "stuckPoint_music_selected")
    
        } else if  bgmData?.voiceStatue == .isPlaying{
            playImageView.isHidden = false
            imageMaskView.isHidden = false
            playImageView.image = nil
            playImageView.kf.setImage(with: URL(fileURLWithPath: currentBundlePath()!.path(forResource: "stuckPoint_music_playing", ofType: ".gif")!))
      
        } else if  bgmData?.voiceStatue == .isPause{
            playImageView.isHidden = false
            imageMaskView.isHidden = false
            playImageView.image = UIImage.moduleImage(named: "stuckPoint_music_pause", moduleName: "BFFramework",isAssets: false)
      
        }else {
            playImageView.isHidden = true
            playImageView.image = nil
            
            imageMaskView.isHidden = true
        }
        
//        if  bgmData?.voiceStatue == .isSelected{
//            playImageView.isHidden = false
//            imageMaskView.isHidden = false
//            if bgmData?.voiceStatue == .isPlaying {
//                playImageView.image = nil
//                playImageView.kf.setImage(with: URL(fileURLWithPath: currentBundlePath()!.path(forResource: "stuckPoint_music_playing", ofType: ".gif")!))
//
//            } else {
//                playImageView.image = UIImage.moduleImage(named: "stuckPoint_music_pause", moduleName: "BFFramework",isAssets: false)
//            }
//
//        } else {
//            playImageView.isHidden = true
//            playImageView.image = nil
//
//            imageMaskView.isHidden = true
//        }
        
        confirmBtn.isHidden = !(bgmData?.voiceStatue == .isPause || bgmData?.voiceStatue == .isPlaying)

        if(bgmData?.voiceStatue == .isSelected || bgmData?.voiceStatue == .isPause || bgmData?.voiceStatue == .isPlaying){
            musicNameLab.textColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
            musicNameLab.font = UIFont.boldSystemFont(ofSize: 12)
        }else{
            musicNameLab.textColor =  UIColor.hexColor(hexadecimal: "#959595")
            musicNameLab.font = UIFont.systemFont(ofSize: 12)
        }
        

    }

    func addLayout() {
      
        audioImageView.snp.remakeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.height.equalTo(60)
        }
        imageMaskView.snp.makeConstraints { make in
            make.size.equalTo(audioImageView)
        }
        playImageView.snp.remakeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(24)
        }

        musicNameLab.snp.remakeConstraints { make in
            make.width.equalTo(60)
            make.height.equalTo(30)
            make.top.equalTo(audioImageView.snp.bottom).offset(6)
        }
 
        confirmBtn.snp.remakeConstraints { make in
            make.width.equalTo(54)
            make.height.equalTo(29)
            make.top.equalTo(musicNameLab.snp.bottom).offset(6)
            make.centerX.equalTo(audioImageView.snp.centerX)
          
        }
        audioImageView.addCorner(corner: 60 / 2)
        imageMaskView.addCorner(corner: 60 / 2)
    }

    @objc func confirmClick(sender: UIButton) {
        if btnClickHandle != nil {
            btnClickHandle!(confirmBtn, bgmData)
        }
    }
}


