//
//  MPPositive_ListShowViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/28.
//

import UIKit
///b面列表歌单展示
class MPPositive_ListShowViewController: MPPositive_BaseViewController, UIViewControllerTransitioningDelegate {
    //顶部封面图（呈现歌单封面）
    private lazy var coverImageView:UIImageView = {
        let imageView:UIImageView = .init()
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        return imageView
    }()
    //阴影渐变图（遮挡封面图）
    private lazy var maskImageView:UIImageView = {
        let imageView:UIImageView = .init(image: .init(named: "List_Cover'mask"))
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    //毛玻璃效果View
    private lazy var blurView:UIVisualEffectView = setBlurView()
    //标题Label
    private lazy var titleLabel:UILabel = createLabel(font: .systemFont(ofSize: 22*width, weight: .medium), textColor: .white, textAlignment: .left, lines: 1)
    //介绍Label
    private lazy var descriptionLabel:UILabel = createLabel(font: .systemFont(ofSize: 12*width, weight: .regular), textColor: .init(hex: "#FFFFFF", alpha: 0.6), textAlignment: .left, lines: 3)
    ///播放全部
    private lazy var playAllBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "Center_PlayAll'logo"), for: .normal)
        btn.setTitle(" Play all ()", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14*width, weight: .regular)
        btn.addTarget(self, action: #selector(playAllClick(_ :)), for: .touchUpInside)
        return btn
    }()
    ///随机播放按钮
    private lazy var shuffleBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "List_ShufflePlay'logo"), for: .normal)
        btn.setTitle(" Shuffle", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14*width, weight: .regular)
        btn.addTarget(self, action: #selector(shuffleClick(_ :)), for: .touchUpInside)
        return btn
    }()
    //收藏按钮
    private lazy var collectionListBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "List_UnCollection'logo"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "List_Collectioned'logo"), for: .selected)
        btn.addTarget(self, action: #selector(collectionSwitchClick(_ :)), for: .touchUpInside)
        return btn
    }()

    //tableView（歌单/专辑详情展示）
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: .init(x: 0, y: 0, width: screen_Width, height: screen_Height), style: .plain)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(MPPositive_MusicItemShowTableViewCell.self, forCellReuseIdentifier: MPPositive_MusicItemShowTableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        return tableView
    }()
    private let MPPositive_MusicItemShowTableViewCellID = "MPPositive_MusicItemShowTableViewCell"
    //传递的列表/专辑值
    private var listOrAlbum:MPPositive_ListAlbumListViewModel!{
        didSet{
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                if listOrAlbum != nil {
                    configure()
                    reload()
                    removeErrorView()
                    MP_HUD.hideNow()
                }
            }
        }
    }
    
    private var browseid:String!
    private var params:String!
    private var centerTtitle:String!
    private var subtitle:String!
    /// 生成列表控制器
    /// - Parameters:
    ///   - browseId: 列表的id
    ///   - params: 列表的编码
    init(_ browseId:String, params:String, title:String, subtitle:String) {
        self.browseid = browseId
        self.params = params
        self.centerTtitle = title
        self.subtitle = subtitle
        MP_HUD.loading()
        super.init(nibName: nil, bundle: nil)
        //发起网络请求
        MP_NetWorkManager.shared.requestAlbumOrListDatas(browseId, params: params) { [weak self] result in
            guard let self = self else {return}
            listOrAlbum = result
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("")
        setPopBtn()
        errorBlock = {
            [weak self] in
            guard let self = self else {
                return
            }
            //移除所有（除了navView）的子控件，并告知页面处理错误，提示用户重试
            view.subviews.forEach { item in
                if item != self.navView {
                    //移除
                    if item.superview != nil {
                        item.removeFromSuperview()
                    }
                }
            }
            //添加报错View
            setErrorView()
            MP_HUD.hideNow()
        }
        retryBlock = {
            [weak self] in
            guard let self = self else {return}
            MP_HUD.loading()
            MP_NetWorkManager.shared.requestAlbumOrListDatas(self.browseid, params: self.params) { [weak self] result in
                guard let self = self else {return}
                listOrAlbum = result
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reload()
    }
    //页面刷新
    private func reload() {
        listOrAlbum?.header?.setUrltoImage(coverImageView)
        titleLabel.text = listOrAlbum?.header?.title
        descriptionLabel.text = listOrAlbum?.header?._description
        playAllBtn.setTitle(" Play (\(listOrAlbum?.items.count ?? 0))", for: .normal)
        MPPositive_CollectionListModel.fetch(predicate: .init(format: "browseId == %@", self.browseid)) {[weak self] results in
            guard let self = self else {return}
            results.forEach { i in
                if i.browseId == self.browseid{
                    if i.params == self.params{
                        self.collectionListBtn.isSelected = true
                    }
                }
            }
        }
        tableView.reloadData()
    }
    //MARK: - UI生成与配置
    //页面配置
    private func configure() {
        //添加封面图
        view.addSubview(coverImageView)
        coverImageView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(413*width)
        }
        view.sendSubviewToBack(coverImageView)
        //添加阴影
        view.addSubview(maskImageView)
        maskImageView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(281*width)
            make.bottom.equalTo(coverImageView.snp.bottom)
        }
        //添加毛玻璃
        view.addSubview(blurView)
        blurView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(173*width)
            make.bottom.equalTo(maskImageView.snp.bottom)
        }
        //设置毛玻璃内容
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(blurView.snp.top).offset(18*width)
            make.left.equalToSuperview().offset(18*width)
            make.right.equalToSuperview().offset(-18*width)
        }
        view.addSubview(descriptionLabel)
        descriptionLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12*width)
            make.left.right.equalTo(titleLabel)
        }
        view.addSubview(playAllBtn)
        playAllBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18*width)
            make.height.equalTo(32*width)
            make.bottom.equalTo(blurView.snp.bottom).offset(-29*width)
        }
        view.addSubview(shuffleBtn)
        shuffleBtn.snp.makeConstraints { make in
            make.left.equalTo(playAllBtn.snp.right).offset(18*width)
            make.height.equalTo(32*width)
            make.centerY.equalTo(playAllBtn)
        }
        view.addSubview(collectionListBtn)
        collectionListBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24*width)
            make.right.equalToSuperview().offset(-18*width)
            make.centerY.equalTo(playAllBtn.snp.centerY)
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(coverImageView.snp.bottom)
        }
    }
    ///生成一个毛玻璃效果View，包含标题和说明
    private func setBlurView() -> UIVisualEffectView {
        // 创建一个模糊效果
        let blurEffect = UIBlurEffect(style: .light)
        // 创建一个可交互的毛玻璃视图
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.alpha = 0.3
        blurEffectView.isUserInteractionEnabled = true
        blurEffectView.layer.masksToBounds = true
        blurEffectView.layer.cornerRadius = 16*width
        blurEffectView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        return blurEffectView
    }
    
    //MARK: - 点击事件
    //播放全部事件
    @objc private func playAllClick(_ sender:UIButton) {
        MPPositive_Debouncer.shared.call {
            [weak self] in
            guard let self = self,  let item = listOrAlbum.items.first else {return}
            guard MP_NetWorkManager.shared.netWorkStatu == .reachable else {
                MP_HUD.text("Weak connection.", delay: 2.0, completion: nil)
                return
            }
            MP_AnalyticsManager.shared.song_clickAction("List")
            //优先清除数据
            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()
            }
        }
    }
    //随机播放事件
    @objc private func shuffleClick(_ sender:UIButton) {
        MPPositive_Debouncer.shared.call {
            [weak self] in
            guard let self = self,  let item = listOrAlbum.items.randomElement() else {return}
            guard MP_NetWorkManager.shared.netWorkStatu == .reachable else {
                MP_HUD.text("Weak connection.", delay: 2.0, completion: nil)
                return
            }
            MP_AnalyticsManager.shared.song_clickAction("List")
            //优先清除数据
            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()
            }
        }
    }
    //切换当前列表收藏状态
    @objc private func collectionSwitchClick(_ sender:UIButton) {
        if self.collectionListBtn.isSelected == true{
            self.collectionListBtn.isSelected = false
            MPPositive_CollectionListModel.fetch(predicate: .init(format: "browseId == %@", self.browseid)) {[weak self] results in
                guard let self = self else {return}
                results.forEach { i in
                    if i.browseId == self.browseid{
                        if i.params == self.params{
                            MPPositive_CollectionListModel.delete(i)
                        }
                    }
                }
                MPPositive_LoadCoreModel.shared.reloadCollectionListViewModels(nil)
            }
        }else{
            self.collectionListBtn.isSelected = true
            let item = MPPositive_CollectionListModel.create()
            item.title = self.centerTtitle
            item.subtitle = self.subtitle
            item.browseId = self.browseid
            item.params = self.params
            item.coverImage = listOrAlbum.header?.coverUrl
            MPPositive_CollectionListModel.save()
            MPPositive_LoadCoreModel.shared.reloadCollectionListViewModels(nil)
        }
    }

}
//MARK: - tableView
extension MPPositive_ListShowViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listOrAlbum?.items.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_MusicItemShowTableViewCellID, for: indexPath) as! MPPositive_MusicItemShowTableViewCell
        cell.itemView = listOrAlbum.items[indexPath.row]
        cell.rank = indexPath.row + 1
        cell.moreBlock = {
            [weak self] in
            guard let self = self else {return}
            MPPositive_Debouncer.shared.call {
                MPPositive_ModalType = .MoreOperations
                let moreVC = MPPositive_MoreSongOperationsViewController(self.listOrAlbum.items[indexPath.row])
                moreVC.disMissBlock = {
                    self.reload()
                }
                moreVC.transitioningDelegate = self
                moreVC.modalPresentationStyle = .custom
                self.present(moreVC, animated: true)
            }
        }
        cell.deleteBlock = {
            [weak self] in
            guard let self = self else {return}
            //点击删除下载
            let alertController = UIAlertController(title: "Delete This Song", message: "Are you sure you want to delete the offline resources of this song?", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "Cancel", style: .cancel)
            alertController.addAction(cancel)
            let sure = UIAlertAction(title: "Sure", style: .destructive) {(action) in
                guard let videoId = self.listOrAlbum.items[indexPath.row].browseItem.videoId else {return}
                //确定删除
                MP_DownloadManager.shared.deleteFileDocuments(videoId) { videoId in
                    MP_HUD.progress("Loading...", delay: 0.5) {
                        MP_HUD.text("Removed", delay: 1.0, completion: nil)
                        tableView.reloadData()
                    }
                }
            }
            alertController.addAction(sure)
            present(alertController, animated: true)
        }
        cell.cancelBlock = {
            [weak self] in
            guard let self = self else {return}
            //点击取消下载
            let alertController = UIAlertController(title: "Cancel Song Download Task", message: "Are you sure you want to cancel the download task of this song?", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "Cancel", style: .cancel)
            alertController.addAction(cancel)
            let sure = UIAlertAction(title: "Sure", style: .destructive) {(action) in
                guard let videoId = self.listOrAlbum.items[indexPath.row].browseItem.videoId else {return}
                //确定取消
                MP_DownloadManager.shared.cancelDownloadTask(videoId) { videoId in
                    MP_HUD.text("Canceled", delay: 1.0, completion: nil)
                    tableView.reloadData()
                }
            }
            alertController.addAction(sure)
            present(alertController, animated: true)
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt 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
            }
            MP_AnalyticsManager.shared.song_clickAction("List")
            //弹出播放器
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
            MP_AnalyticsManager.shared.player_b_impAction()
            //触发next请求，优先获取列表全部单曲基础数据（不完善）
            MP_NetWorkManager.shared.requestNextList(listOrAlbum.items[indexPath.row].browseItem.playListId ?? "", videoId: listOrAlbum.items[indexPath.row].browseItem.videoId ?? ""){ [weak self] listSongs in
                guard let self = self else {return}
                //回掉的数据并不完善，生成一个playerloadViewModel
                let lodaViewModel = MPPositive_PlayerLoadViewModel(listSongs, currentVideoId: listOrAlbum.items[indexPath.row].browseItem.videoId ?? "")
                lodaViewModel.improveData(listOrAlbum.items[indexPath.row].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)
    }

}
