//
//  RolePhotoResultsPickController.swift

//
//  Created by Leon on 2025/9/19.
//

import UIKit
import Combine

/// 二创选图
class RolePhotoResultsPickController: RoleCreateBaseController<RolePhotoResultsPickView> {
    var helpGhostButton: EPIconGhostButton!
    
    var batchNo: String! = ""
    var aiId: Int!
    
    var isAllImagesOK: Bool = false
    
    var regenerateType: RolePhotoGenerateType = .album
    
    var tapRegenerateAction: (()-> Void)?
    
    var confirmSelectAction:(([AIUserImageQuery]?) -> Void)?
    
    private var cancellables = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        container.regenerateType = regenerateType
        
        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.tapBackButtonAction = {[weak self] in
            self?.alertToExitNotSaved(dismissFirst: true)
        }
        
        if (regenerateType == .album){
            helpGhostButton = {
                let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .faq)
                v.addTarget(self, action: #selector(tapHelpButton), for: .touchUpInside)
                navigationView.rightStackH.addArrangedSubview(v)
                navigationView.paddingRightForRightStack = 16
                v.snp.makeConstraints { make in
                    make.size.equalTo(v.bgImageSize())
                }
                return v
            }()
        }
    }
    
    private func setupDatas(){
        if batchNo.count > 0{
            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(tapBottomButton), 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
            switch result {
            case .success(let 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: - Functions
    @objc private func doAddPicsToAlbum(){
        var params = [String:Any]()
        
        //...
        var request = AlbumPhotoBatchAddRequest()
        request.aiId = aiId
        var images = [AlbumPhotoBatchAddImage]()

        for per in container.selectImgs {
            var item = AlbumPhotoBatchAddImage()
            item.url = per.imageUrl ?? ""
            item.unlockPrice = per.unlockPrice ?? 0
            images.append(item)
        }
        
//        for per in container.appearanceResult.selectDatas {
//            var item = AlbumPhotoBatchAddImage()
//            item.url = per.imageUrl ?? ""
//            item.unlockPrice = container.price
//            images.append(item)
//        }
        request.images = images
        
        
        params = request.toNonNilDictionary()
        
        //dlog("params: \(params)")
        
        Hud.showIndicator()
        AIRoleProvider.request(.aiRoleBatchAddAlbum(params: params), modelType: EmptyModel?.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                NotificationCenter.post(name: .aiRoleAlbumAddOrDelete)
                self?.close(dismissFirst: true)
            case .failure:
                break
            }
        }
    }
    
    private func doConfirmSelectThis(){
        let imgs = container.selectImgs
        guard imgs.count > 0 else{
            return
        }
        
        confirmSelectAction?(imgs)
        self.close(dismissFirst: true)
    }
    
    // MARK: - Action
    /// 批量添加到相册
    @objc private func tapBottomButton(){
        switch regenerateType {
        case .album:
            doAddPicsToAlbum()
        case .figure:
            doConfirmSelectThis()
        }
    }
    
    
    @objc private func tapHelpButton(){
        let title = "Instructions"
        let content = "Interviewers can unlock the characters' pictures through paid methods, which can increase the creator's income share\nCrushlevel platform will share 20% of the sales revenue of each picture as the platform service fee\nSet up several free images that can attract interlocutors to interact with your virtual characters"
        
        let vc = UniversalInstructionsController()
        vc.pageTitle = title
        vc.content = content
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func tapBackButton(){
        alertToExitNotSaved(dismissFirst: false)
    }
    
    @objc private func alertToExitNotSaved(dismissFirst: Bool) {
        let alert = Alert(title: "放弃创作", text: "选择退出或重新生图片，已经创作的图片将消失，同时消耗1次创作次数。")
        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 tapRegenerate() {
        let alert = Alert(title: "放弃创作", text: "选择退出或重新生图片，已经创作的图片将消失，同时消耗1次创作次数。")
        let action1 = AlertAction(title: "重新生成", actionStyle: .confirm) { [weak self] in
            self?.doRegenerate()
        }
        let action2 = AlertAction(title: "Cancel", actionStyle: .cancel){
            // ...
        }
        alert.addAction(action1)
        alert.addAction(action2)
        alert.show()
    }
    
    @objc private func doRegenerate(){
        tapRegenerateAction?()
    }

}

extension RolePhotoResultsPickController:RolePhotoGenerateSetGridCellDelegate{
    func generateSetCellTapPrice(obj: AIUserImageQuery?) {
        let vc = RolePhotoUnlockWaySetController()
        vc.albumGenerated = obj
        vc.priceUpdateAction = { [weak self] price in
            let unlockPrice = price ?? 0
            obj?.unlockPrice = unlockPrice
            self?.container.reloadCv()
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
}
