//
//  TSDiscoverListVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/17.
//

class TSDiscoverListVC: TSBaseVC {
    
    var reloadUIBlock:(()->Void)?
    
    var ringCategoryModel:TSRingCategoryModel
    init(ringCategoryModel: TSRingCategoryModel) {
        self.ringCategoryModel = ringCategoryModel
        super.init()
    }

    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var viewModel:TSDiscoverListVM = {
        let viewModel = TSDiscoverListVM(categoryID:ringCategoryModel.categoryId,animationView: self.view)
        return viewModel
    }()
    
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: k_ScreenWidth-32, height: 74)
        layout.minimumInteritemSpacing = 10.0
        layout.minimumLineSpacing = 18.0
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 16, right: 0)
        collectionView.register(TSAIRintoneHistoryCell.self, forCellWithReuseIdentifier: TSAIRintoneHistoryCell.cellID)
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        
        collectionView.addRefresh{ [weak self]  in
            guard let self = self else { return }
            TSBusinessAudioPlayer.shared.stop()
            viewModel.reloadAllData { [weak self] success  in
                guard let self = self else { return }
                if success {
                    updateListView()
                }
                collectionView.endRefreshing()
            }
        }

        collectionView.addLoadMore { [weak self]  in
            guard let self = self else { return }

            viewModel.getMoreData { [weak self] success,haveMore in
                guard let self = self else { return }
                if success {
                    updateListView()
                }
                collectionView.endRefreshing(noMore: !haveMore)
            }
        }
        
        return collectionView
    }()
    
    override func createView() {
        
        setViewBgImageNamed(named: kViewBJ)
        
        addNormalNavBarView()
        setPageTitle(ringCategoryModel.title)

        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        TSBusinessAudioPlayer.shared.stop()
    }
    
    override func dealThings() {
        viewModel.getData {[weak self] success in
            guard let self = self else { return }
            if success {
                updateListView()
            }
        }
    }
    
    override func navBarClickLeftAction() {
        super.navBarClickLeftAction()
        reloadUIBlock?()
    }
    func updateListView(){
        collectionView.reloadData()
    }
    

}

extension TSDiscoverListVC: UICollectionViewDataSource ,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.modelList.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let sectionModel = viewModel.modelList.safeObj(At: section) {
            return sectionModel.list.count
        }
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TSAIRintoneHistoryCell.cellID, for: indexPath)
        
        if let sectionModel = viewModel.modelList.safeObj(At: indexPath.section),
            let itemModel = sectionModel.list.safeObj(At: indexPath.item),
           let cell = cell as? TSAIRintoneHistoryCell
        {
            if let model = itemModel as? TSActionInfoModel {
                cell.model = model
            }else if let ringModel = itemModel as? TSRingModel {
                cell.ringModel = ringModel
            }
            
            cell.setRingBtn.indexPath = indexPath
            cell.setRingBtn.addTarget(self, action: #selector(clickSetRingBtn(_ :)), for: .touchUpInside)
        }
        
        return cell
    }

    @objc func clickSetRingBtn(_ btn:TSUIExpandedTouchButton){
        let indexPath = btn.indexPath
        if let sectionModel = self.viewModel.modelList.safeObj(At: indexPath.section),
        let itemModel = sectionModel.list.safeObj(At: indexPath.item){
//            if let model = itemModel as? TSActionInfoModel {
//                _ = kPurchaseToolShared.kshareBand(needVip: model.response.vip, vc: self, urlString: model.response.musicUrl, fileName: model.response.title)
//            }else
            if let ringModel = itemModel as? TSRingModel {
                _ = kPurchaseToolShared.kshareBand(needVip: ringModel.vip, vc: self, urlString: ringModel.audioUrl, fileName: ringModel.title){ success in
                    if success {
                        TSMineRintoneHistory.saveModel(model: ringModel)
                    }
                }
            }
        }
        TSBusinessAudioPlayer.shared.stop()
    }
}
