//
//  TSGenerateHistoryVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/18.
//
import SwipeCellKit
class TSGenerateHistoryVC: TSBaseVC {

    lazy var viewModel : TSGenerateHistoryVM = {
        let viewModel = TSGenerateHistoryVM()
        return viewModel
    }()
    
    var reloadUIBlock:(()->Void)?
    
    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
    }()
    

    lazy var generalRintoneVC: TSTextGeneralRintoneVC = {
        let generalRintoneVC = TSTextGeneralRintoneVC()
        generalRintoneVC.reloadUIBlock = { [weak self]  in
            guard let self = self else { return }
            viewModel.updateRecentData()
            updateListView()
        }
        return generalRintoneVC
    }()

    override func createView() {
        
        setViewBgImageNamed(named: kViewBJ)
        
        addNormalNavBarView()
        setPageTitle("Generate History".localized)

        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() {
        updateListView()
        
        NotificationCenter.default.addObserver(forName: .kGenerateRintoneOperationChanged, object: nil, queue: nil) {[weak self] notification in
            guard let self = self else { return }
            if let userInfo = notification.userInfo as? [String: Any],let state = userInfo["state"] as? TSProgressState {
                switch state {
                case .start, .success(_),.failed(_),.none:
                    self.viewModel.updateRecentData()
                    self.updateListView()
                default:break
                }
            }
        }
    }
    
    func updateListView(){
        collectionView.reloadData()
    }
    
//    override func navBarClickLeftAction() {
//        super.navBarClickLeftAction()
//        self.reloadUIBlock?()
//    }

}

extension TSGenerateHistoryVC: 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
        {
            weak var weakSelf = self
            cell.delegate = weakSelf
            cell.setRingBtn.indexPath = indexPath
            cell.setRingBtn.addTarget(weakSelf, action: #selector(clickSetRingBtn(_ :)), for: .touchUpInside)
            if let model = itemModel as? TSActionInfoModel {
                cell.model = model
            }else if let ringModel = itemModel as? TSRingModel {
                cell.ringModel = ringModel
            }
        }
        
        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)
//                    }
//                }
            }
        }
        TSBusinessAudioPlayer.shared.stop()
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
}

extension TSGenerateHistoryVC: SwipeCollectionViewCellDelegate {
    
    func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }
        
        if indexPath.section != 0 {
            return nil
        }
        
        if let sectionModel = self.viewModel.modelList.safeObj(At: indexPath.section),
        let model = sectionModel.list.safeObj(At: indexPath.item){
            if let model = model as? TSActionInfoModel {
                switch model.actionStatus {
                case .pending,.running:
                    return nil
                default:break
                }
            }
        }
        
        // 删除操作
        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:  { [weak self]  in
                guard let self = self else { return }
                if let sectionModel = self.viewModel.modelList.safeObj(At: indexPath.section),
                let model = sectionModel.list.safeObj(At: indexPath.item){
                    if let model = model as? TSActionInfoModel {
//                        collectionView.performBatchUpdates({
//                            self.viewModel.removeModel(model: model)
//                            if sectionModel.list.count == 0 {
//                                collectionView.deleteSections([indexPath.section])
//                            }else{
//                                collectionView.deleteItems(at: [indexPath])
//                            }
//                        })
                        self.viewModel.removeModel(model: model)
                        collectionView.reloadData()
                        
                        TSBusinessAudioPlayer.shared.stop()
                    }
                }
            })
        }
        
        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
    }
    
}
