package com.zswc.creativity.utils

import android.text.TextUtils
import android.util.Log
import com.google.gson.Gson
import com.zswc.creativity.R
import com.zswc.creativity.inte.OnCall
import com.zswc.creativity.inte.OnUploadCallback
import com.zswc.creativity.model.ImageSign
import com.zswc.creativity.model.KeyType
import com.zswc.creativity.utils.net.NetEngine
import com.ysnows.base.base.BViewModel
import com.ysnows.base.dialog.QMUIProgressDialog
import com.ysnows.base.view.BView
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import okhttp3.Call
import java.io.File
import java.util.*
import java.util.regex.Pattern

/**
 *Created by shihuiyun
 *on 2020/9/16
 */
class OssUtils(var bView: BView, val vm: BViewModel<*>) {

    /**
     * 获取sign
     *
     * @param onCall
     */
    fun getSign(type: String, onCall: OnCall<ImageSign>) {

        vm.repository().rxLreq(NetEngine.service.getSignedUrl(type))
                .doOnNext() {
                    onCall.onCall(it.data()!!)
                }.subscribe()
    }

    /**
     * url中是否含有中文
     *
     * @param str
     * @return
     */
    fun isContainChinese(str: String?): Boolean {
        val p = Pattern.compile("[\u4e00-\u9fa5]")
        val m = p.matcher(str)
        return m.find()
    }


    var key = ""
    fun setUpLoad(type: String, urls: ArrayList<String>, onUploadListener: OnUploadCallback<String>) {
        key = ""
        val size = intArrayOf(urls.size)
        if (size[0] <= 0) return
        val arr: HashMap<Int, KeyType> = HashMap<Int, KeyType>() //图片上次后的地址

        getSign(type, object : OnCall<ImageSign> {
            override fun onCall(imageSign: ImageSign) {

                val qmuiProgressDialog = arrayOfNulls<QMUIProgressDialog>(1)
                qmuiProgressDialog[0] = QMUIProgressDialog()
                if(null!=bView?.context()) {
                    qmuiProgressDialog[0]!!.show(bView!!.context())
                }

                val spe = "android/" + RandomUtils.getRandomOfLetter(1).toString() + "/"
                for (i in urls.indices) {
                    val index = urls[i].lastIndexOf("/")
                    var name: String //文件名字不能含有中文
                    name = if (isContainChinese(urls[i].substring(index + 1))) {
                        System.currentTimeMillis().toString() + ".jpg"
                    } else {
                        urls[i].substring(index + 1)
                    }
                    if (TextUtils.isEmpty(key)) {
                        key = imageSign.key
                    }
                    imageSign.key = key + spe + name
                    val request: HashMap<String, String> = HashMap<String, String>()
                    request["OSSAccessKeyId"] = imageSign.OSSAccessKeyId
                    request["policy"] = imageSign.policy
                    request["Signature"] = imageSign.Signature
                    request["host"] = imageSign.host
                    request["expire"] = imageSign.expire.toString()
                    request["success_action_status"] = imageSign.success_action_status.toString()
                    request["key"] = imageSign.key


                    val fileName = name //文件名
                    Log.e("-shy-", "fileName=: " + fileName)

                    Log.e("-shy-", "request=: " + Gson().toJson(request))

                    val requestCall = OkHttpUtils.post()
                            .url(imageSign.host)
                            .addFile("file", fileName, File(urls[i]))
                            .params(request)
                            .id(i)
                            .build()
                    val keyType = KeyType(imageSign.key)
                    arr[i] = keyType
                    requestCall.execute(object : StringCallback() {
                        override fun onError(call: Call, e: Exception, id: Int) {
                            bView.toast(bView.getStr(R.string.upload_pic_fail)+e)
                            Log.e("-shy-", "onError: $e")
                            size[0]--
                            if (size[0] <= 0) {
                               if(null!=bView?.context()) {
                                   qmuiProgressDialog[0]!!.dismiss()
                               }
                            }
                        }

                        override fun onResponse(response: String, id: Int) {
                            //地址
                            onUploadListener.onUploadSuccess(arr[id]!!.key + "," + imageSign.host + arr[id]!!.key)
                            size[0]--
                            if (size[0] <= 0) {
                                if(null!=bView?.context()) {
                                    qmuiProgressDialog[0]!!.dismiss()
                                }
                            }
                        }
                    })
                }
            }
        })

    }


}
