package com.yzx.escreen.utils

import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.yzx.escreen.model.User
import com.yzx.escreen.config.YzxInterface
import org.json.JSONObject
import java.io.File

object FileUpload {

    fun upload(path: String, callBack: FileUploadCallBack) {
        val user = User.getUser()
        OkGo.post<String>(YzxInterface.FILE_UPLOAD_URL)
            .tag(this)
            .params("token", user.token)
            .params("user", user.user_id)
            .params("file", File(path))
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    try {
                        val noteJson = response.body()
                        val noteJsonObject = JSONObject(noteJson)
                        val noteContent = noteJsonObject.optString("content")
                        val noteContentObject = JSONObject(noteContent)
                        val noteKey = noteContentObject.optString("key")
                        val noteIdentity = noteContentObject.optString("identity")
                        callBack.onSuccess(noteIdentity, noteKey)
                    } catch (e: Exception) {
                    }
                }

                override fun onError(response: Response<String>) {
                    super.onError(response)
                    callBack.onError("上传失败")
                }

                override fun onFinish() {
                    super.onFinish()
                }
            })
    }
}

interface FileUploadCallBack {
    fun onSuccess(identity: String, key: String)
    fun onError(msg: String)
}