//
//  MPPositive_ArtistShowViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/15.
//

import UIKit

class MPPositive_ArtistShowViewController: MPPositive_BaseViewController {
    ///头视图
    private lazy var headView:MPPositive_ArtistShowHeaderView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 385*width))
    ///艺术家Label
    private lazy var nameLabel:UILabel = {
        let label:UILabel = createLabel(font:  .systemFont(ofSize: 20*width, weight: .regular), textColor: .white, textAlignment: .left)
        label.alpha = 0
        return label
    }()
    //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
        indicator.verticalOffset = 5*width
        return indicator
    }()
    ///分页内容承载框
    fileprivate lazy var pagingView: JXPagingView = {
        let pagingView = JXPagingView(delegate: self)
        pagingView.backgroundColor = .clear
        pagingView.isHidden = true
        pagingView.mainTableView.backgroundColor = .clear
        //禁止弹簧效果
        pagingView.mainTableView.bounces = false
        return pagingView
    }()
    private var artist:MPPositive_ArtistViewModel!{
        didSet{
            if artist != nil {
                pagingView.isHidden = false
                //更新头部视图数据
                headView.artistid = self.browseid
                headView.artist = artist
               
                //更新分页数据源
                dataSource.titles = artist.lists.compactMap({$0.title})
                nameLabel.text = artist.header?.title
                dataSource.reloadData(selectedIndex: 0)
                segmentView.reloadData()
            }
        }
    }
    var browseid:String = ""
    var iscollection:Bool = false
    
    /// 艺术家页面
    /// - Parameter browseId: 艺术家Id
    init(_ browseId:String) {
        super.init(nibName: nil, bundle: nil)
        browseid = browseId
        //进行网络请求
        MP_NetWorkManager.shared.requestArtist(browseId) { [weak self] result in
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                artist = result
            }
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setPopBtn()
        setTitle("")
        configure()
    }

    private func configure() {
        segmentView.dataSource = dataSource
        segmentView.indicators = [indicator]
        view.addSubview(pagingView)
        pagingView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.bottom.equalToSuperview().priority(999)
        }
        segmentView.listContainer = pagingView.listContainerView
        pagingView.listContainerView.backgroundColor = .clear
        pagingView.listContainerView.listCellBackgroundColor = .clear
        navView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(68*width)
            make.right.equalToSuperview().offset(-16*width)
        }
        pagingView.pinSectionHeaderVerticalOffset = Int(statusBarHeight + (50*width))
    }
}
//MARK: - JXPagingViewDelegate
extension MPPositive_ArtistShowViewController: JXPagingViewDelegate{
    func pagingView(_ pagingView: JXPagingView, mainTableViewDidScroll scrollView: UIScrollView) {
        //状态栏加导航栏高度
        let allHeight = statusBarHeight + (50*width)
        let maxHeight = headView.frame.height - allHeight
        let currentOffset = scrollView.contentOffset
        if currentOffset.y <= maxHeight {
            //随着滚动变化header的透明度
            let value:CGFloat = currentOffset.y/maxHeight
            let topValue:CGFloat = 1-value
            if value >= 0.8 {
                nameLabel.alpha = 1
                headView.alpha = 0
            }else {
                nameLabel.alpha = value
                headView.alpha = topValue
            }
        }
    }
    //头部高度
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return Int(headView.frame.height)
    }
    //头部View内容
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return headView
    }
    // 悬浮分页栏的高度
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return Int(60 * width)
    }
    
    // 分页栏
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentView
    }
    //分页数量
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return dataSource.titles.count
    }
    //要展现的View
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        let showView:MPPositive_ArtistShowTypeView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: screen_Height-headView.frame.height-(60 * width)), list: artist.lists[index])
        showView.header = artist.header
        showView.chooseItemBlock = {
            [weak self] (item) in
            guard let self = self else {return}
            switch item.browseItem.itemType {
            case .artist:
                //用户查看艺术家
                let artistVC = MPPositive_ArtistShowViewController(item.browseItem.browseId ?? "")
                navigationController?.pushViewController(artistVC, animated: true)
            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
                    NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
                }
            case .none:
                break
            }
        }
        return showView
    }
}
