//
//  TSPTPStyleVM.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/25.
//
import Alamofire
import ObjectMapper
class TSPhotoToPhotoVM {
    
    var colDataArray:[TSComponent] = [TSComponent]()
    
    var uploadRequest:Request?
    @Published var stateDatauPblished:(TSProgressState,TSGenmojiModel?) = (TSProgressState.none,nil)
   

    //上传图片模型,用于上传图片参数的传递
    private var updateImageModel: TSPTPStyleModel = {
        var updateImageModel = TSPTPStyleModel()
        return updateImageModel
    }()
    
    var upLoadImageUrl:String?
    var upLoadImage:UIImage?{
        didSet{
            updateImageModel.image = upLoadImage
            upLoadImageUrl = nil
            isCanGennerateBlock?(isCanGennerate)
        }
    }
    
    var selectedPTPStyleModel:TSPTPStyleModel?{
        didSet{
            isCanGennerateBlock?(isCanGennerate)
        }
    }
    
    //选择类型组
    lazy var ptpStyleModels: [TSPTPStyleModel] = {
        var ptpStyleModels = [TSPTPStyleModel]()
        if let dataArray = Mapper<TSPTPStyleModel>().mapArray(JSONfile: "photo_to_photo_style.json"){
            ptpStyleModels = dataArray
            
            if let model = dataArray.first {
                selectedPTPStyleModel = model //加上默认的选择
            }
        }
        
        return ptpStyleModels
    }()
    //历史记录
    @UserDefault(key: "photoToPhotoHistoryListString", defaultValue: "")
    private var historyListString: String
    
    
    lazy var listModelArray: [TSGenmojiModel] = {
        if let listModelArray = Mapper<TSGenmojiModel>().mapArray(JSONString: historyListString){
            return listModelArray
        }
        return []
    }()
    
    lazy var uploadSectionModel: TSGenmojiCoLSectionModel = {
        let uploadSectionModel = TSGenmojiCoLSectionModel()
        uploadSectionModel.style = .ptpUpload
        uploadSectionModel.name = ""
        
        let itemModel = TSGenmojiCoLItemModel()
        itemModel.style = .ptpUpload
        itemModel.ptpStyleModels = [updateImageModel]
        
        uploadSectionModel.items = [itemModel]
        return uploadSectionModel
    }()
    
    
    lazy var styleSectionModel: TSGenmojiCoLSectionModel = {
        let styleSectionModel = TSGenmojiCoLSectionModel()
        styleSectionModel.style = .ptpSelectStyle
        styleSectionModel.name = "Select Style".localized
        
        let itemModel = TSGenmojiCoLItemModel()
        itemModel.style = .ptpSelectStyle
        itemModel.ptpStyleModels = ptpStyleModels
        styleSectionModel.items = [itemModel]
        
        return styleSectionModel
    }()
    
    lazy var historySeciton: TSGenmojiCoLSectionModel = {
        let sectionModel = TSGenmojiCoLSectionModel()
        sectionModel.style = .textPicHistory
        sectionModel.name = "History".localized
        for model in listModelArray {
            let itemModel = TSGenmojiCoLItemModel()
            itemModel.style = sectionModel.style
            itemModel.dataModel = model
            sectionModel.items.append(itemModel)
        }
        return sectionModel
    }()
    

    var isCanGennerate:Bool {
        if upLoadImage != nil , selectedPTPStyleModel != nil {
            return true
        }
        return false
    }
    
    var isCanGennerateBlock:((Bool)->Void)?
    init() {
        combinedData()
    }
    
    func combinedData(){
        colDataArray.removeAll()
        colDataArray.append(uploadSectionModel)
        colDataArray.append(styleSectionModel)
        
        if historySeciton.items.count > 0 {
            colDataArray.append(historySeciton)
        }
    }
    
}
 
extension TSPhotoToPhotoVM {
    //历史记录
    var modelArray:[TSGenmojiModel]{
        get{
            let sectionModel = TSGenmojiCoLSectionModel()
            sectionModel.style = .textPicHistory
            sectionModel.name = "History".localized
        
            if let modelArray = Mapper<TSGenmojiModel>().mapArray(JSONString: historyListString){
                return modelArray
            }
            return []
        }
        set{
            if let jsonString = newValue.toJSONString() {
                historyListString = jsonString
            }
        }
    }
    
    //返回值,是否需要清空后刷新
    func saveModel(model:TSGenmojiModel)->Bool{
        listModelArray.insert(model, at: 0)
        if let jsonString = listModelArray.toJSONString() {
            historyListString = jsonString
        }
        var isNeed = false
        if historySeciton.items.count == 0 {
            colDataArray.append(historySeciton)
            isNeed = true
        }
          
        let colItemModel = TSGenmojiCoLItemModel()
        colItemModel.style = .textPicHistory
        colItemModel.dataModel = model
        historySeciton.items.insert(colItemModel, at: 0)
        return isNeed
    }
    
    
    
    func removeAllHistoryList(){
        listModelArray.removeAll()
        if let jsonString = listModelArray.toJSONString() {
            historyListString = jsonString
        }
        
        historySeciton.items.removeAll()
        colDataArray.removeLast()
    }
    
}




extension TSPhotoToPhotoVM {
    func uploadImage(
        progressHandler: @escaping (Float) -> Void, // 上传进度回调
        completion: @escaping (Any?, Error?) -> Void)
    {
        guard let image = upLoadImage else { return }
        guard let imageData = image.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)
            }
        })
    }
    
}
