//
//  RolePhotoGenerateController.swift

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

import UIKit

/// 二创类型
enum RolePhotoGenerateType {
    case album // 相册创建
    case figure // 形象编辑
}

/// 和RoleFigureGenerateController类似的逻辑。 通过选择风格，输入描述词进行生图。
class RolePhotoGenerateController: RoleCreateBaseController<RolePhotoGenerateView> {

    var aiId: Int?
    var introduction: String?
    var sex: Sex?
    var birthday: Int?
    var birthdayString: String?
    
    // 可选
    var preSelectstyleCode: String? // 生图Style
    var prePhotoDesc: String? // Description

    /// 剩余二创
    var countResponse: UserCreateCountResponse?
    
    var regenerateType: RolePhotoGenerateType = .album
    
    var confirmSelectAction: ((String, String, [AIUserImageQuery]?)-> Void)?

    override class var shouldPresentThisVc: Bool {
        return true
    }
    
    convenience init(type: RolePhotoGenerateType){
        self.init()
        regenerateType = type
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDatas()
        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 = container.titleView.title
    }

    private func setupDatas() {
        loadCreateAlbumLeftCount()
        
        if let imageDesc = prePhotoDesc {
            container.figureDescriptionContent = imageDesc
        }
        
        if let styleCode = preSelectstyleCode{
            container.selectStyleId = styleCode
        }
        

        #if DEBUG
        testCreationUIStates()
        #endif
    }

    private func loadCreateAlbumLeftCount(_ complete: ((Bool)-> Void)? = nil) {
        Hud.showIndicator()
        UserProvider.request(.getUserCreateCount, modelType: UserCreateCountResponse.self) { [weak self] result in
            Hud.hideIndicator()
            switch result {
            case let .success(model):
                self?.countResponse = model
                self?.handleCountResponse(data: model)
                complete?(true)
            case .failure:
                complete?(false)
            }
        }
    }

    private func setupEvents() {
        container.bottomButton.addTarget(self, action: #selector(bottomButtonTapped), for: .touchUpInside)
        container.generate1Button.addTarget(self, action: #selector(tapAIGenerated), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifyCreateChanged), name: AppNotificationName.vipStateChange.notificationName, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notifyCreateChanged), name: AppNotificationName.buyCreditsOnce.notificationName, object: nil)
        
    }

    // MARK: - Functions

    private func handleCountResponse(data: UserCreateCountResponse?) {
        guard let countModel = data else { return }
        let leftFreeNum = max((countModel.freeNum ?? 0) - (countModel.usedFreeNum ?? 0), 0)
        let leftMemberNum = max((countModel.memberNum ?? 0) - (countModel.usedMemberNum ?? 0), 0)
        let leftBuyNum = max((countModel.buyNum ?? 0) - (countModel.usedBuyNum ?? 0), 0)

        let isMemeber = UserCore.shared.user?.isMember.boolValue ?? false
        
        container.handleCreationUI(freeNum: leftFreeNum, memberNum: leftMemberNum, buyNum: leftBuyNum, isMember: isMemeber)
//        #warning("test")
//        container.handleCreationUI(freeNum: 0, memberNum: 0, buyNum: 0, isMember: false)
    }

    private func goAlbumsResultVc(_ batchNo: String, _ imageStyleCode: String, _ description: String) {
        let vc = RolePhotoResultsPickController()//RolePhotoResultPickController()
        vc.batchNo = batchNo
        vc.aiId = aiId
        vc.regenerateType = regenerateType
        vc.tapRegenerateAction = { [weak self] in
            self?.bottomButtonTapped(regenerate: true)
        }
        
        vc.confirmSelectAction = {[weak self] imgQuerys in
            let styleCode = self?.container.selectStyleId ?? ""
            let picDescription = self?.container.figureDescriptionContent ?? ""
            
            self?.confirmSelectAction?(styleCode, picDescription, imgQuerys)
        }
        
        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: RolePhotoResultsPickController.self), let resultVc = last as? RolePhotoResultsPickController {
            resultVc.refreshToken(photosNo: batchNo)
        } else {
            dlog("❌Check下RolePhotoGenerateController")
        }
    }

    // MARK: - Action

    @objc private func tapAIGenerated() {
        view.endEditing(true)

        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() {
        var params = [String: Any]()

        // 需要introduction
        if let introduction = introduction {
            params.updateValue(introduction, forKey: "introduction")
        }
        
        if let sex = sex{
            params.updateValue(sex.rawValue, forKey: "sex")
        }
        
        if let birthday = birthday{
            let date = Date.dateFromMilliseconds(Int64(birthday))
            let birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            params.updateValue(birthdayStr, forKey: "birthday")
        }
        
        if let birthdayStr = birthdayString{
            params.updateValue(birthdayStr, forKey: "birthday")
        }

        /// 形象描述
        // 新需求： 总是覆盖
        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 let .success(success):
                if let content = success?.content {
                    self?.container.figureDescriptionAIGenerated = content
                }
            case .failure:
                return
            }
        }
    }

    /// 创建生成图片
    @objc private func bottomButtonTapped(regenerate: Bool = false) {
        guard let state = container.createState else { return }

        if state == .nonMemberNoQuota {
            // 去买会员
            CLPurchase.shared.showVIPSubscribeSheet()
            return
        } else if state == .vipUserNoQuota {
            // 买次数
            CLPurchase.shared.showBuyPhotoGeneratedCountSheet()
            return
        }

        var params = [String: Any]()

        if let aiUserId = aiId {
            params.updateValue(aiUserId, forKey: "aiId")
        }

        if let sex = sex {
            params.updateValue(sex.rawValue, forKey: "sex")
        }

        if let birthday = birthday {
            let date = Date.dateFromMilliseconds(Int64(birthday))
            let birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
            params.updateValue(birthdayStr, forKey: "birthday")
        }
        
        if let birthdayStr = birthdayString{
            params.updateValue(birthdayStr, forKey: "birthday")
        }

        // 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.ALBUM.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 let .success(success):
                if let response = success, let batchNo = response.batchNo {
//                    self?.generatedBatchNoAction?(batchNo, imageStyleCode, description)
//                    self?.viewModel.batchNo = batchNo
//                    self?.navigationController?.popViewController(animated: true)
                    if regenerate {
                        self?.refreshBatchNoPhotos(batchNo, imageStyleCode, description)
                    } else {
                        self?.goAlbumsResultVc(batchNo, imageStyleCode, description)
                    }
                    
                    self?.loadCreateAlbumLeftCount()
                }
            case let .failure(failure):
                dlog(failure)
            }
        }
    }
    
    // MARK: - Noti
    
    @objc private func notifyCreateChanged(){
        Hud.showIndicator()
        loadCreateAlbumLeftCount { result in
            Hud.hideIndicator()
        }
    }

    // MARK: - 测试方法

    var currentIndex = 0
    let testCases: [(freeNum: Int, memberNum: Int, buyNum: Int, isMember: Bool, description: String)] = [
        (5, 0, 0, false, "1免费用户有剩余次数"),
        (0, 3, 0, true, "2会员用户有剩余次数"),
        (0, 0, 2, false, "3购买用户有剩余次数"),
        (0, 0, 0, false, "4非会员次数用尽"),
        (0, 0, 0, true, "5会员用户次数用尽"),
    ]

    /// 测试不同状态的UI显示
    /// 用于快速验证各种用户状态下的界面表现
    private func testCreationUIStates() {
        navigationView.rightButton.isHidden = false
        navigationView.rightButton.setTitle("Test", for: .normal)
        navigationView.rightButton.setTitleColor(.white, for: .normal)
        navigationView.paddingRightForRightStack = 24
        navigationView.rightButton.addTarget(self, action: #selector(switchTestState), for: .touchUpInside)

        // 显示第一个测试状态
        // showTestState(at: currentIndex)
    }

    @objc private func switchTestState() {
        showTestState(at: currentIndex)
        
        let nextIndex = (currentIndex + 1) % testCases.count
        currentIndex = nextIndex
    }

    private func showTestState(at index: Int) {
        let testCase = testCases[index]
        let state = container.handleCreationUI(
            freeNum: testCase.freeNum,
            memberNum: testCase.memberNum,
            buyNum: testCase.buyNum,
            isMember: testCase.isMember
        )

        // 更新导航栏标题显示当前测试状态
        navigationItem.title = "测试: \(testCase.description)"

        // 打印状态信息到控制台
        print(" 测试状态 \(index + 1)/\(testCases.count): \(testCase.description)")
        print("   参数: freeNum=\(testCase.freeNum), memberNum=\(testCase.memberNum), buyNum=\(testCase.buyNum), isMember=\(testCase.isMember)")
        print("   状态: \(state)")

        // 显示Toast提示
        view.hideToast()
        view.makeToast("测试状态: \(testCase.description)", duration: 10.0, position: .top)
    }

    /// 快速测试单个状态
    /// - Parameters:
    ///   - freeNum: 免费次数
    ///   - memberNum: 会员次数
    ///   - buyNum: 购买次数
    ///   - isMember: 是否为会员
    ///   - description: 状态描述
    private func quickTestState(freeNum: Int, memberNum: Int, buyNum: Int, isMember: Bool, description: String) {
        let state = container.handleCreationUI(
            freeNum: freeNum,
            memberNum: memberNum,
            buyNum: buyNum,
            isMember: isMember
        )

        print("🧪 快速测试: \(description)")
        print("   状态: \(state)")

        view.makeToast("测试: \(description)", duration: 2.0, position: .top)
    }
}
