//
//  MPPositive_HomeSinglesTableViewCell.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/7/4.
//

import UIKit
///首页单曲组展示Cell
class MPPositive_HomeSinglesTableViewCell: UITableViewCell, UIViewControllerTransitioningDelegate {
    //标题
    private lazy var titleLabel:UILabel = createLabel("Title", font: .systemFont(ofSize: 18*width, weight: .regular), textColor: .white, textAlignment: .left)
    private lazy var layout:UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = .init(width: screen_Width*0.85, height: 70*width)
        layout.sectionInset = .init(top: 10*width, left: 16*width, bottom: 0, right: 16*width)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        return layout
    }()
    //collectionView
    private lazy var collectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(MPPositive_HomeSingleCollectionViewCell.self, forCellWithReuseIdentifier: MPPositive_HomeSingleCollectionViewCellID)
        return collectionView
    }()
    private let MPPositive_HomeSingleCollectionViewCellID = "MPPositive_HomeSingleCollectionViewCell"
    ///预览模块
    var browseViewModel:MPPositive_BrowseModuleListViewModel!{
        didSet{
            titleLabel.text = browseViewModel.title
            collectionView.reloadData()
        }
    }

    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        confirgue()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    //配置
    private func confirgue() {
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16*width)
            make.top.equalToSuperview().offset(8*width)
            make.right.equalToSuperview().offset(-16*width)
        }
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-32*width).priority(999)
        }
    }
    //经过计算设置tableViewCell真实高度
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
        collectionView.layoutIfNeeded()
        let height = layout.itemSize.height*3 + layout.sectionInset.top + 10
        return CGSize(width: size.width, height: size.height + height)
    }
}
//MARK: - collectionView
extension MPPositive_HomeSinglesTableViewCell:UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return browseViewModel.items.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MPPositive_HomeSingleCollectionViewCellID, for: indexPath) as! MPPositive_HomeSingleCollectionViewCell
        cell.itemViewModel = browseViewModel.items[indexPath.row]
        cell.moreBlock = {
            [weak self] in
            guard let self = self else {return}
            let itemView = self.browseViewModel.items[indexPath.row]
            MPPositive_Debouncer.shared.call {
                MPPositive_ModalType = .MoreOperations
                let moreVC = MPPositive_MoreSongOperationsViewController(itemView)
                moreVC.disMissBlock = {
                    DispatchQueue.main.async {
                        collectionView.reloadData()
                    }
                }
                moreVC.transitioningDelegate = self
                moreVC.modalPresentationStyle = .custom
                self.parentController()?.present(moreVC, animated: true)
            }
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //单曲/视频跳转
        MPPositive_Debouncer.shared.call {
            [weak self] in
            guard let self = self else {return}
            guard MP_NetWorkManager.shared.netWorkStatu == .reachable else {
                MP_HUD.text("Weak connection.", delay: 2.0, completion: nil)
                return
            }
            let item = self.browseViewModel.items[indexPath.row]
            MP_AnalyticsManager.shared.home_b_module_clickAction(item.browseItem.pageType ?? "")
            MP_AnalyticsManager.shared.song_clickAction("Home")
            //优先清除数据
            MP_PlayerManager.shared.loadPlayer = nil
            //弹出播放器
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
            MP_AnalyticsManager.shared.player_b_impAction()
            //触发next请求，优先获取列表全部单曲基础数据（不完善）
            MP_NetWorkManager.shared.requestNextList(item.browseItem.playListId ?? "", videoId: item.browseItem.videoId ?? ""){ [weak self] listSongs in
                guard let self = self else {return}
                //回掉的数据并不完善，生成一个playerloadViewModel
                let lodaViewModel = MPPositive_PlayerLoadViewModel(listSongs, currentVideoId: item.browseItem.videoId ?? "")
                lodaViewModel.improveData(item.browseItem.videoId ?? "")
                //更改播放器播放类型
                MP_PlayerManager.shared.setPlayType(.normal)
                MP_PlayerManager.shared.loadPlayer = lodaViewModel
                MP_AnalyticsManager.shared.player_b_listAction()
            }
        }
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
