package com.yidian.shenghuoquan.newscontent.ui

import android.app.Activity
import android.content.ContentResolver
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.FileUtils
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
import com.yidian.common.constant.GlobalConstants
import com.yidian.common.utils.YdFileUtils
import com.yidian.shenghuoquan.newscontent.databinding.ActivityLifeAccountEnterpriseCertificationBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.httpbean.BusinessLicenseOCRBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.IBusinessLicenseOCRCallback
import com.yidian.shenghuoquan.newscontent.utils.KS3Core
import com.yidian.utils.ToastUtil
import java.io.File
import java.io.FileOutputStream

/**
 * author: yinjiacheng
 * date: 5/24/21 3:15 PM
 * description: 企业生活号认证
 */
class LifeAccountEnterpriseCertificationActivity :
    BaseActivity<ActivityLifeAccountEnterpriseCertificationBinding>() {

    companion object {
        private const val TAG = "BusinessLicenseOCR"
        private const val REQUEST_CODE_PERMISSIONS = 1000 //权限
        private const val REQUEST_CODE_ALBUM = 1001 //相册
        private const val REQUEST_CODE_CAMERA = 1002 //相机
        private const val FILE_PATH_BUSINESS_LICENSE_CAMERA = "/ocr/business_license_camera.jpg"
        private const val FILE_PATH_BUSINESS_LICENSE = "/ocr/business_license.jpg"
    }

    /**
     * 调用系统相机拍照，照片Uri
     */
    private lateinit var photoUri: Uri

    /**
     * 营业执照文件路径
     */
    private var filePath: String? = null

    override fun createViewBinding(): ActivityLifeAccountEnterpriseCertificationBinding {
        return ActivityLifeAccountEnterpriseCertificationBinding.inflate(layoutInflater)
    }

    override fun getXPageName(): String {
        return XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_CERTIFICATION
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        initListener()
    }

    private fun initListener() {
        viewBind.btnOpenAlbum.setOnClickListener {
            // 打开系统相册
            val intent = Intent()
            intent.action = Intent.ACTION_PICK
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
            startActivityForResult(intent, REQUEST_CODE_ALBUM)
        }

        viewBind.btnTakePhoto.setOnClickListener {
            val file = File(externalCacheDir?.absolutePath + FILE_PATH_BUSINESS_LICENSE_CAMERA)
            if (file.exists()) {
                file.delete()
            } else {
                file.parentFile?.mkdirs()
                file.createNewFile()
            }
            photoUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                FileProvider.getUriForFile(this, GlobalConstants.AUTHORITY, file)
            } else {
                Uri.fromFile(file)
            }
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            //android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            startActivityForResult(intent, REQUEST_CODE_CAMERA)
        }

        viewBind.btnOcr.setOnClickListener {
            KS3Core.INSTANCE.uploadObject(
                generateUploadFile(filePath),
                KS3Core.ObjectType.IMAGE,
                KS3Core.ScenarioType.BUSINESS_LICENSE,
                object : KS3Core.OnKS3TaskListener {
                    override fun onTaskStart() {

                    }

                    override fun onTaskProgress(progress: Double) {

                    }

                    override fun onTaskFinish() {

                    }

                    override fun onTaskCancel() {

                    }

                    override fun onTaskSuccess(bucket: String?, objectKey: String?) {
                        if (bucket == null || objectKey == null) return
                        val requestParams = HashMap<String, String?>()
                        requestParams["business_image_objectid"] = objectKey
                        requestParams["business_image_bucket"] = bucket
                        ApiService.businessLicenseOCR(object : IBusinessLicenseOCRCallback {
                            override fun businessLicenseOCRSuccess(result: BusinessLicenseOCRBean.Response?) {
                                Log.d(TAG, "name: ${result?.name}, code: ${result?.code}")
                                ToastUtil.showToast(this@LifeAccountEnterpriseCertificationActivity, "ocr result, name: ${result?.name}, code: ${result?.code}")
                            }

                            override fun businessLicenseOCRFailure(message: String?) {

                            }

                        }, requestParams)
                    }

                    override fun onTaskFailure(statesCode: Int, message: String?) {

                    }

                })
        }
    }

    /**
     * 通过Uri获取文件全路径
     * 适配Android Q
     */
    private fun getFilePathFromUri(uri: Uri?): String? {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val file = File(externalCacheDir?.absolutePath + FILE_PATH_BUSINESS_LICENSE)
            if (file.exists()) {
                file.delete()
            } else {
                file.parentFile?.mkdirs()
                file.createNewFile()
            }
            if (uri?.scheme == ContentResolver.SCHEME_CONTENT) {
                val inputStream = contentResolver.openInputStream(uri)
                val fileOutputStream = FileOutputStream(file)
                inputStream?.let { FileUtils.copy(it, fileOutputStream) }
                inputStream?.close()
                fileOutputStream.close()
                return file.absolutePath
            }
            return null
        } else {
            return YdFileUtils.getImageAbsolutePath(this, uri)
        }
    }

    /**
     * 生成金山云上传文件
     */
    private fun generateUploadFile(filePath: String?): File {
        BitmapFactory.decodeFile(filePath)
            .compress(Bitmap.CompressFormat.JPEG, 10, FileOutputStream(filePath))
        return File(filePath)
    }

    /**
     * 根据容器大小生成Bitmap
     *
     * @param filePath 本地文件路径
     */
    private fun generateBitmap(filePath: String?): Bitmap? {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, options)
        options.inSampleSize =
            calculateInSampleSize(options, viewBind.ivImage.width, viewBind.ivImage.height)
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }

    /**
     * 计算Bitmap inSampleSize
     *
     * @param targetWidth  容器宽
     * @param targetHeight 容器高
     */
    private fun calculateInSampleSize(
        options: BitmapFactory.Options,
        targetWidth: Int,
        targetHeight: Int
    ): Int {
        val sourceWidth = options.outWidth
        val sourceHeight = options.outHeight
        var inSampleSize = 1
        if (sourceWidth > targetWidth || sourceHeight > targetHeight) {
            val halfWidth = sourceWidth / 2
            val halfHeight = sourceHeight / 2
            // 压缩后的尺寸与所需的尺寸进行比较
            while (halfWidth / inSampleSize >= targetWidth && halfHeight / inSampleSize >= targetHeight) {
                inSampleSize *= 2
            }
        }
        return inSampleSize
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_ALBUM -> {
                    filePath = getFilePathFromUri(data?.data)
                    viewBind.ivImage.setImageBitmap(generateBitmap(filePath))
                }
                REQUEST_CODE_CAMERA -> {
                    filePath = getFilePathFromUri(photoUri)
                    viewBind.ivImage.setImageBitmap(generateBitmap(filePath))
                }
            }
        }
    }

}
