package com.abbidot.tracker.ui.activity

import android.content.Intent
import android.net.Uri
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityMyCropImageBinding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.canhub.cropper.CropImage
import com.canhub.cropper.CropImageView
import com.huantansheng.easyphotos.models.album.entity.Photo

/**
 * 裁剪图片
 */
class MyCropImageActivity :
    BaseActivity<ActivityMyCropImageBinding>(ActivityMyCropImageBinding::inflate),
    CropImageView.OnCropImageCompleteListener, CropImageView.OnSetImageUriCompleteListener {

    private val mTag = "裁剪图片"

    override fun getTopBar() = mViewBinding.photoCropImageBar.titleTopBar

    override fun initData() {
        super.initData()
        initStatus()

        var aspectRatioX = 1
        var aspectRatioY = 1
        var photo: Photo? = null
        intent.extras?.apply {
            aspectRatioX = getInt(ConstantString.Type, 1)
            aspectRatioY = getInt(ConstantString.Index, 1)
            photo = Util.getParcelableAdaptive(intent, ConstantString.Photo, Photo::class.java)
        }

        if (null == photo) {
            LogUtil.e(mTag, "null == photo")
        } else {
            mViewBinding.photoCropImageView.apply {
                setImageUriAsync(photo!!.uri)
                //最小裁剪框大小
//                setMinCropResultSize(10000, 10000)
                //裁剪的图片宽高比
                setAspectRatio(aspectRatioX, aspectRatioY)
                setOnCropImageCompleteListener(this@MyCropImageActivity)
                setOnSetImageUriCompleteListener(this@MyCropImageActivity)
            }
        }
    }

    private fun initStatus() {
        setTopBarTitle(R.string.txt_crop)
        mViewBinding.root.setBackgroundResource(R.color.crop_photos_status_bar)
        mTopBar?.titleView?.setTextColor(ContextCompat.getColor(mContext, R.color.white))
        setStatusBarDark()
        //设置沉浸状态栏颜色
//        mViewBinding.photoCropImageBar.titleTopBarLayout.setBackgroundResource(
//            R.color.crop_photos_status_bar
//        )
        setLeftBackImage(R.drawable.ico_cancel_detail)

        val rightTextButton =
            mTopBar!!.addRightTextButton(R.string.txt_sure, R.id.topbar_right_change_textview)
        rightTextButton.apply {
            setTextColor(ContextCompat.getColor(mContext, R.color.crop_images_fg_accent))
            background =
                ContextCompat.getDrawable(mContext, R.drawable.selector_transparent_pressed)
            val tf = ViewUtil.instance.setTypeface(mContext, getString(R.string.roboto_bold_font))
            typeface = tf
            setOnClickListener {
                mViewBinding.photoCropImageView.croppedImageAsync()
            }
        }
    }

    override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) {
        if (result.isSuccessful) {
            val uriContent = result.uriContent
            //uniqueName=true每个被裁剪的图像有一个不同的文件名，false始终只有一个文件名,节省内存
            val uriFilePath = result.getUriFilePath(mContext, false)
            LogUtil.d(mTag, "成功----------->$uriContent\n$uriFilePath")
        } else {
            val exception = result.error
            LogUtil.e(mTag, "error:${exception?.message}")
            showToast(exception?.message.toString())
        }

        setResult(result.uriContent, result.error, result.sampleSize)
    }


    private fun setResult(uri: Uri?, error: Exception?, sampleSize: Int) {
        setResult(error?.let { CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE } ?: RESULT_OK,
            getResultIntent(uri, error, sampleSize))
        finish()
    }

    /**
     * Get intent instance to be used for the result of this activity.
     */
    private fun getResultIntent(uri: Uri?, error: Exception?, sampleSize: Int): Intent {
        val cropImageView = mViewBinding.photoCropImageView
        val result = CropImage.ActivityResult(
            cropImageView.imageUri,
            uri,
            error,
            cropImageView.cropPoints,
            cropImageView.cropRect,
            cropImageView.rotatedDegrees ?: 0,
            cropImageView.wholeImageRect,
            sampleSize
        )
        val intent = Intent()
        intent.putExtras(getIntent())
        intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result)
        return intent
    }

    override fun onSetImageUriComplete(view: CropImageView, uri: Uri, error: Exception?) {
        if (null != error) {
            LogUtil.e(mTag, "加载原图uri错误,Failed to load image by URI, ------>${error.message}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBinding.photoCropImageView.setOnCropImageCompleteListener(null)
        mViewBinding.photoCropImageView.setOnSetImageUriCompleteListener(null)
    }
}