//
//  MPPositive_CustomPlayListViewController.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/6/24.
//

import UIKit
import MJRefresh
///自定义歌单
class MPPositive_CustomPlayListViewController: MPPositive_BaseViewController, UIViewControllerTransitioningDelegate {
    ///更多按钮
    private lazy var moreBtn:UIButton = {
        let btn:UIButton = .init()
        btn.setBackgroundImage(UIImage(named: "Center_ListMore'logo"), for: .normal)
        btn.addTarget(self, action: #selector(moreClick(_ :)), for: .touchUpInside)
        return btn
    }()
    ///顶部大封面
    private lazy var backImageView:UIImageView = {
        let image:UIImageView = .init(image: placeholderImage)
        image.contentMode = .scaleAspectFill
        image.layer.masksToBounds = true
        return image
    }()
    ///顶部模糊遮罩
    private lazy var backBlurView:UIVisualEffectView = {
        // 创建一个模糊效果
        let blurEffect = UIBlurEffect(style: .dark)
        // 创建一个可交互的毛玻璃视图
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.alpha = 0.6
        blurEffectView.isUserInteractionEnabled = false
        return blurEffectView
    }()
    ///阴影渐变图（遮挡封面图）
    private lazy var maskImageView:UIImageView = {
        let imageView:UIImageView = .init(image: .init(named: "List_Cover'mask"))
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    ///顶部小封面
    private lazy var coverImageView:UIImageView = {
        let image:UIImageView = .init(image: placeholderImage)
        image.contentMode = .scaleAspectFill
        image.layer.masksToBounds = true
        image.layer.cornerRadius = 8*width
        return image
    }()
    ///歌单标题
    private lazy var titleLabel:UILabel = createLabel("Name", font: .systemFont(ofSize: 18*width, weight: .regular), textColor: .white, textAlignment: .center, lines: 2)
    ///歌单创建时间Label
    private lazy var createTimeLabel:UILabel = createLabel("CreateTime:", font: .systemFont(ofSize: 12*width), textColor: .white, textAlignment: .center)
    ///播放全部
    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 searchBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "Center_Search'logo"), for: .normal)
        btn.addTarget(self, action: #selector(searchActionShowClick(_ :)), for: .touchUpInside)
        return btn
    }()
    //搜索View
    private lazy var searchShowView:MPPositive_CenterListSearchView = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 30*width))
    ///tableView
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: .init(x: 0, y: 0, width: screen_Width, height: screen_Height), style: .plain)
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(MPPositive_SearchResultShowTableViewCell.self, forCellReuseIdentifier: MPPositive_SearchResultShowTableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        return tableView
    }()
    private let MPPositive_SearchResultShowTableViewCellID = "MPPositive_SearchResultShowTableViewCell"
    
    ///当前歌单
    var list:MPPositive_CustomPlayListModel!{
        didSet{
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                reload(list)
            }
        }
    }
    //是否搜索模式
    private var isSearchStyle:Bool = false
    //搜索展示的Videos
    private var videos:[MPPositive_CustomVideoModel] = []
    init(_ playList:MPPositive_CustomPlayListModel) {
        super.init(nibName: nil, bundle: nil)
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else {return}
            self.list = playList
        }
        setTitle("")
        setPopBtn()
        configure()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        searchShowView.cancelBlock = {
            [weak self] in
            guard let self = self else {return}
            UIView.animate(withDuration: 0.2) {
                [weak self] in
                guard let self = self else {return}
                searchShowView.isUserInteractionEnabled = false
                searchShowView.alpha = 0
                isSearchStyle = false
            } completion: { [weak self] statu in
                guard let self = self else {return}
                searchShowView.isHidden = true
                playAllBtn.isUserInteractionEnabled = true
                shuffleBtn.isUserInteractionEnabled = true
                searchBtn.isUserInteractionEnabled = true
                reload(list)
            }
        }
        searchShowView.textBlock = {
            [weak self] (text) in
            guard let self = self else {return}
            isSearchStyle = true
            //获得文本回调，根据文本筛选数据
            reloadSearch(text)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    private func reload(_ list:MPPositive_CustomPlayListModel) {
        //最新的封面,取最新的存入数据
        let coverURL = list.videosArray.first?.coverImageURL
        backImageView.kf.setImage(with: coverURL, placeholder: placeholderImage)
        coverImageView.kf.setImage(with: coverURL, placeholder: placeholderImage)
        titleLabel.text = list.title
        createTimeLabel.text = "Create Time: \(list.createTime.toString(.custom("YYYY/MM/dd-HH:mm")))"
        playAllBtn.setTitle(" Play (\(list.videosArray.count))", for: .normal)
        tableView.reloadData()
    }
    //搜索状态刷新
    private func reloadSearch(_ text:String) {
        if text.isEmpty {
            //当前输入文本为空，展示所有数据
            videos = list.videosArray
        }else {
            //当前输入文本不为空，筛选文本
            videos = list.videosArray.filter({$0.title.contains(text) || $0.subtitle.contains(text)})
        }
        //刷新
        tableView.reloadSections(.init(integer: 0), with: .automatic)
    }
    
    //配置
    private func configure() {
        //添加更多按钮
        navView.addSubview(moreBtn)
        moreBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-18*width)
            make.width.height.equalTo(24*width)
            make.centerY.equalToSuperview()
        }
        //添加顶部背景
        view.addSubview(backImageView)
        backImageView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo((227*width)+navAndstatusBarHeight)
        }
        //添加顶部模糊层
        view.addSubview(backBlurView)
        backBlurView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(backImageView)
        }
        //添加顶部阴影
        view.addSubview(maskImageView)
        maskImageView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(120*width)
            make.bottom.equalTo(backImageView)
        }
        //小封面
        view.addSubview(coverImageView)
        coverImageView.snp.makeConstraints { make in
            make.width.height.equalTo(120*width)
            make.center.equalTo(backImageView)
        }
        //标题
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.width.lessThanOrEqualToSuperview().multipliedBy(0.7)
            make.centerX.equalToSuperview()
            make.top.equalTo(coverImageView.snp.bottom).offset(30*width)
        }
        //创建时间
        view.addSubview(createTimeLabel)
        createTimeLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(6*width)
        }
        //播放全部按钮
        view.addSubview(playAllBtn)
        playAllBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18*width)
            make.top.equalTo(backImageView.snp.bottom).offset(24*width)
        }
        //随机播放按钮
        view.addSubview(shuffleBtn)
        shuffleBtn.snp.makeConstraints { make in
            make.left.equalTo(playAllBtn.snp.right).offset(18*width)
            make.centerY.equalTo(playAllBtn)
        }
        //搜索
        view.addSubview(searchBtn)
        searchBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-18*width)
            make.width.height.equalTo(24*width)
            make.centerY.equalTo(playAllBtn)
        }
        view.addSubview(searchShowView)
        searchShowView.snp.makeConstraints { make in
            make.height.equalTo(35*width)
            make.left.right.equalToSuperview()
            make.centerY.equalTo(searchBtn)
        }
        searchShowView.alpha = 0
        searchShowView.isHidden = true
        searchShowView.isUserInteractionEnabled = false
        //添加tableView
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(playAllBtn.snp.bottom).offset(18*width)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    
    //更多
    @objc private func moreClick(_ sender:UIButton) {
        MPPositive_ModalType = .PlayListEdit
        //歌单更多
        let moreVC = MPPositive_PlayListMoreViewController(list.title)
        moreVC.editBlock = {
            [weak self] text in
            guard let self = self else {return}
            list.title = text
            MPPositive_CustomPlayListModel.save()
            MPPositive_LoadCoreModel.shared.reloadCustomPlayLists(nil)
            reload(list)
        }
        moreVC.deleteBlock = {
            [weak self] in
            guard let self = self else {return}
            MPPositive_CustomPlayListModel.delete(list)
            MPPositive_LoadCoreModel.shared.reloadCustomPlayLists(nil)
            navigationController?.popViewController(animated: true)
        }
        moreVC.transitioningDelegate = self
        moreVC.modalPresentationStyle = .custom
        present(moreVC, animated: true)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
    //播放全部
    @objc private func playAllClick(_ sender:UIButton) {
        guard list.videosArray.count != 0 else {return}
        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("CustomList")
            //优先清除数据
            MP_PlayerManager.shared.loadPlayer = nil
            //弹出播放器
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
            MP_AnalyticsManager.shared.player_b_impAction()
            //将当前收藏音乐放入列表中
            var array:[MPPositive_SongItemModel] = []
            for (index,song) in list.videosArray.enumerated() {
                let item = MPPositive_SongItemModel()
                //填补item数据
                item.index = index
                item.reviewUrls = [song.coverImageURL.absoluteString]
                item.title = song.title
                item.shortBylineText = song.subtitle
                item.videoId = song.videoId
                item.lyricsID = song.lyricsID
                item.relatedID = song.relatedID
                array.append(item)
            }
            let lodaViewModel = MPPositive_PlayerLoadViewModel(array, currentVideoId: list.videosArray.first?.videoId ?? "")
            lodaViewModel.improveData(list.videosArray.first?.videoId ?? "")
            //更改播放器播放类型
            MP_PlayerManager.shared.setPlayType(.normal)
            MP_PlayerManager.shared.loadPlayer = lodaViewModel
            MP_AnalyticsManager.shared.player_b_listAction()
        }
    }
    //随机播放
    @objc private func shuffleClick(_ sender:UIButton) {
        guard list.videosArray.count != 0 else {return}
        MPPositive_Debouncer.shared.call {
            [weak self] in
            guard let self = self else {return}
            MP_AnalyticsManager.shared.song_clickAction("CustomList")
            //优先清除数据
            MP_PlayerManager.shared.loadPlayer = nil
            //弹出播放器
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
            MP_AnalyticsManager.shared.player_b_impAction()
            //将当前收藏音乐放入列表中
            var array:[MPPositive_SongItemModel] = []
            for (index,song) in list.videosArray.enumerated() {
                let item = MPPositive_SongItemModel()
                //填补item数据
                item.index = index
                item.reviewUrls = [song.coverImageURL.absoluteString]
                item.title = song.title
                item.shortBylineText = song.subtitle
                item.videoId = song.videoId
                item.lyricsID = song.lyricsID
                item.relatedID = song.relatedID
                array.append(item)
            }
            //选择随机的一个值
            let item = list.videosArray.randomElement()
            let lodaViewModel = MPPositive_PlayerLoadViewModel(array, currentVideoId: item?.videoId ?? "")
            lodaViewModel.improveData(item?.videoId ?? "")
            //更改播放器播放类型
            MP_PlayerManager.shared.setPlayType(.normal)
            MP_PlayerManager.shared.loadPlayer = lodaViewModel
            MP_AnalyticsManager.shared.player_b_listAction()
        }
    }
    //搜索
    @objc private func searchActionShowClick(_ sender:UIButton) {
        //点击搜索时，展示搜索框
        UIView.animate(withDuration: 0.2) {
            [weak self] in
            guard let self = self else {return}
            searchShowView.isHidden = false
            //调整searchView的透明度
            searchShowView.alpha = 1
            playAllBtn.isUserInteractionEnabled = false
            shuffleBtn.isUserInteractionEnabled = false
            searchBtn.isUserInteractionEnabled = false
        } completion: { [weak self] statu in
            guard let self = self else {return}
            searchShowView.isUserInteractionEnabled = true
        }
    }
}
//MARK: - tableView
extension MPPositive_CustomPlayListViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return isSearchStyle ? videos.count:list?.videosArray.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_SearchResultShowTableViewCellID, for: indexPath) as! MPPositive_SearchResultShowTableViewCell
        if isSearchStyle {
            cell.videoModel = videos[indexPath.row]
        }else {
            cell.videoModel = list?.videosArray[indexPath.row]
        }
        cell.moreBlock = {
            [weak self] in
            guard let self = self else {return}
            MPPositive_Debouncer.shared.call {
                let item = self.isSearchStyle ? self.videos[indexPath.row]:self.list?.videosArray[indexPath.row]
                MPPositive_ModalType = .MoreOperations
                let moreVC = MPPositive_MoreSongOperationsViewController(self.list, video: item)
                moreVC.disMissBlock = {
                    self.isSearchStyle ? self.reloadSearch(self.searchShowView.textField.text ?? ""):self.reload(self.list)
                }
                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.isSearchStyle ? self.videos[indexPath.row].videoId:self.list?.videosArray[indexPath.row].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.isSearchStyle ? self.videos[indexPath.row].videoId:self.list?.videosArray[indexPath.row].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("CustomList")
            //优先清除数据
            MP_PlayerManager.shared.loadPlayer = nil
            //弹出播放器
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
            MP_AnalyticsManager.shared.player_b_impAction()
            //将当前收藏音乐放入列表中
            var array:[MPPositive_SongItemModel] = []
            for (index,song) in list.videosArray.enumerated() {
                let item = MPPositive_SongItemModel()
                //填补item数据
                item.index = index
                item.reviewUrls = [song.coverImageURL.absoluteString]
                item.title = song.title
                item.shortBylineText = song.subtitle
                item.videoId = song.videoId
                item.lyricsID = song.lyricsID
                item.relatedID = song.relatedID
                array.append(item)
            }
            let currentVideo = isSearchStyle ? videos[indexPath.row]:list.videosArray[indexPath.row]
            let lodaViewModel = MPPositive_PlayerLoadViewModel(array, currentVideoId: currentVideo.videoId ?? "")
            lodaViewModel.improveData(currentVideo.videoId ?? "")
            //更改播放器播放类型
            MP_PlayerManager.shared.setPlayType(.normal)
            MP_PlayerManager.shared.loadPlayer = lodaViewModel
            MP_AnalyticsManager.shared.player_b_listAction()
        }
    }
}
