package com.bc_chat.bc_base.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import com.bc_chat.bc_base.R
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.zhaohaoting.framework.utils.DensityUtil
import com.zhaohaoting.framework.utils.file.FileUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.io.File

/**
 * Created by zhaoting on 2019/4/17.
 * Desc：
 */
object QrUtils {

    private var qrWidth: Int = 500


    /**
     * 当前sdcard没有缓存二维码 则重新保存 读取
     */
    fun createQrCode(context: Context, url: String, qrCodeStr: String, qrCodeName: String): Observable<String> {
        return Observable.create<Bitmap> {
            Glide.with(context)
                    .asBitmap()
                    .apply(RequestOptions().centerCrop().circleCrop())
                    .load(url)
                    .into(object : SimpleTarget<Bitmap>() {
                        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                            it.onNext(resource)
                        }
                    })
        }.subscribeOn(AndroidSchedulers.mainThread())
                .flatMap { resource ->
                    Observable.fromCallable<String> {
                        val drawable = context.resources.getDrawable(R.drawable.qr_code_logo_border)
                        val resource_border = FileUtils.getBitmapFromDrawable(drawable)
                        //创建图片副本
                        val bmCopy = Bitmap.createBitmap(resource.width, resource.height, Bitmap.Config.ARGB_8888)
                        val canvas = Canvas(bmCopy)
                        canvas.drawBitmap(
                                Bitmap.createScaledBitmap(resource, bmCopy.width - DensityUtil.dip2px(context, 6f), bmCopy.width - DensityUtil.dip2px(context, 6f), true),
                                DensityUtil.dip2px(context, 3f).toFloat(), DensityUtil.dip2px(context, 3f).toFloat(), null)
                        canvas.drawBitmap(
                                Bitmap.createScaledBitmap(resource_border, bmCopy.width, bmCopy.height, true),
                                0f, 0f, null)
                        val bitmapQrCode = EncodingUtils.createQRCode(qrCodeStr, qrWidth, qrWidth, bmCopy)
                        val qrfile: File = FileUtils.saveImageToGallery(bitmapQrCode, qrCodeName)
                        return@fromCallable qrfile.absolutePath
                    }
                }
    }
}