//
//  MPPositive_PlayerListShowViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/10.
//

import UIKit

class MPPositive_PlayerListShowViewController: UIViewController, UIViewControllerTransitioningDelegate {
    //小角标图片
    private lazy var indictorImageView:UIImageView = .init(image: .init(named: "Player_Indictor'logo"))
    //查询艺术家
    private lazy var artistView:UIView = {
        let artistView:UIView = createTopView("Artist", image: .init(named: "Search Artist'logo"))
        //添加点击效果
        artistView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(searchArtistClick(_ :))))
        return artistView
    }()
    //添加歌单
    private lazy var listView:UIView = {
        let listView:UIView = createTopView("Add playlist", image: .init(named: "Add PlayList'logo"))
        listView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(addPlayListClick(_ :))))
        return listView
    }()
    //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.contentInset = .init(top: 0, left: 0, bottom: bottomPadding, right: 0)
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(MPPositive_PlayerListShowTableViewCell.self, forCellReuseIdentifier: MPPositive_PlayerListShowTableViewCellID)
        
        return tableView
    }()
    private let MPPositive_PlayerListShowTableViewCellID = "MPPositive_PlayerListShowTableViewCell"
    var searchBlock:((String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .init(hex: "#1A1A1A")
        view.layer.masksToBounds = true
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.layer.cornerRadius = 18*width
        configure()
        //添加监听，当前音乐切换后，刷新
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(currentVideoReloadAction(_:)), notificationName: .positive_player_reload)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //生成顶部按钮View
    private func createTopView(_ title:String, image:UIImage?) -> UIView {
        let backView:UIView = UIView()
        backView.backgroundColor = .clear
        backView.isUserInteractionEnabled = true
        backView.layer.masksToBounds = false
        //一个黑色view（内含一个图片）
        let centerView:UIView = UIView(frame: .init(x: 0, y: 0, width: 52*width, height: 52*width))
        centerView.layer.masksToBounds = true
        centerView.layer.cornerRadius = 26*width
        centerView.backgroundColor = .init(hex: "#282828")
        let iconImageView:UIImageView = .init(image: image)
        centerView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(24*width)
        }
        backView.addSubview(centerView)
        //一个标题Label
        let label = createLabel(title, font: .systemFont(ofSize: 12*width, weight: .regular), textColor: .white, textAlignment: .center)
        backView.addSubview(label)
        label.snp.makeConstraints { make in
            make.top.equalTo(centerView.snp.bottom).offset(6*width)
            make.centerX.equalToSuperview()
        }
        return backView
    }
    
    private func configure() {
        view.addSubview(indictorImageView)
        indictorImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(29*width)
            make.height.equalTo(4*width)
            make.top.equalTo(12*width)
        }
        view.addSubview(artistView)
        artistView.snp.makeConstraints { make in
            make.width.height.equalTo(52*width)
            make.left.equalToSuperview().offset(18*width)
            make.top.equalToSuperview().offset(48*width)
        }
        view.addSubview(listView)
        listView.snp.makeConstraints { make in
            make.width.height.equalTo(52*width)
            make.left.equalTo(artistView.snp.right).offset(40*width)
            make.centerY.equalTo(artistView.snp.centerY)
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(150*width)
            make.left.right.bottom.equalToSuperview()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    @objc private func currentVideoReloadAction(_ sender:Notification) {
        tableView.reloadData()
    }
    //用户点击了搜查艺术家
    @objc private func searchArtistClick(_ sender:UITapGestureRecognizer) {
        guard let currentVideo = MP_PlayerManager.shared.loadPlayer?.currentVideo,  let subtitle = currentVideo.subtitle, subtitle.isEmpty == false else {
            dismiss(animated: true)
            return
        }
        //回调
        dismiss(animated: true) {
            [weak self] in
            if let block = self?.searchBlock {
                block(subtitle)
            }
        }
    }
    //用户点击了添加歌单
    @objc private func addPlayListClick(_ sender:UITapGestureRecognizer) {
        guard let currentVideo = MP_PlayerManager.shared.loadPlayer?.currentVideo else {
            dismiss(animated: true)
            return
        }
        //选择歌单
        MPPositive_ModalType = .MoreOperations
        let chooseVC = MPPositive_ChoosePlayListViewController(currentVideo.song)
        chooseVC.disMissBlock = {
            [weak self] in
            self?.dismiss(animated: true)
        }
        chooseVC.transitioningDelegate = self
        chooseVC.modalPresentationStyle = .custom
        present(chooseVC, animated: true)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
//MARK: - tableView
extension MPPositive_PlayerListShowViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //展示MP_PlayerManager中的列表数据
        return MP_PlayerManager.shared.loadPlayer?.songVideos.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_PlayerListShowTableViewCellID, for: indexPath) as! MPPositive_PlayerListShowTableViewCell
        cell.song = MP_PlayerManager.shared.loadPlayer?.songVideos[indexPath.row]
        cell.removeBlock = {
            [weak self] in
            if MP_PlayerManager.shared.loadPlayer.songVideos.count > 1 {
                //从列表中移除音乐
                MP_PlayerManager.shared.loadPlayer.removeData(MP_PlayerManager.shared.loadPlayer.songVideos[indexPath.row].videoId)
                tableView.reloadData()
            }else {
                //当音乐库只有一首的话，移除的话，直接关闭播放器
                MP_PlayerManager.shared.stop()
                MP_PlayerManager.shared.loadPlayer = nil
                self?.dismiss(animated: true)
            }
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //播放选中音乐
        dismiss(animated: true) {
            guard MP_PlayerManager.shared.loadPlayer?.songVideos[indexPath.row].videoId != MP_PlayerManager.shared.loadPlayer?.currentVideo?.song.videoId else {
                return
            }
            //更新播放音乐
            MP_PlayerManager.shared.loadPlayer.improveData(MP_PlayerManager.shared.loadPlayer.songVideos[indexPath.row].videoId)
        }
    }
}
