//
//  MPPositive_RecommendViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/20.
//

import UIKit
///相关内容推荐
class MPPositive_RecommendViewController: MPPositive_BaseViewController {
    //load模块
    private var loadRecommend:MPPositive_RecommendLoadViewModel!{
        didSet{
            if loadRecommend != nil {
                membersView.isHidden = false
                segmentView.isHidden = false
                listContainerView.isHidden = false
                loadRecommend.resultReloadBlock = {
                    [weak self] in
                    //刷新分页控制器
                    guard let self = self else {return}
                    sectionLabel.text = loadRecommend.members.title
                    collectionView.reloadData()
                    dataSource.titles = loadRecommend?.sectionLists.compactMap({$0.title}) ?? []
                    dataSource.reloadData(selectedIndex: 0)
                    segmentView.reloadData()
                }
            }else {
                membersView.isHidden = true
                segmentView.isHidden = true
                listContainerView.isHidden = true
            }
        }
    }
    //MARK: - 音乐人模块
    ///音乐人View
    private lazy var membersView:UIView = createMusicMembersView()
    //模块标题
    private lazy var sectionLabel:UILabel = createLabel(font: .systemFont(ofSize: 18*width, weight: .regular), textColor: .white, textAlignment: .left)
    //音乐人CollectionView
    private lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = .init(width: 50*width, height: 90*width)
        layout.sectionInset = .init(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumInteritemSpacing = 16*width
        layout.scrollDirection = .horizontal
        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_RecommendMemberCollectionViewCell.self, forCellWithReuseIdentifier: MPPositive_RecommendMemberCollectionViewCellID)
        return collectionView
    }()
    private let MPPositive_RecommendMemberCollectionViewCellID = "MPPositive_RecommendMemberCollectionViewCell"
    //MARK: - 分页栏设置
    //分页栏View
    private lazy var segmentView:JXSegmentedView = {
        var jxSegmentView = JXSegmentedView()
        jxSegmentView.backgroundColor = .init(hex: "1A1A1A")
        return jxSegmentView
    }()
    //数据源
    private lazy var dataSource:JXSegmentedTitleDataSource = {
        var dataSource = JXSegmentedTitleDataSource()
        //标题未选中状态
        dataSource.titleNormalColor = .init(hex: "#666666")
        dataSource.titleNormalFont = .systemFont(ofSize: 16*width, weight: .regular)
        //标题选中状态
        dataSource.titleSelectedColor = .init(hex: "#80F988")
        dataSource.titleSelectedFont = .systemFont(ofSize: 16*width, weight: .bold)
        //是否颜色过度
        dataSource.isTitleColorGradientEnabled = true
        dataSource.isSelectedAnimable = true
        dataSource.isItemTransitionEnabled = true
        return dataSource
    }()
    //指示器
    private lazy var indicator:JXSegmentedIndicatorLineView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16*width
        indicator.indicatorHeight = 3*width
        indicator.indicatorCornerRadius = 1.5*width
        indicator.indicatorColor = .init(hex: "#80F988")
        indicator.indicatorPosition = .bottom
        return indicator
    }()
    //分页内容承载框
    fileprivate lazy var listContainerView:JXSegmentedListContainerView = {
        let listContainerView = JXSegmentedListContainerView(dataSource: self)
        listContainerView.backgroundColor = .clear
        return listContainerView
    }()
    /// 初始化
    /// - Parameter browseId: 相关内容id
    init(_ browseId:String) {
        super.init(nibName: nil, bundle: nil)
        DispatchQueue.main.async {
            [weak self] in
            self?.loadRecommend = .init(browseId)
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("Recommend")
        setPopBtn()
        configure()
    }
    private func configure() {
        view.addSubview(membersView)
        membersView.snp.makeConstraints { make in
            make.width.equalTo(338*width)
            make.height.equalTo(141*width)
            make.top.equalTo(navView.snp.bottom).offset(33*width)
            make.centerX.equalToSuperview()
        }
        segmentView.indicators = [indicator]
        segmentView.dataSource = dataSource
        //配置View
        view.addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(membersView.snp.bottom).offset(10*width)
            make.height.equalTo(60*width)
        }
        view.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview().priority(999)
            make.top.equalTo(segmentView.snp.bottom).priority(999)
        }
        segmentView.contentScrollView = listContainerView.scrollView
        segmentView.listContainer = listContainerView
    }
    
    //生成音乐人部分
    private func createMusicMembersView() -> UIView {
        let membersView:UIView = .init()
        membersView.backgroundColor = .init(hex: "#1A1A1A")
        membersView.layer.masksToBounds = true
        membersView.layer.cornerRadius = 14*width
        //添加内容
        membersView.addSubview(sectionLabel)
        sectionLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(14*width)
            make.left.equalToSuperview().offset(12*width)
            make.right.equalToSuperview().offset(-12*width)
        }
        membersView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(50*width)
            make.left.equalToSuperview().offset(14*width)
            make.right.equalToSuperview().offset(-10*width)
            make.bottom.equalToSuperview()
        }
        return membersView
    }
}
//MARK: - collectionView
extension MPPositive_RecommendViewController:UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return loadRecommend?.members?.items.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MPPositive_RecommendMemberCollectionViewCellID, for: indexPath) as! MPPositive_RecommendMemberCollectionViewCell
        cell.itemView = loadRecommend?.members?.items[indexPath.row]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //用户查看艺术家
        let artistVC = MPPositive_ArtistShowViewController(loadRecommend?.members?.items[indexPath.row].browseItem.artistId ?? "")
        navigationController?.pushViewController(artistVC, animated: true)
    }
}
//MARK: - JXSegmentedTitleDataSource
extension MPPositive_RecommendViewController: JXSegmentedListContainerViewDataSource, JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return dataSource.titles.count
    }
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        let showView:MPPositive_RecommendShowTypeView = .init(listContainerView.frame, list: loadRecommend.sectionLists[index])
        showView.chooseItemBlock = {
            [weak self] (item) in
            guard let self = self else {return}
            switch item.browseItem.itemType {
            case .list:
                //列表专辑
                let listVC = MPPositive_ListShowViewController(item.browseItem.browseId ?? "", params: "")
                navigationController?.pushViewController(listVC, animated: true)
            case .single:
                //单曲/视频跳转
                //触发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.loadPlayer = lodaViewModel
                    
                }
            default:
                break
            }
        }
        return showView
    }
}
