//
//  MPPositive_RecommendShowTypeView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/20.
//

import UIKit
import MJRefresh
class MPPositive_RecommendShowTypeView: UIView, JXSegmentedListContainerViewListDelegate {
    //tableView
    private lazy var tableView:UITableView = {
        let tableView = UITableView()
        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_ArtistShowSongTableViewCell.self, forCellReuseIdentifier: MPPositive_ArtistShowSongTableViewCellID)
        tableView.register(MPPositive_ArtistShowListableViewCell.self, forCellReuseIdentifier: MPPositive_ArtistShowListableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        return tableView
    }()
    private let MPPositive_ArtistShowSongTableViewCellID = "MPPositive_ArtistShowSongTableViewCell"
    private let MPPositive_ArtistShowListableViewCellID = "MPPositive_ArtistShowListableViewCell"
    private var sectionList:MPPositive_RecommendListViewModel!{
        didSet{
            //当前数据完整
            tableView.reloadData()
        }
    }
    //选中内容
//    var chooseItemBlock:((MPPositive_BrowseItemViewModel) -> Void)?
//    var moreBlock:((MPPositive_BrowseItemViewModel) -> Void)?
//    var deleteBlock:((MPPositive_BrowseItemViewModel, UITableView) -> Void)?
//    var cancelBlock:((MPPositive_BrowseItemViewModel, UITableView) -> Void)?
    init(_ frame:CGRect, list:MPPositive_RecommendListViewModel) {
        super.init(frame: frame)
        backgroundColor = .clear
        //赋值
        DispatchQueue.main.async {
            [weak self] in
            self?.sectionList = list
        }
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    //MARK: - 分页代理
    func listView() -> UIView {
        return self
    }
    func listWillAppear() {
        tableView.reloadData()
    }
    func chooseItemClick(_ item:MPPositive_BrowseItemViewModel) {
        switch item.browseItem.itemType {
        case .list:
            //列表专辑
            let listVC = MPPositive_ListShowViewController(item.browseItem.browseId ?? "", params: "", title: item.title ?? "", subtitle: item.subtitle ?? "")
            self.parentController()?.navigationController?.pushViewController(listVC, animated: true)
        case .single:
            //优先清除数据
            MP_AnalyticsManager.shared.song_clickAction("Recommend")
            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()
            }
        default:
            break
        }
    }
}
//MARK: - tableView
extension MPPositive_RecommendShowTypeView:UITableViewDataSource, UITableViewDelegate, UIViewControllerTransitioningDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let first = sectionList?.items.first {
            switch first.browseItem.itemType {
            case .single:
                return sectionList.items.count
            case .list:
                return 1
            default:
                return 0
            }
        }else {
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let first = sectionList?.items.first {
            switch first.browseItem.itemType {
            case .single:
                let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowSongTableViewCellID) as! MPPositive_ArtistShowSongTableViewCell
                cell.itemView = sectionList.items[indexPath.row]
                cell.moreBlock = {
                    [weak self] in
                    if let itemView = self?.sectionList.items[indexPath.row]{
                        MPPositive_Debouncer.shared.call {
                            MPPositive_ModalType = .MoreOperations
                            let moreVC = MPPositive_MoreSongOperationsViewController(itemView)
                            moreVC.disMissBlock = {
                                DispatchQueue.main.async {
                                    tableView.reloadData()
                                }
                            }
                            moreVC.transitioningDelegate = self
                            moreVC.modalPresentationStyle = .custom
                            self?.parentController()?.present(moreVC, animated: true)
                        }
                    }
                }
                cell.cancelBlock = {
                    [weak self] in
                    if let itemView = self?.sectionList.items[indexPath.row]{
                        //点击取消下载
                        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 = itemView.browseItem.videoId else {return}
                            //确定取消
                            MP_DownloadManager.shared.cancelDownloadTask(videoId) { videoId in
                                MP_HUD.text("Canceled", delay: 1.0, completion: nil)
                                DispatchQueue.main.async {
                                    tableView.reloadData()
                                }
                            }
                        }
                        alertController.addAction(sure)
                        self?.parentController()?.present(alertController, animated: true)
                    }
                }
                cell.deleteBlock = {
                    [weak self] in
                    if  let itemView = self?.sectionList.items[indexPath.row]{
                        //点击删除下载
                        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 = itemView.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)
                                    DispatchQueue.main.async {
                                        tableView.reloadData()
                                    }
                                }
                            }
                        }
                        alertController.addAction(sure)
                        self?.parentController()?.present(alertController, animated: true)
                    }
                }
                return cell
            case .list:
                let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowListableViewCellID, for: indexPath) as! MPPositive_ArtistShowListableViewCell
                cell.itemViews = sectionList.items
                cell.chooseItemBlock = {
                    [weak self] item in
                    guard let self = self else {return}
                    chooseItemClick(sectionList.items[indexPath.row])
                }
                cell.showType = .List
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowSongTableViewCellID) as! MPPositive_ArtistShowSongTableViewCell
                
                return cell
            }
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowSongTableViewCellID) as! MPPositive_ArtistShowSongTableViewCell
            
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let first = sectionList?.items.first {
            switch first.browseItem.itemType {
            case .single:
                //当前是单曲分页，点击cell可以直接触发事件块
                chooseItemClick(sectionList.items[indexPath.row])
            case .list:
                break
            default:
                break
            }
        }
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
