//
//  TSThemeSetVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/3.
//

class TSThemeSetVC: TSBaseVC {
    
    
    var model:TSThemeModel
    var duration:Float
    
    var getNeedVip:Bool{
        if model.vip{
            return true
        }
        return false
    }

    lazy var audioPlayer = TSBusinessAudioPlayer{ [weak self] state in
        guard let self = self else { return }
        audioPlayerStateChange(state: state)
    }

    lazy var contactsTool: TSContactsTool = {
        let contactsTool = TSContactsTool(targetVC: self)
        return contactsTool
    }()
    
    
    lazy var ringView: TSThemeSetRingToneView = {
        let ringView = TSThemeSetRingToneView()
        ringView.moreInfoBtn.isHidden = true
        ringView.setBtn.addTarget(self, action: #selector(clickSetRing), for: .touchUpInside)
        ringView.setClickPlayHandel { [weak self] paly in
            guard let self = self else { return }
            clickPlay()
        }
        return ringView
    }()
    
    lazy var posterView: TSThemeSetPosterView = {
        let posterView = TSThemeSetPosterView()
        posterView.setBtn.addTarget(self, action: #selector(clickSetPoster), for: .touchUpInside)
        posterView.moreInfoBtn.addTarget(self, action: #selector(clickSetMoreInfoPoster), for: .touchUpInside)
        return posterView
    }()
    
    lazy var photoView: TSThemeSetPhotorView = {
        let photoView = TSThemeSetPhotorView()
        photoView.setBtn.addTarget(self, action: #selector(clickPhoto), for: .touchUpInside)
        photoView.moreInfoBtn.addTarget(self, action: #selector(clickSetMoreInfoPhoto), for: .touchUpInside)
        return photoView
    }()
    
    lazy var stackView : TSCustomStackView = {
        let stackView = TSCustomStackView(axis: .vertical,spacing: 16)
        return stackView
    }()
    
    init(model: TSThemeModel, duration: Float) {
        self.model = model
        self.duration = duration
        super.init()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    var avatarImage:UIImage?{
        return photoView.netWorkImageView.image
    }
    
    override func createView() {
        setViewBgImageNamed(named: kViewBJ)
        addNormalNavBarView()
        setPageTitle("Set Theme".localized)
        
        _ = setNavigationItem("", imageName: "tutorials", direction: .right, action: #selector(clickRight))

        contentView.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.bottom.equalTo(0)
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
        }
        
        stackView.addSubviewToStack(ringView)
        stackView.addSubviewToStack(posterView)
        stackView.addSubviewToStack(photoView)
    
    }
    
    override func dealThings() {
        ringView.cellView.nameLab.text = model.ringtoneName
        ringView.cellView.setCoverImageView(urlString: model.ringtoneCover)
        ringView.cellView.timeLab.text = duration.floatToMinuteSecond()
        posterView.netWorkImageView.setAsyncImage(urlString: model.poster,contentMode: .scaleAspectFill)
        photoView.netWorkImageView.setAsyncImage(urlString: model.photo,contentMode: .scaleAspectFill)
        

        NotificationCenter.default.addObserver(self, selector: #selector(vipInfoChanged), name: .kPurchaseDidChanged, object: nil)
        setVipUI()
    }
    
    @objc func vipInfoChanged() {
        kExecuteOnMainThread {
            self.setVipUI()
        }
    }
    
    func setVipUI(){
        self.ringView.setBtn.setImage(getNeedVip ? UIImage(named: "vip_icon_white"): nil, for: .normal)
        self.posterView.setBtn.setImage(getNeedVip ? UIImage(named: "vip_icon_white"): nil, for: .normal)
        self.photoView.setBtn.setImage(getNeedVip ? UIImage(named: "vip_icon_white"): nil, for: .normal)
    }
    

    func audioPlayerStateChange(state:TSBusinessAudioPlayer.PlayerState){
        switch state {
        case .loading(let progress):
            if progress == 0.0 {
                ringView.cellView.isloading = true
            }else if progress == 1.0 {
                ringView.cellView.isloading = false
            }
        case .play:
            ringView.cellView.isPlay = true
        case .stop:
            ringView.cellView.isPlay = false
        default:
            break
        }
    }
    
    @objc func clickRight(){
        let browseVC = TSThemeTutorialsVC()
        kPushVC(target: self, modelVC: browseVC)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        audioPlayer.stop()
    }

}

extension TSThemeSetVC {
    
    @objc func clickPlay(){
        if audioPlayer.isPlaying{
            audioPlayer.stop()
        }else{
            audioPlayer.playUrlString( model.ringtone)
        }
    }
    
    @objc func clickSetRing(){
        audioPlayer.stop()
//        if kPurchaseToolShared.kJudgeVip(externalBool: getNeedVip, vc: self){ return }//判断 vip
        _ = kPurchaseToolShared.kshareBand(needVip: getNeedVip, vc: self, urlString: model.ringtone, fileName:  model.name)
        
    }
    
    @objc func clickSetPoster(){
        
        if kPurchaseToolShared.kJudgeVip(externalBool: getNeedVip, vc: self){ return }//判断 vip
        
        if let image = posterView.netWorkImageView.image{
            PhotoManagerShared.saveImageToAlbum(image) { success, error in
                if success {
                    kSavePhotoSuccesswShared.show(atView: self.view)
                }else{
                    debugPrint(error)
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }
    
    @objc func clickPhoto(){
        
        if kPurchaseToolShared.kJudgeVip(externalBool: getNeedVip, vc: self){ return }//判断 vip
        
        guard let photo = avatarImage else { return }
        contactsTool.setContactsAvatar(avatarImage: photo) { data, error in
            if error == nil {
                kSavePhotoSuccesswShared.show(atView: self.view,showViewBtn: false)
            }
        }
    }
    
    @objc func clickSetMoreInfoPoster(){
        kPresentModalVC(target: self, modelVC: TSTutorialPopupVC(selectedIndex: 0),transitionStyle: .crossDissolve)
    }
    
    @objc func clickSetMoreInfoPhoto(){
        kPresentModalVC(target: self, modelVC: TSTutorialPopupVC(selectedIndex: 1),transitionStyle: .crossDissolve)
    }

}

