//
//  PQStuckPointMusicContentCell.swift
//  PQSpeed
//
//  Created by SanW on 2021/4/28.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import BFCommonKit
import BFMediaKit
import BFUIKit
import UIKit

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

    lazy var audioImageView: UIImageView = {
        let audioImageView = UIImageView(image: BFStuckPointImage(by: "videomk_music_default")!)
        audioImageView.addCorner(corner: 4)
        audioImageView.contentMode = .scaleAspectFill
        return audioImageView
    }()

    lazy var imageMaskView: UIView = {
        let imageMaskView = UIView()
        imageMaskView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
        imageMaskView.addCorner(corner: 4)
        return imageMaskView
    }()

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

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

    /// 音乐歌曲名称
    lazy var musicNameLab: LMJHorizontalScrollText = {
        let musicNameLab = LMJHorizontalScrollText(frame: CGRect(x: 0, y: 0, width: cDefaultMargin * 6, height: cDefaultMargin * 3))
        musicNameLab.textColor = BFConfig.shared.styleTitleColor
        musicNameLab.textFont = UIFont.systemFont(ofSize: 16)
        musicNameLab.speed = 0.03
        musicNameLab.moveDirection = LMJTextScrollMoveLeft
        musicNameLab.moveMode = LMJTextScrollContinuous
        musicNameLab.stop()
        return musicNameLab
    }()

    // 使用按钮
    lazy var confirmContentView: UIView = {
        let confirmContentView = UIView()
        confirmContentView.backgroundColor = BFConfig.shared.styleBackGroundColor
        let ges = UITapGestureRecognizer(target: self, action: #selector(confirmClick))
        confirmContentView.addGestureRecognizer(ges)
        confirmContentView.isHidden = true
        return confirmContentView
    }()

    // 使用按钮
    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.isUserInteractionEnabled = false
        confirmBtn.addCorner(corner: 5)
        confirmBtn.backgroundColor = UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue)
        return confirmBtn
    }()

    lazy var remindView: UIView = {
        let remindView = UIView()
        remindView.backgroundColor = UIColor.hexColor(hexadecimal: BFConfig.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(confirmContentView)
        confirmContentView.addSubview(confirmBtn)
        PQNotification.addObserver(forName: Notification.Name(rawValue: "MusicContentCellIconLoadingAnimationStop"), object: nil, queue: .main) { [weak self] _ in
            if !(self?.imageMaskView.isHidden ?? true) {
                self?.stopLoadingAnimation()
            }
        }
    }

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

    deinit {
        PQNotification.removeObserver(self)
    }

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

    func addData() {
        imageMaskView.isHidden = !(bgmData is PQVoiceModel) || BFConfig.shared.hiddenMusicMask
        musicNameLab.isHidden = !(bgmData is PQVoiceModel)
        titleLab.isHidden = (bgmData is PQVoiceModel)
        if bgmData is PQVoiceModel {
            audioImageView.setNetImage(url: "\((bgmData as? PQVoiceModel)?.avatarUrl ?? "")", placeholder: BFStuckPointImage(by: "videomk_music_default")!)
            confirmContentView.isHidden = !((bgmData as? PQVoiceModel)?.isSelected ?? false)
            if (bgmData as? PQVoiceModel)?.isSelected ?? false {
                imageMaskView.isHidden = false
                playImageView.isHidden = false
                if (bgmData as? PQVoiceModel)?.isPlaying ?? false {
                    if playImageView.image == nil {
                        playImageView.image = UIImage.moduleImage(named: "loading", moduleName: "BFStuckPointKit", isAssets: false)
                        startLoadingAnimation()
                    } else {
                        playImageView.kf.setImage(with: URL(fileURLWithPath: currentBundlePath()!.path(forResource: "stuckPoint_music_playing", ofType: ".gif")!))
                    }
                    musicNameLab.move()
                } else {
                    playImageView.image = UIImage.moduleImage(named: "stuckPoint_music_pause", moduleName: "BFStuckPointKit", isAssets: false)
                    musicNameLab.stop()
                }
            } else {
                playImageView.isHidden = true
                playImageView.image = nil
                musicNameLab.stop()
            }
        } else {
            if (bgmData as? PQStuckPointMusicTagsModel)?.tagEmoji != nil {
                audioImageView.setNetImage(url: "\((bgmData as? PQStuckPointMusicTagsModel)?.tagEmoji ?? "")", placeholder: BFStuckPointImage(by: "videomk_music_default")!)
            } else {
                audioImageView.image = BFStuckPointImage(by: "videomk_music_default")
            }
            titleLab.text = " \((bgmData as? PQStuckPointMusicTagsModel)?.tagName ?? "")"
            if (titleLab.text?.count ?? 0) > 8 {
                titleLab.font = UIFont.systemFont(ofSize: 8)
            } else if (titleLab.text?.count ?? 0) > 7 {
                titleLab.font = UIFont.systemFont(ofSize: 10)
            } else if (titleLab.text?.count ?? 0) > 6 {
                titleLab.font = UIFont.systemFont(ofSize: 11)
            } else {
                titleLab.font = UIFont.systemFont(ofSize: 14)
            }
            contentView.backgroundColor = ((bgmData as? PQStuckPointMusicTagsModel)?.isSelected ?? false) ? BFConfig.shared.styleBackGroundColor : BFConfig.shared.otherTintColor
            titleLab.textColor = ((bgmData as? PQStuckPointMusicTagsModel)?.isSelected ?? false) ? UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue) : BFConfig.shared.styleTitleColor
            remindView.isHidden = !((bgmData as? PQStuckPointMusicTagsModel)?.isSelected ?? false)
        }
    }

    func addLayout() {
        let margin: CGFloat = 12
        let leftmargin: CGFloat = 16
        let imageW: CGFloat = bgmData is PQVoiceModel ? 55 : 22
        if bgmData is PQVoiceModel {
            var nameW: CGFloat = sizeWithText(text: (bgmData as? PQVoiceModel)?.musicName ?? "", font: UIFont.systemFont(ofSize: 16), size: CGSize(width: frame.width - leftmargin - imageW - margin * 2, height: cDefaultMargin * 3)).width
            if nameW < cDefaultMargin * 3 {
                musicNameLab.text = "\((bgmData as? PQVoiceModel)?.musicName ?? "")              "
                nameW = cDefaultMargin * 6
            } else if nameW < cDefaultMargin * 6 {
                musicNameLab.text = "\((bgmData as? PQVoiceModel)?.musicName ?? "")        "
                nameW = cDefaultMargin * 6
            } else {
                musicNameLab.text = "\((bgmData as? PQVoiceModel)?.musicName ?? "") "
            }
            audioImageView.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(leftmargin)
                make.centerY.equalToSuperview()
                make.width.height.equalTo(imageW)
            }
            imageMaskView.snp.makeConstraints { make in
                make.size.equalToSuperview()
            }
            playImageView.snp.remakeConstraints { make in
                make.center.equalToSuperview()
                make.width.height.equalTo(cDefaultMargin * 2)
            }

            musicNameLab.snp.remakeConstraints { make in
                make.left.equalTo(audioImageView.snp.right).offset(margin)
                make.width.equalTo(nameW)
                make.height.equalTo(cDefaultMargin * 3)
                make.centerY.equalToSuperview()
            }
            confirmContentView.snp.remakeConstraints { make in
                make.right.equalToSuperview()
                make.centerY.equalToSuperview()
                make.width.equalTo(85)
                make.height.equalTo(55)
            }
            confirmBtn.snp.remakeConstraints { make in
                make.right.equalToSuperview().offset(-leftmargin)
                make.centerY.equalToSuperview()
//                make.width.equalTo(confirmBtn)
                make.height.equalTo(cDefaultMargin * 3)
            }
            audioImageView.addCorner(corner: imageW / 2)
            imageMaskView.addCorner(corner: imageW / 2)
        } else {
            audioImageView.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(cDefaultMargin)
                make.centerY.equalToSuperview()
                make.width.height.equalTo(imageW)
            }
            remindView.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(-4)
                make.width.equalTo(8)
                make.height.equalTo(22)
                make.centerY.equalToSuperview()
            }
            titleLab.snp.remakeConstraints { make in
                make.left.equalTo(audioImageView.snp.right)
                make.right.equalToSuperview().offset(-margin)
                make.centerY.equalToSuperview()
            }
        }
    }

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

    func startLoadingAnimation() {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.toValue = Double.pi * 2
        rotateAnimation.duration = 1
        rotateAnimation.repeatCount = .infinity
        playImageView.layer.add(rotateAnimation, forKey: nil)
    }

    func stopLoadingAnimation() {
        playImageView.layer.removeAllAnimations()
        if (bgmData as? PQVoiceModel)?.isPlaying ?? false {
            playImageView.kf.setImage(with: URL(fileURLWithPath: currentBundlePath()!.path(forResource: "stuckPoint_music_playing", ofType: ".gif")!))
        }
    }
}
