//
//  MPPositive_LibraryViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/19.
//

import UIKit
import Kingfisher
class MPPositive_LibraryViewController: MPPositive_BaseViewController, UIViewControllerTransitioningDelegate {
    ///背景图片
    private lazy var backGroundImageView:UIImageView = {
        let imageView:UIImageView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 812*width))
        imageView.image = UIImage(named: "Center_Mask'bg")
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    //标题Label
    private lazy var titleLabel:UILabel = createLabel("Library", font: .systemFont(ofSize: 32*width, weight: .regular), textColor: .white, textAlignment: .left)
    ///封面图片组
    private lazy var coverImageViews:[UIImageView] = {
        var array:[UIImageView] = []
        for index in 0...2{
            let imageView:UIImageView = .init()
            imageView.contentMode = .scaleAspectFill
            imageView.tag = index
            imageView.image = placeholderImage
            array.append(imageView)
        }
        return array
    }()
    ///收藏单曲Label
    private lazy var songsLabel:UILabel = createLabel("0", font: .systemFont(ofSize: 12*width, weight: .light), textColor: .white, textAlignment: .left)
    ///收藏歌手Label
    private lazy var artistsLabel:UILabel = createLabel("0", font: .systemFont(ofSize: 12*width, weight: .light), textColor: .white, textAlignment: .left)
    ///下载单曲Label
    private lazy var loadsLabel:UILabel = createLabel("0", font: .systemFont(ofSize: 12*width, weight: .light), textColor: .white, textAlignment: .left)
    ///事件View组
    private lazy var actionViews:UIView = showTopView()
    ///广告View
    fileprivate lazy var adContainerView:UIView = {
        let adContainerView:UIView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 300*width))
        adContainerView.backgroundColor = .clear
        return adContainerView
    }()
    //MARK: - 分页栏设置
    //分页栏View
    private lazy var segmentView:JXSegmentedView = {
        var jxSegmentView = JXSegmentedView()
        jxSegmentView.backgroundColor = .clear
        return jxSegmentView
    }()
    //数据源
    private lazy var dataSource:JXSegmentedTitleDataSource = {
        var dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["Playlists", "Collect Playlists"]
        //标题未选中状态
        dataSource.titleNormalColor = .init(hex: "#999999")
        dataSource.titleNormalFont = .systemFont(ofSize: 14*width, weight: .regular)
        //标题选中状态
        dataSource.titleSelectedColor = .white
        dataSource.titleSelectedFont = .systemFont(ofSize: 14*width, weight: .regular)
        dataSource.itemSpacing = 16*width
        dataSource.isItemSpacingAverageEnabled = false
        //是否颜色过度
        dataSource.isTitleColorGradientEnabled = true
        dataSource.isSelectedAnimable = true
        dataSource.isItemTransitionEnabled = true
        return dataSource
    }()
    //指示器
    private lazy var indicator:JXSegmentedIndicatorLineView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 20*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
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("")
        configure()
        view.backgroundColor = .init(hex: "#000000")
        MP_AdMobManager.shared.configureLibraryNativeAd(rootController: self)
        MP_AdMobManager.shared.loadLibraryNativeAd()
        MP_AdMobManager.shared.layoutLibraryNativeAd(in: adContainerView, index: 0)
        MP_AdMobManager.shared.onLibraryNativeAdBlock = {
            [weak adContainerView] in
            guard let adContainerView = adContainerView else {return}
            MP_AdMobManager.shared.layoutLibraryNativeAd(in: adContainerView, index: 0)
        }
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        MP_AnalyticsManager.shared.me_b_pvAction()
        reload()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    //刷新列表
    private func reload() {
        MPPositive_LoadCoreModel.shared.reloadCollectionListViewModels {
            [weak self] in
            guard let self = self else {return}
            
            //封面设置
            songsLabel.text = "Songs \(MPPositive_LoadCoreModel.shared.songViewModels.count)"
            let songCover = MPPositive_LoadCoreModel.shared.songViewModels.first?.coverURL
            coverImageViews[0].kf.setImage(with: songCover, placeholder: placeholderImage)

            artistsLabel.text = "Artists \(MPPositive_LoadCoreModel.shared.artistViewModels.count)"
            let artistCover = MPPositive_LoadCoreModel.shared.artistViewModels.first?.coverURL
            coverImageViews[1].kf.setImage(with: artistCover, placeholder: placeholderImage)
            
            loadsLabel.text = "Offline \(MPPositive_LoadCoreModel.shared.loadViewModels.count)"
            let loadCover = MPPositive_LoadCoreModel.shared.loadViewModels.first?.reviewURL
            coverImageViews[2].kf.setImage(with: loadCover, placeholder: placeholderImage)
            
        }
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
    private func configure() {
        view.addSubview(backGroundImageView)
        navView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16*width)
            make.centerY.equalToSuperview()
        }
        //添加广告
        view.addSubview(adContainerView)
        adContainerView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(20*width)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        //添加事件块
        view.addSubview(actionViews)
        actionViews.snp.makeConstraints { make in
            make.top.equalTo(adContainerView.snp.bottom).offset(24*width)
            make.left.right.equalToSuperview()
            make.height.equalTo(109*width)
        }
        //添加分页
        segmentView.indicators = [indicator]
        segmentView.dataSource = dataSource
        view.addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(actionViews.snp.bottom).offset(20*width)
            make.height.equalTo(45*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
    }
    
    //返回顶部事件View组
    private func showTopView() -> UIView {
        let topView = UIView()
        topView.backgroundColor = .clear
        //添加事件按钮
        let first = actionView(songsLabel, text: "Center_Songs'logo", tag: 0)
        topView.addSubview(first)
        first.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.height.width.equalTo(109*width)
            make.left.equalToSuperview().offset(16*width)
        }
        let second = actionView(artistsLabel, text: "Center_Artists'logo", tag: 1)
        topView.addSubview(second)
        second.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.height.width.equalTo(109*width)
            make.centerX.equalToSuperview()
        }
        let third = actionView(loadsLabel, text: "Center_Offline'logo", tag: 2)
        topView.addSubview(third)
        third.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.height.width.equalTo(109*width)
            make.right.equalToSuperview().offset(-16*width)
        }
        topView.isUserInteractionEnabled = true
        return topView
    }
    //生成一个事件View块
    private func actionView(_ label:UILabel, text:String, tag:Int) -> UIView {
        let actionView = UIView()
        actionView.backgroundColor = .clear
        //设置圆角
        actionView.layer.masksToBounds = true
        actionView.layer.cornerRadius = 8*width
        //添加封面图片
        actionView.addSubview(coverImageViews[tag])
        coverImageViews[tag].snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        //添加一个iconImage
        let iconImageView:UIImageView = .init(image: .init(named: text))
        iconImageView.contentMode = .scaleAspectFill
        actionView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.width.height.equalTo(20*width)
            make.left.equalToSuperview().offset(8*width)
            make.bottom.equalToSuperview().offset(-8*width)
        }
        //添加一个标题
        actionView.addSubview(label)
        label.snp.makeConstraints { make in
            make.centerY.equalTo(iconImageView)
            make.left.equalTo(iconImageView.snp.right).offset(4*width)
            make.right.equalToSuperview().offset(-8*width)
        }
        actionView.tag = tag
        actionView.isUserInteractionEnabled = true
        actionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(actionClick(_:))))
        return actionView
    }
    //事件点击方法
    @objc private func actionClick(_ sender:UITapGestureRecognizer) {
        let tag = sender.view?.tag
        switch tag {
        case 0:
            let loveSongsVC = MPPositive_LoveSongsViewController()
            navigationController?.pushViewController(loveSongsVC, animated: true)
        case 1:
            let loveArtistsVC = MPPositive_LoveArtistsViewController()
            navigationController?.pushViewController(loveArtistsVC, animated: true)
        default:
            let offlineVC = MPPositive_OfflineSongsViewController()
            navigationController?.pushViewController(offlineVC, animated: true)
        }
        MP_AdMobManager.shared.showLibraryInterstitialAdIfAvailable(completion: nil)
    }
}
//MARK: - JXSegmentedTitleDataSource
extension MPPositive_LibraryViewController:JXSegmentedListContainerViewDataSource, JXSegmentedViewDelegate{
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return dataSource.titles.count
    }
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        switch index {
        case 0://自定义歌单
            let showView:MPPositive_PlayListsShowTypeView = .init(frame: listContainerView.frame)
            showView.addBlock = {
                [weak self] in
                guard let self = self else {return}
                //弹出新增自定义框
                MPPositive_ModalType = .NewList
                let listVC = MPSideA_RenameViewController()
                listVC.titleText = "Name Your PlayList"
                listVC.renameBlock = {
                    [weak self] text in
                    //新建一个自定歌单列表
                    let list = MPPositive_CustomPlayListModel.create()
                    list.playListId = Date().timeZone().toString(.custom("YYYY/MM/dd/HH:mm:ss"))
                    list.title = text
                    list.createTime = Date().timeZone()
                    list.addToRelationshipToCustomVideos([])
                    MPPositive_CustomPlayListModel.save()
                    //成功新建歌单列表
                    print("成功新建\(text)歌单")
                    //发布通知
                    NotificationCenter.notificationKey.post(notificationName: .create_custom_playlist)
                }
                listVC.transitioningDelegate = self
                listVC.modalPresentationStyle = .custom
                present(listVC, animated: true)
            }
            showView.chooseBlock = {
                [weak self] item in
                guard let self = self else {return}
                //展示歌单详情
                let playListVC = MPPositive_CustomPlayListViewController(item.playList)
                navigationController?.pushViewController(playListVC, animated: true)
                MP_AdMobManager.shared.showLibraryInterstitialAdIfAvailable(completion: nil)
            }
            return showView
        default://收藏歌单
            let showView:MPPositive_CollectionListsShowTypeView = .init(frame: listContainerView.frame)
            showView.chooseBlock = {
                [weak self] item in
                guard let self = self else {return}
                let listVC = MPPositive_ListShowViewController(item.collectionList.browseId ?? "", params: item.collectionList.params ?? "", title: item.collectionList.title ?? "", subtitle: item.collectionList.subtitle ?? "")
                navigationController?.pushViewController(listVC, animated: true)
            }
            return showView
        }
    }
}
