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

import UIKit
///b面列表歌单展示
class MPPositive_ListShowViewController: MPPositive_BaseViewController {
    //顶部封面图（呈现歌单封面）
    private lazy var coverImageView:UIImageView = {
        let imageView:UIImageView = .init()
        imageView.contentMode = .scaleAspectFill
        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)
    //播放全部View
    private lazy var playListView:UIView = setPlayAllView()
    //播放全部列表按钮
    private lazy var playListBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "List_UnPlay'logo"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "List_Played'logo"), for: .selected)
        btn.isUserInteractionEnabled = false
        return btn
    }()
    //全部Label
    private lazy var playListNumberLabel:UILabel = createLabel(font: .systemFont(ofSize: 14*width, weight: .regular), textColor: .white, textAlignment: .left)
    //收藏按钮
    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
    }()
    //播放状态按钮
    private lazy var playTypeBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "List_NormolPlay'logo"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "List_ShufflePlay'logo"), for: .selected)
        btn.addTarget(self, action: #selector(collectionStatuClick(_ :)), 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)
        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 {
                    reload()
                    tableView.reloadData()
                }
            }
        }
    }
    
    var browseid:String = ""
    var params:String = ""
    /// 生成列表控制器
    /// - Parameters:
    ///   - browseId: 列表的id
    ///   - params: 列表的编码
    init(_ browseId:String, params:String) {
        super.init(nibName: nil, bundle: nil)
        self.browseid = browseId
        self.params = params
        //发起网络请求
        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()
        configure()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        MPPositive_CollectionListModel.fetch(.init(format: "browseId == %@", self.browseid)).forEach { i in
            if i.browseId == self.browseid{
                if i.params == self.params{
                    self.collectionListBtn.isSelected = true
                }
            }
        }
    }
    //页面刷新
    private func reload() {
        listOrAlbum.header?.setUrltoImage(coverImageView)
        titleLabel.text = listOrAlbum.header?.title
        descriptionLabel.text = listOrAlbum.header?._description
        playListNumberLabel.text = "Play all (\(listOrAlbum.items.count))"
    }
    //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(playListView)
        playListView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18*width)
            make.width.equalTo(138*width)
            make.height.equalTo(32*width)
            make.bottom.equalTo(blurView.snp.bottom).offset(-29*width)
        }
        view.addSubview(playTypeBtn)
        playTypeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24*width)
            make.right.equalToSuperview().offset(-18*width)
            make.centerY.equalTo(playListView.snp.centerY)
        }
        view.addSubview(collectionListBtn)
        collectionListBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24*width)
            make.right.equalToSuperview().offset(-56*width)
            make.centerY.equalTo(playListView.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
    }
    ///播放全部按钮View
    private func setPlayAllView() -> UIView {
        let allView:UIView = .init()
        allView.backgroundColor = .clear
        allView.isUserInteractionEnabled = true
        allView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(playListActionClick(_ :))))
        let image = UIImageView(image: UIImage(named: "List_PlayAll'bg"))
        image.contentMode = .scaleAspectFill
        allView.addSubview(image)
        image.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        //添加
        allView.addSubview(playListBtn)
        playListBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24*width)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(4*width)
        }
        //添加
        allView.addSubview(playListNumberLabel)
        playListNumberLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(playListBtn.snp.right).offset(6*width)
        }
        return allView
    }
    
    //MARK: - 点击事件
    //播放/暂停列表
    @objc private func playListActionClick(_ sender:UITapGestureRecognizer) {
        
    }
    //切换当前列表收藏状态
    @objc private func collectionSwitchClick(_ sender:UIButton) {
        if self.collectionListBtn.isSelected == true{
            self.collectionListBtn.isSelected = false
            
                MPPositive_CollectionListModel.fetch(.init(format: "browseId == %@", self.browseid)).forEach { i in
                    if i.browseId == self.browseid{
                        if i.params == self.params{
                            MPPositive_CollectionListModel.delete(i)
                        }
                    }
                }
            
        }else{
            self.collectionListBtn.isSelected = true
            let item = MPPositive_CollectionListModel.create()
            item.title = listOrAlbum.header.title
            item.browseId = self.browseid
            item.params = self.params
            item.coverImage = listOrAlbum.header.coverUrl
            MPPositive_CollectionListModel.save()
            
        }
    }
    //更改当前列表播放状态
    @objc private func collectionStatuClick(_ sender:UIButton) {
        
    }
}
//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]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //触发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.loadPlayer = lodaViewModel
            //发布弹出音乐播放器的通知
            NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
        }
    }
}
