//
//  ChatBackgroundResultGridController.swift

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

import UIKit

class ChatBackgroundResultGridController: CLViewController<ChatBackgroundResultGridView> {
    var batchNo: String!
    var aiId: Int!

    var tapRegenerateAction: (() -> Void)?

    // -- Flag
    var isAllImagesOK: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupViews()
        setupDatas()
        setupEvents()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        disabledFullScreenPan()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        enabledFullScreenPan()
    }

    private func setupViews() {
        navigationView.alpha0Title = "Confirm the work"
        navigationView.setupBackButtonCloseIcon()
        navigationView.tapBackButtonAction = { [weak self] in
            self?.alertToExitNotSaved(dismissFirst: true)
        }
    }

    private func setupDatas() {
        Hud.showIndicator()
        container.setupLastGenerateProcessStart()
        loadingGeneratingResults(onbatchNo: batchNo)
    }

    private func setupEvents() {
        container.backButton.addTarget(self, action: #selector(tapBackButton), for: .touchUpInside)
        container.headView.generateButton.addTarget(self, action: #selector(tapRegenerate), for: .touchUpInside)
        container.bottomButton.addTarget(self, action: #selector(tapOperateButton), for: .touchUpInside)
    }

    // MARK: - Public

    func refreshToken(photosNo: String?) {
        self.batchNo = photosNo
        dlog("重新生成聊天背景中...")
        isAllImagesOK = false
        container.setupLastGenerateProcessStart()
        loadingGeneratingResults(onbatchNo: photosNo)
    }

    // MARK: - Functions

    func loadingGeneratingResults(onbatchNo: String?) {
        if isAllImagesOK {
            return
        }

        guard let queryNo = onbatchNo, queryNo.isEmpty == false else {
            dlog("❌batchNo is nil")
            return
        }

        if let lastBatchNo = batchNo, lastBatchNo != queryNo {
            dlog("⚠️换新的batchNo了，退出之前的查询")
            return
        }

        dlog("📖查询图片生成中...")
        AICowProvider.request(.imageGeneratedQuery(batchNo: queryNo), modelType: [AIUserImageQuery].self) { [weak self] result in
            Hud.hideIndicator()
            switch result {
            case let .success(success):
                guard let queryDatas = success else {
                    return
                }
                self?.container.config(success)
                var ok = true
                if queryDatas.count < 6 {
                    ok = false
                } else {
                    for per in queryDatas {
                        if per.status == .pending{
                            ok = false
                        }
                    }
                }
                self?.isAllImagesOK = ok
                if ok == false {
                    // ⚠️ seconds delay to query batch images
                    DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak self] in
                        self?.loadingGeneratingResults(onbatchNo: queryNo)
                    }
                }else{
                    self?.batchNo = ""
                    self?.container.setupLastGenerateProcessEnd()
                }
            case .failure:
                return
            }
        }
    }

    // MARK: - Action

    @objc private func alertToExitNotSaved(dismissFirst: Bool) {
        let alert = Alert(title: "Give up creation", text: "If you choose to opt out or regenerate the picture, the picture you have created will disappear and the Crush coin you have consumed will not be refunded.")
        let action1 = AlertAction(title: "确定", actionStyle: .destructive) { [weak self] in
            self?.close(dismissFirst: dismissFirst)
        }
        let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.show()
    }

    @objc private func tapBackButton() {
        //close()
        alertToExitNotSaved(dismissFirst: false)
    }

    @objc private func tapRegenerate() {
        tapRegenerateAction?()
    }

    @objc private func tapOperateButton() {
        guard container.selectImgs.count > 0 else {
            return
        }

        var params = [String: Any]()
        params.updateValue(aiId!, forKey: "aiId")

        var imgs = [[String:Any]]()
        for per in container.selectImgs {
            var image = TempBatchAddBackground()
            image.url = per.imageUrl
            imgs.append(image.toNonNilDictionary())
        }
        
        params.updateValue(imgs, forKey: "images")

        /*
         返回：
         {
           "ids" : [
             13
           ]
         }
         */
        AIRoleProvider.request(.batchAddChatBackground(params: params), modelType: EmptyModel.self) { [weak self] result in
            switch result {
            case .success:
                NotificationCenter.post(name: .chatSettingBackgroundListUpdated)
                self?.close(dismissFirst: true)
            case .failure:
                break
            }
        }
    }

    struct TempBatchAddBackground: Codable {
        var url: String?
        var width: String = "\(AppConst.gAIPhotoWidth)"
        var height: String = "\(AppConst.gAIPhotoHeight)"
    }
}
