//
//  MPPositive_GrideMoodViewController.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/7/12.
//

import UIKit
///模块数据详情
class MPPositive_GrideMoodViewController: MPPositive_BaseViewController {
    //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_HomeSinglesTableViewCell.self, forCellReuseIdentifier: MPPositive_HomeSinglesTableViewCellID)
        tableView.register(MPPositive_HomeShowTableViewCell.self, forCellReuseIdentifier: MPPositive_HomeShowTableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        return tableView
    }()
    private let MPPositive_HomeSinglesTableViewCellID = "MPPositive_HomeSinglesTableViewCell"
    private let MPPositive_HomeShowTableViewCellID = "MPPositive_HomeShowTableViewCell"
    private var browseModuleLists:[MPPositive_BrowseModuleListViewModel]! = []{
        didSet{
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                if browseModuleLists != nil{
                    configure()
                    reload()
                    removeErrorView()
                    MP_HUD.hideNow()
                }
            }
        }
    }
    private var browseId:String!
    private var params:String!
    private var titleText:String!
    init(_ browseId:String, params:String, title:String) {
        self.browseId = browseId
        self.params = params
        self.titleText = title
        super.init(nibName: nil, bundle: nil)
        //执行网络请求获取对应模块详情数据
        MP_HUD.loading()
        MP_NetWorkManager.shared.requestMoodDetails(browseId, params: params) { [weak self] result in
            guard let self = self else {return}
            browseModuleLists = result
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置页面标题
        setTitle(titleText)
        setPopBtn()
        errorBlock = {
            [weak self] in
            guard let self = self else {
                return
            }
            //移除所有（除了navView）的子控件，并告知页面处理错误，提示用户重试
            view.subviews.forEach { item in
                if item != self.navView {
                    //移除
                    if item.superview != nil {
                        item.removeFromSuperview()
                    }
                }
            }
            //添加报错View
            setErrorView()
            MP_HUD.hideNow()
        }
        retryBlock = {
            [weak self] in
            guard let self = self else {return}
            MP_HUD.loading()
            MP_NetWorkManager.shared.requestMoodDetails(browseId, params: params) { [weak self] result in
                guard let self = self else {return}
                browseModuleLists = result
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reload()
    }
    //页面刷新
    private func reload() {
        tableView.reloadData()
    }
    private func configure() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(navView.snp.bottom).offset(20*width)
        }
    }
}
//MARK: - tableView
extension MPPositive_GrideMoodViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return browseModuleLists.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let first = browseModuleLists[indexPath.section].items.first, first.browseItem.itemType == .single, first.browseItem.pageType == "MUSIC_VIDEO_TYPE_ATV" {
            //是单曲
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_HomeSinglesTableViewCellID, for: indexPath) as! MPPositive_HomeSinglesTableViewCell
            cell.browseViewModel = browseModuleLists[indexPath.section]
            
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_HomeShowTableViewCellID, for: indexPath) as! MPPositive_HomeShowTableViewCell
            cell.browseViewModel = browseModuleLists[indexPath.section]
            if let first = browseModuleLists[indexPath.section].items.first, first.browseItem.itemType == .single, first.browseItem.pageType == "MUSIC_VIDEO_TYPE_OMV" {
                cell.showType = .Fifth
            }else {
                //判断是列表还是艺术家
                if browseModuleLists[indexPath.section].items.first?.browseItem.pageType == "MUSIC_PAGE_TYPE_ARTIST" {
                    cell.showType = .Fourth
                }else {
                    cell.showType = .Third
                }
            }
            cell.requestNextBlock = {
                [weak self] (item) in
                guard let self = self else {return}
                switch item.browseItem.itemType {
                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("Mood")
                        //优先清除数据
                        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:
                    //列表专辑
                    let listVC = MPPositive_ListShowViewController(item.browseItem.browseId ?? "", params: "", title: item.title ?? "", subtitle: item.subtitle ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                    navigationController?.pushViewController(listVC, animated: true)
                case .artist:
                    //前往艺术家页面
                    let artistVC = MPPositive_ArtistShowViewController(item.browseItem.artistId ?? "", clickTrackingParams: item.browseItem.clickTrackingParams ?? "")
                    navigationController?.pushViewController(artistVC, animated: true)
                default:
                    break
                }
            }
            cell.findMoreBlock = {
                [weak self] in
                guard let self = self else {return}
                let moreVC = MPPositive_MoreContentViewController(browseModuleLists[indexPath.section])
                navigationController?.pushViewController(moreVC, animated: true)
            }
            return cell
        }
    }
}
