//
//  TSPTPGeneratorVM.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/25.
//
import Alamofire
class TSPTPGeneratorVM {
    
    var uploadRequest:Request?
    var creatRequest:Request?
    var queryRequest:Request?
    var stopNetwork = false
    
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
   
    var prompt:String
    var imageUrl:String?
    var upLoadImage:UIImage
    
    init(prompt:String,upLoadImage:UIImage) {
        self.prompt = prompt
        self.upLoadImage = upLoadImage
    }
    

    func creatImage() {
        
        guard let imageUrl = imageUrl else { return }
        
        stopNetwork = false
        stateDatauPblished = (.start,nil)
        creatRequest = TSNetworkShared.post(urlType: .imageRewrite,parameters: ["prompt":prompt,"imageUrl":imageUrl]) { [weak self] data,error in
            guard let self = self else { return }
            
            if let dataDict = data as? [String:Any] ,
               dataDict.safeInt(forKey: "code") == 200,
               let actionId = dataDict["actionId"] as? Int{
                if stopNetwork == false {
                    self.getActionInfo(action_id:actionId)
                }
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
    func getActionInfo(action_id:Int){
        queryRequest = TSNetworkShared.get(urlType: .actionInfo,parameters: ["action_id":action_id]) { [weak self] data,error in
            guard let self = self else { return }
            if let result = kNetWorkResultSuccess(data: data) {
                if let genmojiModel = TSGenmojiModel(JSON: result) {
                    switch genmojiModel.actionStatus {
                    case .success:
                        TSToastShared.hideLoading()
                        self.stateDatauPblished = (.success(nil),genmojiModel)
                    case .failed:
                        self.stateDatauPblished = (.failed(kNetWorkMessage(data: data) ?? ""),nil)
                    default:
                        if stopNetwork == false {
                            kDelayOnMainThread(1.0) {
                                self.getActionInfo(action_id: action_id)
                            }
                        }
                    }
                }
            }else{
                self.stateDatauPblished = (.failed(error?.localizedDescription ?? ""),nil)
            }
        }
    }
    
    
    func cancelAllRequest(){
        creatRequest?.cancel()
        queryRequest?.cancel()
        stopNetwork = true
    }
    
    
    func uploadAndCreatImage() {

        if let imageUrl = imageUrl,imageUrl.contains("http") {
            creatImage()
            return
        }
        
        stopNetwork = false
        stateDatauPblished = (.start,nil)
        uploadImage { progress in
            
        } completion: { [weak self]  data, error in
            guard let self = self else { return }
            if let error = error {
                imageUrl = nil
                self.stateDatauPblished = (.failed(error.localizedDescription),nil)
            }else{
                if let string = data as? String {
                    imageUrl = string
                    creatImage()
                }
            }
        }
    }
}


extension TSPTPGeneratorVM {
    func uploadImage(
        progressHandler: @escaping (Float) -> Void, // 上传进度回调
        completion: @escaping (Any?, Error?) -> Void)
    {
        guard let imageData = upLoadImage.pngData() else { return }
        stateDatauPblished = (.start,nil)
        let dataArray = [
            ["data": imageData,
             "fieldName": "file", // 字段名
             "fileName": "image.png", // 文件名
             "mimeType": "image/png" // MIME 类型
            ]
        ]
        
        uploadRequest = TSNetworkShared.uploadData(
            urlType: .upload,
            dataArray: dataArray,
            progressHandler: { progress in
                progressHandler(progress)
            },completion: { [weak self] result in
            guard let self = self else { return }
            switch result {
            case .success(let data):
                if let dataDict = data as? [String:Any] ,
                   dataDict.safeInt(forKey: "code") == 200,
                   let picUrl = dataDict["result"] as? String{
                    completion(picUrl,nil)
                }else{
                    let error = NSError(domain: "Service exception", code: 0)
                    completion(nil,error)
                }
            case .failure(let error):
                completion(nil,error)
            }
        })
    }
    
}
