//
//  RoleDialogStyleSetController.swift

//
//  Created by Leon on 2025/7/20.
//

import UIKit

/// Step 3/4
class RoleDialogStyleSetController: RoleCreateBaseController<RoleDialogStyleSetView> {
    weak var viewModel: RoleCreateViewModel!
    
    lazy var rolePublish: RolePublishController = RolePublishController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViews()
        setupDats()
        setupEvents()
    }

    private func setupViews() {

    }

    private func setupDats() {
//        if let voice = AppDictManager.shared.aiDict?.timbreDictList?.first{
//            container.selectVoice = voice
//        }
        
        
    }
    
    private func restoreEditInfo(aiInfo: AIUserModel?) {
        guard let info = aiInfo else { return }
        
        container.dialogStyleContent = info.aiUserExt?.dialogueStyle ?? ""
        container.openingContent = info.aiUserExt?.dialoguePrologue ?? ""
        
        if let timbreDict = info.aiUserExt?.timbreDict{
            var voiceModel = VoiceModel(voiceDict: timbreDict)
            if let dialoguePitch = info.aiUserExt?.dialoguePitch{
                voiceModel.dialoguePitch = dialoguePitch
            }
            if let dialogueSpeechRate = info.aiUserExt?.dialogueSpeechRate{
                voiceModel.dialogueSpeechRate = dialogueSpeechRate
            }
            container.selectVoice = voiceModel
            
        }

    }

    private func setupEvents() {
        container.backButton.addTarget(self, action: #selector(tapBackButton), for: .touchUpInside)
        container.bottomButton.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
        container.generate1Button.addTarget(self, action: #selector(tapGenerate1Button), for: .touchUpInside)
        container.generate2Button.addTarget(self, action: #selector(tapGenerate2Button), for: .touchUpInside)
        container.vocieSelectView.selectBlock = {[weak self] in
            self?.goVoiceSetup()
        }
        
        restoreEditInfo(aiInfo: viewModel.editAIInfo)
    }
    
    private func goVoiceSetup(){
        guard AppDictManager.shared.aiDict != nil else{
            Hud.showIndicator()
            AppDictManager.shared.loadAIDict { _ in
                Hud.hideIndicator()
            }
            return
        }
        
        let vc = RoleVoiceSetController()
        vc.viewModel = viewModel
        vc.sexSelect = viewModel.requestParams.sex
        vc.selectVoiceBefore = container.selectVoice
        vc.selectVoiceAction = {[weak self] voice in
            self?.container.selectVoice = voice
        }
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc private func tapBottomButton() {
        let dialogueStyle = container.dialogStyleContent.trimmed
        viewModel.requestParams.userDialogueStyle = dialogueStyle
        viewModel.requestParams.aiUserExt?.dialogueStyle = dialogueStyle
        viewModel.requestParams.aiUserExt?.dialoguePrologue = container.openingContent.trimmed
        
        guard let voice = container.selectVoice else { return }
        viewModel.requestParams.aiUserExt?.dialogueTimbreCode = voice.voiceDict.code
        viewModel.requestParams.aiUserExt?.dialoguePitch = voice.dialoguePitch
        viewModel.requestParams.aiUserExt?.dialogueSpeechRate = voice.dialogueSpeechRate
        viewModel.requestParams.aiUserExt?.dialogueTimbreUrl = voice.voiceDict.url
        
        let vc = rolePublish
        vc.viewModel = viewModel
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc private func tapBackButton() {
        close()
    }
    
    @objc private func tapGenerate1Button(){
        if container.dialogStyleContent.count > 0{
            let alert = Alert(title: "内容覆盖", text: "AI创建的内容会覆盖你已经填写的内容，请确认是否继续？")
            let action1 = AlertAction(title: "继续", actionStyle: .confirm) {[weak self] in
                self?.doGenerate1()
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()
        }else{
            doGenerate1()
        }
    }
    
    private func doGenerate1(){
        var params = viewModel.requestParams.toPartialDictionary(keys: ["nickname", "sex", "birthday", "characterCode", "tagCode", "introduction"])
        if container.dialogStyleContent.count > 0{
            /// 根据用户输入进行生成开场白
//            params.updateValue("GEN_DIALOG_STYLE_BY_CONTENT", forKey: "ptType")
            params.updateValue(container.dialogStyleContent, forKey: "content")
        }else{
            /// 完全AI生成开场白
//            params.updateValue("GEN_DIALOG_STYLE_BY_NON", forKey: "ptType")
        }
        params.updateValue("GEN_DIALOG_STYLE_BY_NON", forKey: "ptType")
    
        Hud.showIndicator()
        AICowProvider.request(.aiContentGenerate(params: params), modelType: AIUserContentGenResponse.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let success):
                if let content = success?.content{
                     self?.container.dialogStyleAIGenerated = content
                }
            case .failure:
                return
            }
        }
    }
    
    @objc private func tapGenerate2Button(){
        if container.openingContent.count > 0{
            let alert = Alert(title: "内容覆盖", text: "AI创建的内容会覆盖你已经填写的内容，请确认是否继续？")
            let action1 = AlertAction(title: "继续", actionStyle: .confirm) {[weak self] in
                self?.doGenerate2()
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()
        }else{
            doGenerate2()
        }
    }
    
    private func doGenerate2(){
        var params = viewModel.requestParams.toPartialDictionary(keys: ["nickname", "sex", "birthday", "characterCode", "tagCode", "introduction"])
        //dlog("当前的prams[只生成部分]:\(params)")
        
        if container.openingContent.count > 0{
            /// 根据用户输入进行生成开场白
//            params.updateValue("GEN_PROLOGUE_BY_CONTENT", forKey: "ptType")
            params.updateValue(container.openingContent, forKey: "content")
        }else{
            /// 完全AI生成开场白
//            params.updateValue("GEN_PROLOGUE_BY_NON", forKey: "ptType")
        }
        params.updateValue("GEN_PROLOGUE_BY_NON", forKey: "ptType")
    
        Hud.showIndicator()
        AICowProvider.request(.aiContentGenerate(params: params), modelType: AIUserContentGenResponse.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let success):
                if let content = success?.content{
                     self?.container.openingAIGenerated = content
                }
            case .failure:
                return
            }
        }
    }
}

