//
//  MPPositive_SearchResultTypeShowView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/14.
//

import UIKit
import MJRefresh
///对搜索结果进行分类详情展示
class MPPositive_SearchResultTypeShowView: UIView, JXSegmentedListContainerViewListDelegate, 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_SearchResultShowTableViewCell.self, forCellReuseIdentifier: MPPositive_SearchResultShowTableViewCellID)
        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_SearchResultShowTableViewCellID = "MPPositive_SearchResultShowTableViewCell"
    //对应的分类详情展示
    var sectionList:MPPositive_SearchResultListViewModel!{
        didSet{
            if sectionList != nil {
                if sectionList.allItemViews.count == 0 {
                    //开始请求内容
                    sectionList.requestSearchType()
                }
                sectionList.completionBlock = {
                    [weak self] in
                    self?.tableView.reloadData()
                    self?.tableView.mj_footer?.endRefreshing()
                }
            }else {
                tableView.reloadData()
            }
        }
    }
    var scrollBlock:(() -> Void)?
//    var moreBlock:((MPPositive_SearchResultItemViewModel) -> Void)?
//    //选中内容
//    var chooseItemBlock:((MPPositive_SearchResultItemViewModel) -> Void)?
//    var deleteBlock:((MPPositive_SearchResultItemViewModel, UITableView) -> Void)?
//    var cancelBlock:((MPPositive_SearchResultItemViewModel, UITableView) -> Void)?
    init(frame: CGRect, list:MPPositive_SearchResultListViewModel?) {
        super.init(frame: frame)
        backgroundColor = .init(hex: "1A1A1A")
        DispatchQueue.main.async {
            [weak self] in
            self?.sectionList = list
        }
        configure()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    //MARK: - 分页代理
    func listView() -> UIView {
        return self
    }
    func listWillAppear() {
        //实现下载代理
        tableView.reloadData()
    }
    //配置
    private func configure() {
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
    }
    //上拉刷新
    @objc private func footerRefresh() {
        guard sectionList.continuation != nil, sectionList.itct != nil else {
            tableView.mj_footer?.endRefreshingWithNoMoreData()
            return
        }
        sectionList.requestSearchContinuation()
    }
    func chooseItemClick(_ item:MPPositive_SearchResultItemViewModel) {
        switch item.item.itemType {
        case .artist:
            //用户查看艺术家
            let artistVC = MPPositive_ArtistShowViewController(item.item.browseId ?? "", clickTrackingParams: item.item.clickTrackingParams ?? "")
            if let vc = self.parentController(ofType: MPPositive_SearchResultShowViewController.self) {
                vc.navigationController?.pushViewController(artistVC, animated: true)
            }
        case .list:
            //列表专辑
            let listVC = MPPositive_ListShowViewController(item.item.browseId ?? "", params: "", title: item.title ?? "", subtitle: item.subtitle ?? "", clickTrackingParams: item.item.clickTrackingParams ?? "")
            if let vc = self.parentController(ofType: MPPositive_SearchResultShowViewController.self) {
                vc.navigationController?.pushViewController(listVC, animated: true)
            }
        case .single:
            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("Search")
                //优先清除数据
                MP_PlayerManager.shared.loadPlayer = nil
                //单曲/视频跳转
                //弹出播放器
                NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
                MP_AnalyticsManager.shared.player_b_impAction()
                //触发next请求，优先获取列表全部单曲基础数据（不完善）
                MP_NetWorkManager.shared.requestNextList(item.item.playListId ?? "", videoId: item.item.videoId ?? "", clickTrackingParams: item.item.clickTrackingParams){ [weak self] listSongs in
                    guard let self = self else {return}
                    //回掉的数据并不完善，生成一个playerloadViewModel
                    let lodaViewModel = MPPositive_PlayerLoadViewModel(listSongs, currentVideoId: item.item.videoId ?? "")
                    lodaViewModel.improveData(item.item.videoId ?? "")
                    //更改播放器播放类型
                    MP_PlayerManager.shared.setPlayType(.normal)
                    MP_PlayerManager.shared.loadPlayer = lodaViewModel
                    MP_AnalyticsManager.shared.player_b_listAction()
//                        NotificationCenter.notificationKey.post(notificationName: .pup_player_vc)
                }
            }
        case .none:
            break
        }
    }
}
//MARK: - tableView
extension MPPositive_SearchResultTypeShowView:UITableViewDataSource, UITableViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollBlock != nil {
            scrollBlock!()
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sectionList?.allItemViews.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_SearchResultShowTableViewCellID, for: indexPath) as! MPPositive_SearchResultShowTableViewCell
        cell.itemView = sectionList?.allItemViews[indexPath.row]
        cell.moreBlock = {
            [weak self] in
            guard let self = self else {return}
            if let itemView = self.sectionList?.allItemViews[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?.allItemViews[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.item.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?.allItemViews[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.item.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
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        chooseItemClick(sectionList.allItemViews[indexPath.row])
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
