//Created  on 2019/8/24 by  LCD:https://github.com/liucaide .

/***** 模块文档 *****
 *
 */




import Foundation
import CaamDau
import SwiftyJSON


extension TWFileUpload {
    public class Model {
        public init(){}
        /// type 1 文件 2 图片
        open var type:Int = 1
        open var name = ""
        open var url:URL?
        open var icon:UIImage?
        
        open var isupload:Bool = false
        open var uploadurl:String = ""
        open var param:[String:Any] = [:]
    }
}


public class TWFileUpload {
    public init() {}
    let group = DispatchGroup()
    let queue = DispatchQueue(label: "uploadfile")
    let semaphore = DispatchSemaphore(value: 0)
    var maxCount = 1
    var hud:CD_HUDProgressView?
    var progress:Double = 0 {
        didSet{
            DispatchQueue.main.async { [weak self] in
                guard let self = self else{return}
                let pr = (self.progress * (100.0/self.maxCount.doubleValue)).intValue
                guard pr < 100 else {
                    CD.window?.cd.hud_remove(1)
                    return
                }
                self.hud?.progress = CGFloat((self.progress.floatValue * (100.0/self.maxCount.floatValue)))
            }
            
        }
    }
    
    var failures:[TWFileUpload.Model] = []
    var nextCallback:(()->Void)?
    public func uploadImages(_ list:[TWFileUpload.Model], nextCallback:(()->Void)? = nil, completion:((Bool)->Void)? = nil) {
        self.nextCallback = nextCallback
        let list = list.filter{!$0.isupload}.map{$0}
        maxCount = list.count
        guard maxCount > 0 else {
            completion?(true)
            return
        }
        failures.removeAll()
        CD.window?.cd.hud(.progress(.default(model: CD_HUDProgressView.Model(), handler: { [weak self](vv) in
            self?.hud = vv
        })), title: "上传文件")
        queue.async(group: group, qos: DispatchQoS.default) {[weak self] in
            for (i, item) in list.enumerated() {
                self?.upload(item, idx:i)
                self?.semaphore.wait()
            }
        }
        group.notify(queue: queue) {
            DispatchQueue.main.async { [weak self] in
                hud_hidden()
                guard let self = self else {return}
                if !self.failures.isEmpty {
                    hud_info(self.failures.count.stringValue + "个文件上传失败，请重试")
                }
                completion?(self.failures.isEmpty)
            }
        }
    }
    
    private func upload(_ model:TWFileUpload.Model, idx:Int) {
        var param = CD_Net.UploadParam()
        param.fileURL = model.url
        param.type = .file
        param.filename = model.name
        param.serverName = "file"
        param.mimeType = ""
        CD_Net()
            .baseURL(User.shared.info.app_file_upload_url)
            .uploadParameters([param])
            .uploadProgress({ [weak self](pro) in
                self?.progress = idx.doubleValue + pro.fractionCompleted
            })
            .success({ [weak self](res) in
                self?.progress = (idx + 1).doubleValue
                let json = JSON(res)
                guard json["success"].intValue == 2 else{
                    self?.semaphore.signal()
                    self?.failures.append(model)
                    DispatchQueue.main.async {
                        hud_error(json["error"].stringValue)
                    }
                    return
                }
                DispatchQueue.main.async {
                    self?.nextCallback?()
                }
                model.isupload = true
                model.uploadurl = json["url"].stringValue
                model.param = json.dictionaryObject ?? [:]
                self?.semaphore.signal()
            })
            .failure({ [weak self](error) in
                self?.semaphore.signal()
                self?.failures.append(model)
                DispatchQueue.main.async {
                    hud_error(error.massage)
                }
            })
            .upload()
        
    }
}
