//
//  TSThemeBrowseVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/2.
//
private let cellId = "TSThemeBrowseCell"
class TSThemeBrowseVC: TSBaseVC {
    
    var currentIndex:Int{
        didSet {
            browseViewModel.setFinallyIndex(currentIndex,ringtone:currentModel?.ringtone)
        }
    }
    var themeViewModel:TSThemeVM
    var closePage:()->Void
    

    lazy var audioPlayer = TSBusinessAudioPlayer.shared
    
    lazy var browseViewModel: TSThemeBrowseVM = {
        browseViewModel = TSThemeBrowseVM()
        browseViewModel.audioPlayer = audioPlayer
        return browseViewModel
    }()

    var currentRingtone:String?
    
    var currentModel:TSThemeModel?{
        return themeViewModel.listModelArray.safeObj(At: currentIndex)
    }
    init(currentIndex:Int,themeViewModel: TSThemeVM, closePage: @escaping () -> Void) {
        self.currentIndex = currentIndex
        self.themeViewModel = themeViewModel
        self.closePage = closePage
        super.init()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var btnView: TSTBBtnView = {
        let btnView = TSTBBtnView(
            targetVC: self,
            closePageSelector: #selector(clickClosePage),
            copyrightSelector: #selector(clickNavCopyright),
            lockSelector:#selector(clickLock),
            callSelector: #selector(clickCall),
            soundSelector: #selector(clickSound),
            doneSelector: #selector(clickDone)
        )
        return btnView
    }()
    
    lazy var callPreview:TSTBCallPreviewView = {
        let callPreview = TSTBCallPreviewView()
        callPreview.closePage = { [weak self]  in
            guard let self = self else { return }
            btnView.isHidden = false
        }
        callPreview.isHidden = true
        return callPreview
    }()

    lazy var desktopPreview: TSTBDesktopPreviewView = {
        let desktopPreview = TSTBDesktopPreviewView()
        desktopPreview.closePage = { [weak self]  in
            guard let self = self else { return }
            btnView.isHidden = false
        }
        desktopPreview.isHidden = true
        return desktopPreview
    }()

    lazy var collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: k_ScreenWidth, height: k_ScreenHeight)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.scrollsToTop = false
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.register(TSThemeBrowseCell.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true

        collectionView.addLoadMore { [weak self]  in
            guard let self = self else { return }
            
            themeViewModel.getMoreData { [weak self] success,haveMore in
                guard let self = self else { return }
                if success {
                    collectionView.reloadData()
                }
                collectionView.endRefreshing(noMore: !haveMore)
            }
        }

        return collectionView
    }()
    
    
    
    override func createView() {

        setNavBarViewHidden(true)
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(btnView)
        btnView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(callPreview)
        callPreview.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(desktopPreview)
        desktopPreview.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
    }
    
    override func dealThings() {
        
        kDelayMainShort {
            self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: .bottom, animated: false)
        }
        
        browseViewModel.finallyIndex = currentIndex
        browseViewModel.finallyIndexChange = {[weak self]  in
            guard let self = self else { return }
            setVipUI()
        }
        
        setVipUI()
    
    }
    
    func setVipUI(){
        self.btnView.doneBtnView.setVip(vip: self.getNeedVip)
    }
    
    var getNeedVip:Bool{
        if let currentModel = self.currentModel {
            if currentModel.vip {
                return true
            }
        }
        return false
    }

}

extension TSThemeBrowseVC {
    
    func audioPlayerStateChange(state:TSBusinessAudioPlayer.PlayerState){
        switch state {
        case .loading(let progress):
            if progress == 0.0 {
                btnView.isSoundloadling = true
            }else if progress == 1.0 {
                btnView.isSoundloadling = false
            }
        case .volume(let volume):
            btnView.soundVolume = volume
        case .stop,.play,.pause:
            btnView.isSoundloadling = false
        default:
            break
        }
    }
    
    func setUpRingtone() {
        if let ringtone = currentModel?.ringtone {
            TSCommonTool.downloadAndCacheFile(from: ringtone) { path, error in
                if let path = path {
                    self.currentRingtone = path
                }else{
                    self.currentRingtone = nil
                }
            }
        }else{
            self.currentRingtone = nil
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        browseViewModel.audioPlayer?.stop()
        browseViewModel.audioPlayer?.setVolume(volume: 1.0)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        audioPlayer.stateChangedHandle = { [weak self] state  in
            guard let self = self else { return }
            self.audioPlayerStateChange(state: state)
        }
        
        if browseViewModel.audioPlayer?.playerUsable == true {
            browseViewModel.audioPlayer?.setVolume(volume: 1.0)
            browseViewModel.audioPlayer?.play()
        }else{
            browseViewModel.audioPlayer?.playUrlString( currentModel?.ringtone,loop: true)
        }
    }
}

extension TSThemeBrowseVC {
    @objc func clickClosePage(){
        self.pop()
        self.closePage()
    }
    
    @objc func clickNavCopyright(){
        navigationController?.pushViewController(TSThemeCopyrightVC(), animated: true)
    }
    
    @objc func clickLock(){
        btnView.isHidden = true
        callPreview.urlString = currentModel?.poster
        callPreview.isHidden = false
    }
    
    @objc func clickCall(){
        btnView.isHidden = true
        desktopPreview.urlString = currentModel?.photo
        desktopPreview.islandView.nameLab.text = currentModel?.name
        desktopPreview.isHidden = false
    }
    
    @objc func clickSound(){
        let volume = audioPlayer.changeAudioSwitch()
        btnView.soundVolume = volume
    }
    
    @objc func clickDone(){
        if let currentModel = currentModel {
            let setVC = TSThemeSetVC(model: currentModel, duration: Float(audioPlayer.duration))
            kPushVC(target: self, modelVC: setVC)
        }
    }
    
    
}

//MARK: UICollectionViewDataSource
extension TSThemeBrowseVC:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        dePrint("scrollViewDidEndDecelerating")
        resetIndexWithOffset(scrollView)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        dePrint("scrollViewDidEndScrollingAnimation")
        resetIndexWithOffset(scrollView)
    }

    private func resetIndexWithOffset(_ scrollView: UIScrollView) {
        let item = Int((scrollView.contentOffset.y / scrollView.bounds.height).rounded())
        currentIndex = item
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return themeViewModel.listModelArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TSThemeBrowseCell
        if let model = themeViewModel.listModelArray.safeObj(At: indexPath.item){
            cell.netWorkImageView.setAsyncImage(urlString: model.poster,placeholder:kPlaceholderImage,contentMode: .scaleAspectFill)
            cell.islandView.showImageView.setAsyncImage(urlString: model.photo,placeholder:kPlaceholderImage,contentMode: .scaleAspectFill)
            cell.islandView.nameLab.text = model.name
        }
        return cell
    }
    
}

class TSThemeBrowseCell : TSBaseCollectionCell{

    lazy var islandView : TSTSIslandView = {
        let islandView = TSTSIslandView()
        return islandView
    }()
    
    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView()
        return netWorkImageView
    }()
    
    override func creatUI() {
     
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(k_ScreenWidth)
            make.height.equalTo(kDesignScale*812)
        }

        bgContentView.addSubview(islandView)
        islandView.snp.makeConstraints { make in
            make.top.equalTo(k_Nav_Height+10)
            make.centerX.equalToSuperview()
            make.width.equalTo(islandView.width)
            make.height.equalTo(islandView.height)
        }
    }
}
