//
//  MPPositive_ArtistShowTypeView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/15.
//

import UIKit
import MJRefresh
class MPPositive_ArtistShowTypeView: UIView, JXPagingViewListViewDelegate, UIViewControllerTransitioningDelegate {
    //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.register(MPPositive_ArtistDescriptionTableViewCell.self, forCellReuseIdentifier: MPPositive_ArtistDescriptionTableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        //添加一个上拉加载
        let footer = MJRefreshAutoGifFooter {
            [weak self] in
            self?.footerRefresh()
        }
        footer.setTitle("Pull Up", for: .idle)
        footer.setTitle("Release Refresh", for: .pulling)
        footer.setTitle("Loading...", for: .refreshing)
        footer.setTitle("No Data", for: .noMoreData)
        tableView.mj_footer = footer
        return tableView
    }()
    private let MPPositive_ArtistShowSongTableViewCellID = "MPPositive_ArtistShowSongTableViewCell"
    private let MPPositive_ArtistShowListableViewCellID = "MPPositive_ArtistShowListableViewCell"
    private let MPPositive_ArtistDescriptionTableViewCellID = "MPPositive_ArtistDescriptionTableViewCell"
    private var sectionList:MPPositive_ArtistContentListViewModel!{
        didSet{
            if sectionList != nil {
                //检索当前数据是否为全部
                if sectionList.browseId != nil && sectionList.params != nil {
                    //当前数据并不完整，需要初次补全一部分
                    sectionList.requestArtistType()
                }else {
                    //当前数据完整
                    tableView.reloadData()
                    tableView.mj_footer?.endRefreshing()
                }
                sectionList.completionBlock = {
                    [weak self] in
                    self?.tableView.reloadData()
                    self?.tableView.mj_footer?.endRefreshing()
                }
            }else {
                tableView.reloadData()
            }
        }
    }
    var header:MPPositive_ArtistHeaderModel!
    //scroll滚动回调
    fileprivate var listViewDidScrollCallback: ((UIScrollView) -> ())?
    //选中内容
    init(frame: CGRect, list:MPPositive_ArtistContentListViewModel) {
        super.init(frame: frame)
        backgroundColor = .init(hex: "#151718")
        //赋值
        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)
    }
    //上拉刷新
    @objc private func footerRefresh() {
        guard sectionList.continuation != nil, sectionList.itct != nil else {
            tableView.mj_footer?.endRefreshingWithNoMoreData()
            return
        }
        sectionList.requestArtistContinuation()
    }
    
    //MARK: - 遵循分页代理
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        listViewDidScrollCallback?(scrollView)
    }
    //获取当前视图
    func listView() -> UIView {
        return self
    }
    func listWillAppear() {
        //实现下载代理
        tableView.reloadData()
    }
    //获取当前视图中的ScrollView
    func listScrollView() -> UIScrollView {
        return tableView
    }
    //当前视图滚动时回调闭包
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }
}
//MARK: - tableView
extension MPPositive_ArtistShowTypeView:UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let first = sectionList?.itemViews.first {
            switch first.browseItem.itemType {
            case .single:
                return sectionList.itemViews.count
            case .list:
                return 1
            case .artist:
                return 2
            default:
                return 0
            }
        }else {
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let first = sectionList?.itemViews.first {
            switch first.browseItem.itemType {
            case .single:
                let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowSongTableViewCellID) as! MPPositive_ArtistShowSongTableViewCell
                cell.itemView = sectionList.itemViews[indexPath.row]
                cell.moreBlock = {
                    [weak self] in
                    guard let self = self else {return}
                    let itemView = self.sectionList.itemViews[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.itemViews[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.itemViews[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.itemViews
                cell.chooseItemBlock = {
                    [weak self] item in
                    guard let self = self else {return}
//                    if chooseItemBlock != nil {
//                        chooseItemBlock!(item)
//                    }
                    switch item.browseItem.itemType {
                    case .artist:
                        //用户查看艺术家
                        let artistVC = MPPositive_ArtistShowViewController(item.browseItem.artistId ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                        self.parentController()?.navigationController?.pushViewController(artistVC, animated: true)
                    case .list:
                        //列表专辑
                        let listVC = MPPositive_ListShowViewController(item.browseItem.browseId ?? "", params: "", title: item.title ?? "", subtitle: item.subtitle ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                        self.parentController()?.navigationController?.pushViewController(listVC, animated: true)
                    case .single:
                        break
                    case .none:
                        break
                    }
                }
                cell.showType = .List
                return cell
            case .artist:
                switch indexPath.row {
                case 0:
                    let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistShowListableViewCellID, for: indexPath) as! MPPositive_ArtistShowListableViewCell
                    cell.itemViews = sectionList.itemViews
                    cell.chooseItemBlock = {
                        [weak self] item in
                        guard let self = self else {return}
                        switch item.browseItem.itemType {
                        case .artist:
                            //用户查看艺术家
                            let artistVC = MPPositive_ArtistShowViewController(item.browseItem.artistId ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                            self.parentController()?.navigationController?.pushViewController(artistVC, animated: true)
                        case .list:
                            //列表专辑
                            let listVC = MPPositive_ListShowViewController(item.browseItem.browseId ?? "", params: "", title: item.title ?? "", subtitle: item.subtitle ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                            self.parentController()?.navigationController?.pushViewController(listVC, animated: true)
                        case .single:
                            break
                        case .none:
                            break
                        }
                    }
                    cell.showType = .Artist
                    return cell
                default:
                    let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ArtistDescriptionTableViewCellID, for: indexPath) as! MPPositive_ArtistDescriptionTableViewCell
                    cell.titleLabel.text = header?.fordescription ?? ""
                    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?.itemViews.first {
            switch first.browseItem.itemType {
            case .single:
                let item = sectionList.itemViews[indexPath.row]
                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("Artist")
                    //优先清除数据
                    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 ?? "", clickTrackingParams: item.browseItem.clickTrackingParams){ [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()
                    }
                }
            case .list:
                //当前是歌单专辑分页，用户点击不能触发
                break
            case .artist:
                //当前是艺术家页，用户点击不能触发
                break
            default:
                break
            }
        }
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
