//
//  ChatBackgroundGenerateInputController.swift

//
//  Created by Leon on 2025/8/26.
//

import UIKit


/// 聊天背景二创
class ChatBackgroundGenerateController: CLViewController<ChatBackgroundGenerateInputView> {
    var aiId : Int?
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDats()
        setupEvents()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {[weak self] in
            self?.container.scrollSelectedShow()
        }
    }
    
    private func setupViews() {
        navigationView.alpha0Title = "Create"
        
    }
    
    private func setupDats(){
        
    }
    
    private func setupEvents(){
        container.bottomButton.addTarget(self, action: #selector(bottomButtonTapped), for: .touchUpInside)
        container.generate1Button.addTarget(self, action: #selector(tapAIGenerated), for: .touchUpInside)
    }
    
    @objc private func bottomButtonTapped(regenerate:Bool = false) {
        var params = [String:Any]()
        
        if let aiUserId = aiId{
            params.updateValue(aiUserId, forKey: "aiId")
        }
        
        // imageStylePrompt  形象风格提示词（预设的几种）
        let imageStylePrompt = container.selectStylePrompt
        let imageStyleCode = container.selectStyleId
        params.updateValue(imageStylePrompt, forKey: "imageStylePrompt")
        
        // content：用户形象描述 or 生成的
        let description = container.descriptionTextView.textView.text.trimmed
        params.updateValue(description, forKey: "content")
        
        params.updateValue(AIImageGenerateType.BACKGROUND.rawValue, forKey: "type")
        
        params.updateValue(true, forKey: "hl")
        
        Hud.showIndicator()
        AICowProvider.request(.imageGenerateCreateTask(params: params), modelType: AIUserImageTaskCreateResponse.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let success):
                WalletCore.shared.refreshWallet()
                
                if let response = success, let batchNo = response.batchNo{
                    if regenerate {
                        self?.refreshBatchNoPhotos(batchNo, imageStyleCode, description)
                    }else{
                        self?.goResultVc(batchNo, imageStyleCode, description)
                    }
                }
            case .failure(let failure):
                dlog(failure)
            }
        }
        
        
    }
    
    // MARK: - Functions
    private func goResultVc(_ batchNo: String, _ imageStyleCode: String, _ description: String){
        let vc = ChatBackgroundResultGridController()
        vc.batchNo = batchNo
        vc.aiId = aiId
        vc.tapRegenerateAction = {[weak self] in
            let alert = Alert(title: "Give up creation", text: "已经创作的图片将消失，不会退还已消耗的Crush Coin。")
            let action1 = AlertAction(title: "重新生成", actionStyle: .confirm) {
                self?.bottomButtonTapped(regenerate: true)
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func refreshBatchNoPhotos(_ batchNo: String, _ imageStyleCode: String, _ description: String){
        guard let navc = UIWindow.getTopNavigationController() else{
            return
        }
        if let last = navc.viewControllers.last, last.isKind(of: ChatBackgroundResultGridController.self), let resultVc = last as? ChatBackgroundResultGridController{
            resultVc.refreshToken(photosNo: batchNo)
        }else{
            dlog("❌Check下RolePhotoGenerateController")
        }
    }
    
    
    @objc private func tapAIGenerated(){
        if container.figureDescriptionContent.count > 0{
            let alert = Alert(title: "内容覆盖", text: "AI创建的内容会覆盖你已经填写的内容，请确认是否继续？")
            let action1 = AlertAction(title: "继续", actionStyle: .confirm) {[weak self] in
                self?.doGenerateAlbumDesc()
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()
        }else{
            doGenerateAlbumDesc()
        }
    }
    
    private func doGenerateAlbumDesc(){
        
        guard let aiInfo = IMAIViewModel.shared.aiIMInfo else{
            return
        }
        
        var params = [String: Any]()
        
        if let aiId = aiInfo.aiId {
            params.updateValue(aiId, forKey: "aiId")
        }
        
        if let nickname = aiInfo.nickname{
            params.updateValue(nickname, forKey: "nickname")
        }
        
        if let sex = aiInfo.sex{
            params.updateValue(sex.rawValue, forKey: "sex")
        }
        
        if let birthday = aiInfo.birthday{
            let date = Date.dateFromMilliseconds(Int64(birthday))
            let birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            params.updateValue(birthdayStr, forKey: "birthday")
        }
        
        if let introduction = aiInfo.introduction{
            params.updateValue(introduction, forKey: "introduction")
        }
        
        let imageStylePrompt = container.selectStylePrompt
//        let imageStyleCode = container.selectStyleId
        params.updateValue(imageStylePrompt, forKey: "imageStylePrompt")
        
        /// 形象描述
        params.updateValue("GEN_AI_IMAGE_DESC_BY_NON", forKey: "ptType")
        if container.figureDescriptionContent.count > 0 {
            params.updateValue(container.figureDescriptionContent, forKey: "content")
        }
    
        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.figureDescriptionAIGenerated = content
                }
            case .failure:
                return
            }
        }
    }
    
}
