//
//  TSRingDownVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/17.
//
import SwipeCellKit
class TSRingDownVC: TSBaseVC {
    
    lazy var nullView:TSRingDownNullView = TSRingDownNullView{ [weak self]  in
        guard let self = self else { return }
        let ringCategoryModel = TSRingCategoryModel()
        ringCategoryModel.title = "Popular"
        ringCategoryModel.cover = "http://d3a93z8fj970a4.cloudfront.net/fbae944d-9e49-46ee-a51f-78f75a1952e8"
        ringCategoryModel.categoryId = "Popular"
        
        
        let vc = TSDiscoverListVC(ringCategoryModel: ringCategoryModel)
        vc.reloadUIBlock = { [weak self]  in
            guard let self = self else { return }
            viewModel.updateRecentData()
            updateListView()
        }
        kPushVC(target: self, modelVC:vc)
    }
    
    var reloadUIBlock:(()->Void)?
    
    lazy var viewModel:TSRingDownVM = {
        let viewModel = TSRingDownVM()
        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
        }

        return collectionView
    }()
    
    
    override func createView() {
 
        addNormalNavBarView()
        setPageTitle("Mine".localized)
        _ = setNavigationItem("", imageName: "tutorials", direction: .right, action: #selector(clickRight))

        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        nullView.isHidden = true
        contentView.addSubview(nullView)
    }
    
    @objc func clickRight(){
        kPushVC(target: self, modelVC: TSThemeTutorialsVC())
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        TSMineRintoneHistory.isHaveNew = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        TSBusinessAudioPlayer.shared.stop()
    }
    
    override func dealThings() {
        updateListView()
    }
    
    override func navBarClickLeftAction() {
        super.navBarClickLeftAction()
        reloadUIBlock?()
    }
    
    func updateListView(){
        nullView.isHidden = viewModel.modelList.count > 0
        collectionView.reloadData()
    }
}

extension TSRingDownVC: 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
        {
            cell.delegate = self
            
            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 model = sectionModel.list.safeObj(At: indexPath.item){
//            if let model = model as? TSActionInfoModel {
//                _ = kPurchaseToolShared.kshareBand(needVip: model.response.vip, vc: self, urlString: model.response.musicUrl, fileName: model.response.title)
//            }else

            if let ringModel = model as? TSRingModel {
                _ = kPurchaseToolShared.kshareBand(needVip: ringModel.vip, vc: self, urlString: ringModel.audioUrl, fileName: ringModel.title)
//                { success in
//                    if success {
//                        TSMineRintoneHistory.saveModel(model: ringModel)
//                    }
//                }
            }
        }
        
        collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
        TSBusinessAudioPlayer.shared.stop()
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
}

extension TSRingDownVC: SwipeCollectionViewCellDelegate {
    
    func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }

        // 删除操作
        let deleteAction = SwipeAction(style: .destructive, title: nil) {[weak self] action, indexPath in
            guard let self = self else { return }
            showCustomAlert(message: "Are you sure to delete".localized, deleteHandler:  {
                if let sectionModel = self.viewModel.modelList.safeObj(At: indexPath.section),
                let model = sectionModel.list.safeObj(At: indexPath.item){
                    if let model = model as? TSRingModel {
                        collectionView.performBatchUpdates({
                            self.viewModel.removeModel(model: model)
                            if sectionModel.list.count == 0 {
                                collectionView.deleteSections([indexPath.section])
                            }else{
                                collectionView.deleteItems(at: [indexPath])
                            }
                        })
                        
                        self.nullView.isHidden = self.viewModel.modelList.count > 0
                    }
                }
            })
        }
        
        deleteAction.backgroundColor = "#E83E3E".uiColor
        deleteAction.image = UIImage(named: "delete_white")
        
        return [deleteAction]
    }
    
    func collectionView(_ collectionView: UICollectionView, editActionsOptionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
        var options = SwipeOptions()
//        options.expansionStyle = .destructive(automaticallyDelete: false) // 完全滑动时是否自动触发操作
        options.transitionStyle = .border // 滑动动画样式
        return options
    }
    
}
