//
//  TSGeneralRintoneVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/6.
//

class TSGeneralRintoneVC: TSBottomAlertVC {
    
    var infoModel:TSActionInfoModel?
    var complete:((TSActionInfoModel)->Void)
    
    var aiText:String
    init(aiText: String,complete:@escaping ((TSActionInfoModel)->Void)) {
        self.aiText = aiText
        self.complete = complete
        super.init()
    }
    
    lazy var viewModel: TSGeneralRintoneVM = {
        let viewModel:TSGeneralRintoneVM = TSGeneralRintoneVM()
        viewModel.aiText = aiText
        return viewModel
    }()
    
    lazy var audioPlayer = TSBusinessAudioPlayer{ [weak self] state in
        guard let self = self else { return }
        audioPlayerStateChange(state: state)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var ringView: TSRingToneCellView = {
        let ringToneView = TSRingToneCellView()
        ringToneView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickPlay)))
        return ringToneView
    }()
    
    //############################## 生成动画 ##############################
    lazy var generateInView : TSCommonloadingView = {
        let generateInView = TSCommonloadingView()
        generateInView.cancelBtn.addTarget(self, action: #selector(closePage), for: .touchUpInside)
        return generateInView
    }()

    override func createView() {
        super.createView()
        
        view.addSubview(generateInView)
        generateInView.snp.makeConstraints { make in
            make.top.bottom.leading.trailing.equalTo(0)
        }

        diyView.addSubview(ringView)
        ringView.snp.makeConstraints { make in
            make.top.equalTo(98)
            make.centerX.equalToSuperview()
            make.width.equalTo(k_ScreenWidth - 40)
            make.height.equalTo(72)
        }
        
        diyView.addSubview(regenerateBtn)
        regenerateBtn.snp.makeConstraints { make in
            make.top.equalTo(ringView.snp.bottom).offset(16)
            make.centerX.equalToSuperview()
        }
        saveBtn.setTitle("Set As Ringtone".localized, for: .normal)
        resultIconImageView.image = resultIcon
        bottomViewH = 340.0
        bgImageView.addShadow(shadowColor: "#E6E229".uiColor.cgColor, shadowOffset: .zero, shadowRadius: 20, shadowOpacity: 0.8)
        
        diyView.addSubview(failView)
        failView.snp.updateConstraints { make in
            make.centerY.equalToSuperview().offset(0)
        }
    }
    
    @objc override func closePage() {
        viewModel.cancelAllRequest()
        self.dismiss(animated: true, completion: nil)
    }
    
    override func clickAgainBtn() {
        audioPlayer.stop()
        if kPurchaseToolShared.kJudgeVipFreeType(vipFreeNumType: .ringtones, vc: self){ return }//判断 vip
        viewModel.creatRintone(text:aiText)
    }
    
    @objc override func clickSubmitBtn(){
        
        guard let model = infoModel else {
            kShowToastDataMissing()
            return
        }
        audioPlayer.stop()
        _ = kPurchaseToolShared.kshareBand(needVip: model.response.vip, vc: self, urlString: model.response.musicUrl, fileName: model.response.title)
    }
    
    @objc func clickPlay(){
        if audioPlayer.isPlaying{
            audioPlayer.stop()
        }else{
            audioPlayer.playUrlString( infoModel?.response.musicUrl)
        }
    }
    
    override func dealThings() {
        if kPurchaseToolShared.kJudgeVipFreeType(vipFreeNumType: .ringtones, vc: self){ return }//判断 vip
        viewModel.creatRintone(text: self.aiText)
        viewModel.$stateDatauPblished.receive(on: DispatchQueue.main).sink {[weak self]  (state,model) in
            guard let self = self else { return }
            self.upDateView(state: state, model: model)
        }.store(in: &cancellable)
    }
}

extension TSGeneralRintoneVC{
    func setRingViewData(model:TSActionInfoModel) {
        ringView.timeLab.text = Float(model.request.duration).floatToMinuteSecond()
        ringView.nameLab.text = model.response.title
        ringView.setCoverImageView(urlString: model.response.coverUrl)
    }
    
    func audioPlayerStateChange(state:TSBusinessAudioPlayer.PlayerState){
        switch state {
        case .loading(let progress):
            if progress == 0.0 {
                ringView.isloading = true
            }else if progress == 1.0 {
                ringView.isloading = false
            }
        case .play:
            ringView.isPlay = true
        case .stop:
            ringView.isPlay = false
        default:
            break
        }
    }
}

