//
//  RoleCharacterSetController.swift

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

import UIKit

/// Step 2/4
class RoleCharacterSetController: RoleCreateBaseController<RoleCharacterSetView> {
    weak var viewModel: RoleCreateViewModel!
    
    lazy var styleSetController:RoleDialogStyleSetController = RoleDialogStyleSetController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
    }

    private func setupDatas() {
       
    }
    
    private func restoreEditInfo(aiInfo: AIUserModel?) {
        guard let info = aiInfo else { return }
        
        container.nickname = info.nickname ?? ""
        container.restoreNoneEditableSex(sex: info.sex)
        
        if let birthday = info.birthday{
            let date = Date.dateFromMilliseconds(Int64(birthday))
            let birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            container.birthdayStr = birthdayStr//"2000-07-09"
        }
        container.settingContent = info.aiUserExt?.profile ?? ""
        
    }

    private func setupEvents() {
        container.backButton.addTarget(self, action: #selector(tapBackButton), for: .touchUpInside)
        container.bottomButton.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
        container.generateButton.addTarget(self, action: #selector(tapGenerateButton), for: .touchUpInside)
        
        if viewModel.editAIInfo != nil{
            restoreEditInfo(aiInfo: viewModel.editAIInfo)
        }else{
            // Set gender to Male by default when creating an AI role.
            container.sexView.sex = .male
        }
    }

    @objc private func tapBottomButton() {
        
        guard container.nickname.count > 0 else {
            dlog("nickname is empty")
            return
        }
        Hud.showIndicator()
        UserOperator.checkname(name: container.nickname, uid: viewModel.editAIInfo?.aiId) {[weak self] nicknameOK in
            Hud.hideIndicator()
            if(nicknameOK){
                self?.doGoNextStepStyleSet()
            }
        }
        
    }
    
    private func doGoNextStepStyleSet(){
        viewModel.requestParams.nickname = container.nickname
        viewModel.requestParams.sex = container.sexSelect
        viewModel.requestParams.birthday = container.birthdayStr
        
        let profile = container.settingTextView.textView.text.trimmed
        viewModel.requestParams.aiUserExt?.profile = profile
        viewModel.requestParams.userProfile = profile
        
        let vc = styleSetController
        vc.viewModel = viewModel
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc private func tapBackButton() {
        close()
    }
    
    @objc private func tapGenerateButton(){
        guard container.nickname.trimmed.count > 0 else{
            Hud.toast(str: "请输入昵称")
            return
        }
        
        if container.settingContent.count > 0{
            let alert = Alert(title: "内容覆盖", text: "AI创建的内容会覆盖你已经填写的内容，请确认是否继续？")
            let action1 = AlertAction(title: "继续", actionStyle: .confirm) {[weak self] in
                self?.doGenerateAISettingContent()
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()
        }else{
            doGenerateAISettingContent()
        }
    }
    
    private func doGenerateAISettingContent(){
        Hud.showIndicator()
        var params = self.viewModel.requestParams.toPartialDictionary(keys: ["characterCode", "tagCode", "introduction"])
        // var params = [String:Any]()
        if container.settingContent.count > 0{
            params.updateValue(container.settingContent, forKey: "content")
        }
        
        if container.nickname.count > 0{
            params.updateValue(container.nickname, forKey: "nickname")
        }
        if let sex = container.sexSelect{
            params.updateValue(sex.rawValue, forKey: "sex")
        }
        if let birthdayStr = container.birthdayStr{
            params.updateValue(birthdayStr, forKey: "birthday")
        }
        
        params.updateValue("GEN_PROFILE_BY_NON", forKey: "ptType")

        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.settingAIGenerated = content
                    self?.viewModel.settingAIGenerated = true
                }
            case .failure:
                return
            }
        }
    }
}

