//Created  on 2019/7/27 by  LCD:https://github.com/liucaide .

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




import Foundation
import CaamDau
import SwiftyJSON
public class TWImagePickerUpload {
    public init() {}
    let group = DispatchGroup()
    let queue = DispatchQueue(label: "uploadimg")
    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:[TWImagePicker.Model] = []
    var nextCallback:(()->Void)?
    var uploadURL:String = User.shared.info.app_file_upload_url
    var urlkey:String = "url"
    public func uploadImages(_ list:[TWImagePicker.Model], url:String = User.shared.info.app_file_upload_url, urlkey:String = "url", nextCallback:(()->Void)? = nil, completion:((Bool)->Void)? = nil) {
        self.uploadURL = url
        self.urlkey = urlkey
        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:TWImagePicker.Model, idx:Int) {
        var param = CD_Net.UploadParam()
        /*if let url = model.url {
            param.fileURL = url
            param.type = .file
        }
        else */
        if let data = model.image?.jpegData(compressionQuality: 1) {
            param.fileData = data
            param.type = .data
            
            let originalImgSize = data.count/1024 as Int  //获取图片大小
            if originalImgSize>6999 {
                var newData:NSData
                newData = self.compressImageSize(image: model.image!)
                param.fileData = newData as Data
            }
        }else{
            self.semaphore.signal()
            self.failures.append(model)
            return
        }
        param.filename = CD.timestampNow.stringValue + ".jpg"
        param.serverName = "iconfile"
        param.mimeType = "image/jpeg"
        CD_Net()
            .baseURL(uploadURL)
            .uploadParameters([param])
            .uploadProgress({ [weak self](pro) in
                self?.progress = idx.doubleValue + pro.fractionCompleted
            })
            .success({ [weak self](res) in
                guard let self = self else{ return }
                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[self.urlkey].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()
        
    }
    
    
    //图片压缩 7000kb以下的图片控制在6000kb内
    func compressImageSize(image:UIImage) -> NSData{
        
        var zipImageData = image.jpegData(compressionQuality: 1.0)! 
        let originalImgSize = zipImageData.count/1024 as Int  //获取图片大小
        print("原始图片大小===: \(originalImgSize)")
        
        if originalImgSize>10000 {
            zipImageData = image.jpegData(compressionQuality: 0.5)!
        }else if originalImgSize>9000 {
            
            zipImageData = image.jpegData(compressionQuality: 0.6)!
        }else if originalImgSize>8000 {
            
            zipImageData = image.jpegData(compressionQuality: 0.7)!
            
        }else if originalImgSize>7000 {
            
            zipImageData = image.jpegData(compressionQuality: 0.8)!
        }
        
         print("压缩后图片大小===: \(zipImageData.count/1024 as Int)")
        
        return zipImageData as NSData
    }

}
