//
//  TSAIRintoneVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/2/27.
//
import SwipeCellKit

class TSAIRintoneVC: TSBaseVC {
    
    lazy var viewModel : TSAIRintoneVM = {
        let viewModel = TSAIRintoneVM()
        return viewModel
    }()

    lazy var navBarView: TSBaseNavContentBarView = {
        let navBarView = TSBaseNavContentBarView()

        let titleImageView = UIImageView.createImageView(imageName: "nav_title_aiRing",contentMode: .scaleToFill)
        navBarView.barView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(375)
            make.height.equalTo(48)
        }

        return navBarView
    }()

    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
        layout.headerReferenceSize = CGSizeMake(k_ScreenWidth, 62)
        layout.footerReferenceSize = CGSizeMake(k_ScreenWidth, 48)
        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.register(TSAIRintoneHistoryCell.self, forCellWithReuseIdentifier: TSAIRintoneHistoryCell.cellID)
        collectionView.register(TSAIRintoneHistorySectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: TSAIRintoneHistorySectionHeaderView.reuseIdentifier)
        collectionView.register(TSAIRintoneHistorySectionFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: TSAIRintoneHistorySectionFooterView.reuseIdentifier)
        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)
        
        edgesForExtendedLayout = []
        navBarContentView.addSubview(navBarView)
        navBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        let vcViewH = generalRintoneVC.viewH
        collectionView.addSubview(generalRintoneVC.view)
        generalRintoneVC.view.snp.makeConstraints { make in
            make.top.equalTo(-vcViewH)
            make.leading.trailing.equalTo(0)
            make.height.equalTo(vcViewH)
        }
        
        collectionView.contentInset = UIEdgeInsets(top: vcViewH, left: 0, bottom: 20, right: 0)

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        TSBusinessAudioPlayer.shared.stop()
    }
    
    override func dealThings() {
        updateListView()
        viewModel.getRingRecommend(useCache: false) { [weak self]  in guard
            let self = self else { return }
            collectionView.reloadData()
        }
    }
    
    func updateListView(){
        collectionView.reloadData()
    }
    

}

extension TSAIRintoneVC: 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) {
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if let sectionModel = viewModel.modelList.safeObj(At: indexPath.section) {
            if kind == UICollectionView.elementKindSectionHeader {
                if let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TSAIRintoneHistorySectionHeaderView.reuseIdentifier, for: indexPath) as? TSAIRintoneHistorySectionHeaderView {
                    header.titleView.titleLab.text = sectionModel.title
                    header.rightBtn.isHidden = true
                    if sectionModel.type == .history {
                        header.rightBtn.isHidden = false
                        header.rightBtn.setUpButton{ [weak self]  in
                            guard let self = self else { return }
                            
                            let vc = TSGenerateHistoryVC()
                            vc.reloadUIBlock = { [weak self]  in
                                guard let self = self else { return }
                                viewModel.updateRecentData()
                                updateListView()
                            }
                            kPushVC(target: self, modelVC: vc)
                        }
                    }
        
                    return header
                }
            }else if kind == UICollectionView.elementKindSectionFooter{//},indexPath.section == (viewModel.modelList.count-1) {
                if let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TSAIRintoneHistorySectionFooterView.reuseIdentifier, for: indexPath) as? TSAIRintoneHistorySectionFooterView {
                    footer.clickView = {
                        let ringCategoryModel = TSRingCategoryModel()
                        ringCategoryModel.title = "TikTok"
                        ringCategoryModel.cover = "http://d3a93z8fj970a4.cloudfront.net/0c359196-aeeb-45e6-bc98-eddf50f1dd53"
                        ringCategoryModel.categoryId = "Best of TikTok"
                        kPushVC(target: self, modelVC: TSDiscoverListVC(ringCategoryModel: ringCategoryModel))
                    }
                    return footer
                }
            }
        }
        return UICollectionReusableView()
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if let sectionModel = viewModel.modelList.safeObj(At: section) {
            if  sectionModel.type == .recommend {
                return  CGSizeMake(k_ScreenWidth, 48)
            }
        }
        return .zero
    }
    

}

extension TSAIRintoneVC: SwipeCollectionViewCellDelegate {
    
    func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }
        
        if indexPath.section != 0 {
            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? TSActionInfoModel {
                        collectionView.performBatchUpdates({
                            self.viewModel.removeModel(model: model)
                            if sectionModel.list.count == 0 {
                                collectionView.deleteSections([indexPath.section])
                            }else{
                                collectionView.deleteItems(at: [indexPath])
                            }
                        })
                        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
    }
    
}
