//
//  ChatBubbleGridController.swift

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

import UIKit

class ChatBubbleGridController: CLViewController<ChatBubbleGridView> {
    var aiId : Int?
    var selectChatBubbleCode: String?
    
    var data: IMChatSetting?
    override func viewDidLoad() {
        super.viewDidLoad()

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

    private func setupViews() {
        navigationView.setupBackButtonCloseIcon()
        navigationView.alpha0Title = "Chat Bubble"
    }
    
    private func setupDats(){
        loadBubbles()
    }
    
    private func loadBubbles(){
        guard let theAiId = aiId else{
            return
        }
        Hud.showIndicator()
        CommonProvider.request(.chatBubbleDict(aiId: theAiId), modelType: [IMChatBubble].self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let model):
                self?.container.config(model, selectCode: self?.selectChatBubbleCode)
            case .failure:
                break
            }
        }
    }
    
    private func setupEvents(){
        container.bottomButton.addTarget(self, action: #selector(tapOperateButton), for: .touchUpInside)
    }

    @objc private func tapOperateButton(){
        guard let theAiId = aiId, let code = container.selectCode, code.count > 0, let bubble = container.selectBubble else{
            return
        }
        
        if bubble.unlockType == .heartbeatLevel{
            guard let level = IMAIViewModel.shared.aiIMInfo?.aiUserHeartbeatRelation?.heartbeatLevel, level.isGreaterOrEqual(to: bubble.unlockHeartbeatLevel ?? .level1) else{
                let vc = HeartBeatLevelGridController()
                vc.aiId = theAiId
                navigationController?.pushViewController(vc, animated: true)
                return
            }
        }
        
        if bubble.unlockType == .member && UserCore.shared.user?.isMember == false{
            AppRouter.goVIPCenter()
            return
        }
        
        Hud.showIndicator()
        var params = [String:Any]()
        params.updateValue(theAiId, forKey: "aiId")
        params.updateValue(code, forKey: "code")
        AIRoleProvider.request(.chatBubbleSetup(params: params), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                NotificationCenter.post(name: .chatSettingBackgroundChanged)
                NotificationCenter.post(name: .chatSettingUpdated)
                self?.close(dismissFirst: true)
            case .failure:
                break
            }
        }
    }
}
